log low-level network messages only when fDebug is set
[novacoin.git] / src / net.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_NET_H
6 #define BITCOIN_NET_H
7
8 #include <deque>
9 #include <boost/array.hpp>
10 #include <boost/foreach.hpp>
11 #include <openssl/rand.h>
12
13 #ifndef __WXMSW__
14 #include <arpa/inet.h>
15 #endif
16
17 #include "protocol.h"
18
19 class CAddrDB;
20 class CRequestTracker;
21 class CNode;
22 class CBlockIndex;
23 extern int nBestHeight;
24 extern int nConnectTimeout;
25
26
27
28 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
29 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
30 static const unsigned int PUBLISH_HOPS = 5;
31
32 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
33 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
34 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
35 bool GetMyExternalIP(unsigned int& ipRet);
36 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
37 void AddressCurrentlyConnected(const CAddress& addr);
38 CNode* FindNode(unsigned int ip);
39 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
40 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
41 bool AnySubscribed(unsigned int nChannel);
42 void MapPort(bool fMapPort);
43 void DNSAddressSeed();
44 bool BindListenPort(std::string& strError=REF(std::string()));
45 void StartNode(void* parg);
46 bool StopNode();
47
48 enum
49 {
50     MSG_TX = 1,
51     MSG_BLOCK,
52 };
53
54 class CRequestTracker
55 {
56 public:
57     void (*fn)(void*, CDataStream&);
58     void* param1;
59
60     explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
61     {
62         fn = fnIn;
63         param1 = param1In;
64     }
65
66     bool IsNull()
67     {
68         return fn == NULL;
69     }
70 };
71
72
73
74
75
76 extern bool fClient;
77 extern bool fAllowDNS;
78 extern uint64 nLocalServices;
79 extern CAddress addrLocalHost;
80 extern uint64 nLocalHostNonce;
81 extern boost::array<int, 10> vnThreadsRunning;
82
83 extern std::vector<CNode*> vNodes;
84 extern CCriticalSection cs_vNodes;
85 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
86 extern CCriticalSection cs_mapAddresses;
87 extern std::map<CInv, CDataStream> mapRelay;
88 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
89 extern CCriticalSection cs_mapRelay;
90 extern std::map<CInv, int64> mapAlreadyAskedFor;
91
92 // Settings
93 extern int fUseProxy;
94 extern CAddress addrProxy;
95
96
97
98
99
100
101 class CNode
102 {
103 public:
104     // socket
105     uint64 nServices;
106     SOCKET hSocket;
107     CDataStream vSend;
108     CDataStream vRecv;
109     CCriticalSection cs_vSend;
110     CCriticalSection cs_vRecv;
111     int64 nLastSend;
112     int64 nLastRecv;
113     int64 nLastSendEmpty;
114     int64 nTimeConnected;
115     unsigned int nHeaderStart;
116     unsigned int nMessageStart;
117     CAddress addr;
118     int nVersion;
119     std::string strSubVer;
120     bool fClient;
121     bool fInbound;
122     bool fNetworkNode;
123     bool fSuccessfullyConnected;
124     bool fDisconnect;
125 protected:
126     int nRefCount;
127 public:
128     int64 nReleaseTime;
129     std::map<uint256, CRequestTracker> mapRequests;
130     CCriticalSection cs_mapRequests;
131     uint256 hashContinue;
132     CBlockIndex* pindexLastGetBlocksBegin;
133     uint256 hashLastGetBlocksEnd;
134     int nStartingHeight;
135
136     // flood relay
137     std::vector<CAddress> vAddrToSend;
138     std::set<CAddress> setAddrKnown;
139     bool fGetAddr;
140     std::set<uint256> setKnown;
141
142     // inventory based relay
143     std::set<CInv> setInventoryKnown;
144     std::vector<CInv> vInventoryToSend;
145     CCriticalSection cs_inventory;
146     std::multimap<int64, CInv> mapAskFor;
147
148     // publish and subscription
149     std::vector<char> vfSubscribe;
150
151
152     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
153     {
154         nServices = 0;
155         hSocket = hSocketIn;
156         vSend.SetType(SER_NETWORK);
157         vSend.SetVersion(0);
158         vRecv.SetType(SER_NETWORK);
159         vRecv.SetVersion(0);
160         // Version 0.2 obsoletes 20 Feb 2012
161         if (GetTime() > 1329696000)
162         {
163             vSend.SetVersion(209);
164             vRecv.SetVersion(209);
165         }
166         nLastSend = 0;
167         nLastRecv = 0;
168         nLastSendEmpty = GetTime();
169         nTimeConnected = GetTime();
170         nHeaderStart = -1;
171         nMessageStart = -1;
172         addr = addrIn;
173         nVersion = 0;
174         strSubVer = "";
175         fClient = false; // set by version message
176         fInbound = fInboundIn;
177         fNetworkNode = false;
178         fSuccessfullyConnected = false;
179         fDisconnect = false;
180         nRefCount = 0;
181         nReleaseTime = 0;
182         hashContinue = 0;
183         pindexLastGetBlocksBegin = 0;
184         hashLastGetBlocksEnd = 0;
185         nStartingHeight = -1;
186         fGetAddr = false;
187         vfSubscribe.assign(256, false);
188
189         // Be shy and don't send version until we hear
190         if (!fInbound)
191             PushVersion();
192     }
193
194     ~CNode()
195     {
196         if (hSocket != INVALID_SOCKET)
197         {
198             closesocket(hSocket);
199             hSocket = INVALID_SOCKET;
200         }
201     }
202
203 private:
204     CNode(const CNode&);
205     void operator=(const CNode&);
206 public:
207
208
209     int GetRefCount()
210     {
211         return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
212     }
213
214     CNode* AddRef(int64 nTimeout=0)
215     {
216         if (nTimeout != 0)
217             nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
218         else
219             nRefCount++;
220         return this;
221     }
222
223     void Release()
224     {
225         nRefCount--;
226     }
227
228
229
230     void AddAddressKnown(const CAddress& addr)
231     {
232         setAddrKnown.insert(addr);
233     }
234
235     void PushAddress(const CAddress& addr)
236     {
237         // Known checking here is only to save space from duplicates.
238         // SendMessages will filter it again for knowns that were added
239         // after addresses were pushed.
240         if (addr.IsValid() && !setAddrKnown.count(addr))
241             vAddrToSend.push_back(addr);
242     }
243
244
245     void AddInventoryKnown(const CInv& inv)
246     {
247         CRITICAL_BLOCK(cs_inventory)
248             setInventoryKnown.insert(inv);
249     }
250
251     void PushInventory(const CInv& inv)
252     {
253         CRITICAL_BLOCK(cs_inventory)
254             if (!setInventoryKnown.count(inv))
255                 vInventoryToSend.push_back(inv);
256     }
257
258     void AskFor(const CInv& inv)
259     {
260         // We're using mapAskFor as a priority queue,
261         // the key is the earliest time the request can be sent
262         int64& nRequestTime = mapAlreadyAskedFor[inv];
263         printf("askfor %s   %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
264
265         // Make sure not to reuse time indexes to keep things in the same order
266         int64 nNow = (GetTime() - 1) * 1000000;
267         static int64 nLastTime;
268         nLastTime = nNow = std::max(nNow, ++nLastTime);
269
270         // Each retry is 2 minutes after the last
271         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
272         mapAskFor.insert(std::make_pair(nRequestTime, inv));
273     }
274
275
276
277     void BeginMessage(const char* pszCommand)
278     {
279         cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
280         if (nHeaderStart != -1)
281             AbortMessage();
282         nHeaderStart = vSend.size();
283         vSend << CMessageHeader(pszCommand, 0);
284         nMessageStart = vSend.size();
285         if (fDebug) {
286             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
287             printf("sending: %s ", pszCommand);
288         }
289     }
290
291     void AbortMessage()
292     {
293         if (nHeaderStart == -1)
294             return;
295         vSend.resize(nHeaderStart);
296         nHeaderStart = -1;
297         nMessageStart = -1;
298         cs_vSend.Leave();
299         printf("(aborted)\n");
300     }
301
302     void EndMessage()
303     {
304         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
305         {
306             printf("dropmessages DROPPING SEND MESSAGE\n");
307             AbortMessage();
308             return;
309         }
310
311         if (nHeaderStart == -1)
312             return;
313
314         // Set the size
315         unsigned int nSize = vSend.size() - nMessageStart;
316         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
317
318         // Set the checksum
319         if (vSend.GetVersion() >= 209)
320         {
321             uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
322             unsigned int nChecksum = 0;
323             memcpy(&nChecksum, &hash, sizeof(nChecksum));
324             assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
325             memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
326         }
327
328         if (fDebug) {
329             printf("(%d bytes) ", nSize);
330             printf("\n");
331         }
332
333         nHeaderStart = -1;
334         nMessageStart = -1;
335         cs_vSend.Leave();
336     }
337
338     void EndMessageAbortIfEmpty()
339     {
340         if (nHeaderStart == -1)
341             return;
342         int nSize = vSend.size() - nMessageStart;
343         if (nSize > 0)
344             EndMessage();
345         else
346             AbortMessage();
347     }
348
349
350
351     void PushVersion()
352     {
353         /// when NTP implemented, change to just nTime = GetAdjustedTime()
354         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
355         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
356         CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
357         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
358         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
359                     nLocalHostNonce, std::string(pszSubVer), nBestHeight);
360     }
361
362
363
364
365     void PushMessage(const char* pszCommand)
366     {
367         try
368         {
369             BeginMessage(pszCommand);
370             EndMessage();
371         }
372         catch (...)
373         {
374             AbortMessage();
375             throw;
376         }
377     }
378
379     template<typename T1>
380     void PushMessage(const char* pszCommand, const T1& a1)
381     {
382         try
383         {
384             BeginMessage(pszCommand);
385             vSend << a1;
386             EndMessage();
387         }
388         catch (...)
389         {
390             AbortMessage();
391             throw;
392         }
393     }
394
395     template<typename T1, typename T2>
396     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
397     {
398         try
399         {
400             BeginMessage(pszCommand);
401             vSend << a1 << a2;
402             EndMessage();
403         }
404         catch (...)
405         {
406             AbortMessage();
407             throw;
408         }
409     }
410
411     template<typename T1, typename T2, typename T3>
412     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
413     {
414         try
415         {
416             BeginMessage(pszCommand);
417             vSend << a1 << a2 << a3;
418             EndMessage();
419         }
420         catch (...)
421         {
422             AbortMessage();
423             throw;
424         }
425     }
426
427     template<typename T1, typename T2, typename T3, typename T4>
428     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
429     {
430         try
431         {
432             BeginMessage(pszCommand);
433             vSend << a1 << a2 << a3 << a4;
434             EndMessage();
435         }
436         catch (...)
437         {
438             AbortMessage();
439             throw;
440         }
441     }
442
443     template<typename T1, typename T2, typename T3, typename T4, typename T5>
444     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
445     {
446         try
447         {
448             BeginMessage(pszCommand);
449             vSend << a1 << a2 << a3 << a4 << a5;
450             EndMessage();
451         }
452         catch (...)
453         {
454             AbortMessage();
455             throw;
456         }
457     }
458
459     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
460     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
461     {
462         try
463         {
464             BeginMessage(pszCommand);
465             vSend << a1 << a2 << a3 << a4 << a5 << a6;
466             EndMessage();
467         }
468         catch (...)
469         {
470             AbortMessage();
471             throw;
472         }
473     }
474
475     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
476     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7)
477     {
478         try
479         {
480             BeginMessage(pszCommand);
481             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
482             EndMessage();
483         }
484         catch (...)
485         {
486             AbortMessage();
487             throw;
488         }
489     }
490
491     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
492     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8)
493     {
494         try
495         {
496             BeginMessage(pszCommand);
497             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
498             EndMessage();
499         }
500         catch (...)
501         {
502             AbortMessage();
503             throw;
504         }
505     }
506
507     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
508     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9)
509     {
510         try
511         {
512             BeginMessage(pszCommand);
513             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
514             EndMessage();
515         }
516         catch (...)
517         {
518             AbortMessage();
519             throw;
520         }
521     }
522
523
524     void PushRequest(const char* pszCommand,
525                      void (*fn)(void*, CDataStream&), void* param1)
526     {
527         uint256 hashReply;
528         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
529
530         CRITICAL_BLOCK(cs_mapRequests)
531             mapRequests[hashReply] = CRequestTracker(fn, param1);
532
533         PushMessage(pszCommand, hashReply);
534     }
535
536     template<typename T1>
537     void PushRequest(const char* pszCommand, const T1& a1,
538                      void (*fn)(void*, CDataStream&), void* param1)
539     {
540         uint256 hashReply;
541         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
542
543         CRITICAL_BLOCK(cs_mapRequests)
544             mapRequests[hashReply] = CRequestTracker(fn, param1);
545
546         PushMessage(pszCommand, hashReply, a1);
547     }
548
549     template<typename T1, typename T2>
550     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
551                      void (*fn)(void*, CDataStream&), void* param1)
552     {
553         uint256 hashReply;
554         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
555
556         CRITICAL_BLOCK(cs_mapRequests)
557             mapRequests[hashReply] = CRequestTracker(fn, param1);
558
559         PushMessage(pszCommand, hashReply, a1, a2);
560     }
561
562
563
564     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
565     bool IsSubscribed(unsigned int nChannel);
566     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
567     void CancelSubscribe(unsigned int nChannel);
568     void CloseSocketDisconnect();
569     void Cleanup();
570 };
571
572
573
574
575
576
577
578
579
580
581 inline void RelayInventory(const CInv& inv)
582 {
583     // Put on lists to offer to the other nodes
584     CRITICAL_BLOCK(cs_vNodes)
585         BOOST_FOREACH(CNode* pnode, vNodes)
586             pnode->PushInventory(inv);
587 }
588
589 template<typename T>
590 void RelayMessage(const CInv& inv, const T& a)
591 {
592     CDataStream ss(SER_NETWORK);
593     ss.reserve(10000);
594     ss << a;
595     RelayMessage(inv, ss);
596 }
597
598 template<>
599 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
600 {
601     CRITICAL_BLOCK(cs_mapRelay)
602     {
603         // Expire old relay messages
604         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
605         {
606             mapRelay.erase(vRelayExpiration.front().second);
607             vRelayExpiration.pop_front();
608         }
609
610         // Save original serialized message so newer versions are preserved
611         mapRelay[inv] = ss;
612         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
613     }
614
615     RelayInventory(inv);
616 }
617
618
619
620
621
622
623
624
625 //
626 // Templates for the publish and subscription system.
627 // The object being published as T& obj needs to have:
628 //   a set<unsigned int> setSources member
629 //   specializations of AdvertInsert and AdvertErase
630 // Currently implemented for CTable and CProduct.
631 //
632
633 template<typename T>
634 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
635 {
636     // Add to sources
637     obj.setSources.insert(pfrom->addr.ip);
638
639     if (!AdvertInsert(obj))
640         return;
641
642     // Relay
643     CRITICAL_BLOCK(cs_vNodes)
644         BOOST_FOREACH(CNode* pnode, vNodes)
645             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
646                 pnode->PushMessage("publish", nChannel, nHops, obj);
647 }
648
649 template<typename T>
650 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
651 {
652     uint256 hash = obj.GetHash();
653
654     CRITICAL_BLOCK(cs_vNodes)
655         BOOST_FOREACH(CNode* pnode, vNodes)
656             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
657                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
658
659     AdvertErase(obj);
660 }
661
662 template<typename T>
663 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
664 {
665     // Remove a source
666     obj.setSources.erase(pfrom->addr.ip);
667
668     // If no longer supported by any sources, cancel it
669     if (obj.setSources.empty())
670         AdvertStopPublish(pfrom, nChannel, nHops, obj);
671 }
672
673 #endif