shy patch from Hal
[novacoin.git] / net.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4
5 class CMessageHeader;
6 class CAddress;
7 class CInv;
8 class CRequestTracker;
9 class CNode;
10 class CBlockIndex;
11 extern int nBestHeight;
12
13
14
15 inline unsigned short GetDefaultPort() { return fTestNet ? htons(18333) : htons(8333); }
16 static const unsigned int PUBLISH_HOPS = 5;
17 enum
18 {
19     NODE_NETWORK = (1 << 0),
20 };
21
22
23
24
25 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
26 bool GetMyExternalIP(unsigned int& ipRet);
27 bool AddAddress(CAddress addr, int64 nTimePenalty=0);
28 void AddressCurrentlyConnected(const CAddress& addr);
29 CNode* FindNode(unsigned int ip);
30 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
31 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
32 bool AnySubscribed(unsigned int nChannel);
33 bool BindListenPort(string& strError=REF(string()));
34 void StartNode(void* parg);
35 bool StopNode();
36
37
38
39
40
41
42
43
44 //
45 // Message header
46 //  (4) message start
47 //  (12) command
48 //  (4) size
49 //  (4) checksum
50
51 extern char pchMessageStart[4];
52
53 class CMessageHeader
54 {
55 public:
56     enum { COMMAND_SIZE=12 };
57     char pchMessageStart[sizeof(::pchMessageStart)];
58     char pchCommand[COMMAND_SIZE];
59     unsigned int nMessageSize;
60     unsigned int nChecksum;
61
62     CMessageHeader()
63     {
64         memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
65         memset(pchCommand, 0, sizeof(pchCommand));
66         pchCommand[1] = 1;
67         nMessageSize = -1;
68         nChecksum = 0;
69     }
70
71     CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
72     {
73         memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
74         strncpy(pchCommand, pszCommand, COMMAND_SIZE);
75         nMessageSize = nMessageSizeIn;
76         nChecksum = 0;
77     }
78
79     IMPLEMENT_SERIALIZE
80     (
81         READWRITE(FLATDATA(pchMessageStart));
82         READWRITE(FLATDATA(pchCommand));
83         READWRITE(nMessageSize);
84         if (nVersion >= 209)
85             READWRITE(nChecksum);
86     )
87
88     string GetCommand()
89     {
90         if (pchCommand[COMMAND_SIZE-1] == 0)
91             return string(pchCommand, pchCommand + strlen(pchCommand));
92         else
93             return string(pchCommand, pchCommand + COMMAND_SIZE);
94     }
95
96     bool IsValid()
97     {
98         // Check start string
99         if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
100             return false;
101
102         // Check the command string for errors
103         for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
104         {
105             if (*p1 == 0)
106             {
107                 // Must be all zeros after the first zero
108                 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
109                     if (*p1 != 0)
110                         return false;
111             }
112             else if (*p1 < ' ' || *p1 > 0x7E)
113                 return false;
114         }
115
116         // Message size
117         if (nMessageSize > MAX_SIZE)
118         {
119             printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
120             return false;
121         }
122
123         return true;
124     }
125 };
126
127
128
129
130
131
132 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
133
134 class CAddress
135 {
136 public:
137     uint64 nServices;
138     unsigned char pchReserved[12];
139     unsigned int ip;
140     unsigned short port;
141
142     // disk and network only
143     unsigned int nTime;
144
145     // memory only
146     unsigned int nLastTry;
147
148     CAddress()
149     {
150         Init();
151     }
152
153     CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)
154     {
155         Init();
156         ip = ipIn;
157         port = (portIn == 0 ? GetDefaultPort() : portIn);
158         nServices = nServicesIn;
159     }
160
161     explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
162     {
163         Init();
164         ip = sockaddr.sin_addr.s_addr;
165         port = sockaddr.sin_port;
166         nServices = nServicesIn;
167     }
168
169     explicit CAddress(const char* pszIn, uint64 nServicesIn=NODE_NETWORK)
170     {
171         Init();
172         SetAddress(pszIn);
173         nServices = nServicesIn;
174     }
175
176     explicit CAddress(string strIn, uint64 nServicesIn=NODE_NETWORK)
177     {
178         Init();
179         SetAddress(strIn.c_str());
180         nServices = nServicesIn;
181     }
182
183     void Init()
184     {
185         nServices = NODE_NETWORK;
186         memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
187         ip = INADDR_NONE;
188         port = GetDefaultPort();
189         nTime = 100000000;
190         nLastTry = 0;
191     }
192
193     bool SetAddress(const char* pszIn)
194     {
195         ip = INADDR_NONE;
196         port = GetDefaultPort();
197         char psz[100];
198         strlcpy(psz, pszIn, sizeof(psz));
199         unsigned int a=0, b=0, c=0, d=0, e=0;
200         if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)
201             return false;
202         char* pszPort = strchr(psz, ':');
203         if (pszPort)
204         {
205             *pszPort++ = '\0';
206             port = htons(atoi(pszPort));
207             if (atoi(pszPort) < 0 || atoi(pszPort) > USHRT_MAX)
208                 port = htons(USHRT_MAX);
209         }
210         ip = inet_addr(psz);
211         return IsValid();
212     }
213
214     bool SetAddress(string strIn)
215     {
216         return SetAddress(strIn.c_str());
217     }
218
219     IMPLEMENT_SERIALIZE
220     (
221         if (fRead)
222             const_cast<CAddress*>(this)->Init();
223         if (nType & SER_DISK)
224             READWRITE(nVersion);
225         if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))
226             READWRITE(nTime);
227         READWRITE(nServices);
228         READWRITE(FLATDATA(pchReserved)); // for IPv6
229         READWRITE(ip);
230         READWRITE(port);
231     )
232
233     friend inline bool operator==(const CAddress& a, const CAddress& b)
234     {
235         return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
236                 a.ip   == b.ip &&
237                 a.port == b.port);
238     }
239
240     friend inline bool operator!=(const CAddress& a, const CAddress& b)
241     {
242         return (!(a == b));
243     }
244
245     friend inline bool operator<(const CAddress& a, const CAddress& b)
246     {
247         int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
248         if (ret < 0)
249             return true;
250         else if (ret == 0)
251         {
252             if (ntohl(a.ip) < ntohl(b.ip))
253                 return true;
254             else if (a.ip == b.ip)
255                 return ntohs(a.port) < ntohs(b.port);
256         }
257         return false;
258     }
259
260     vector<unsigned char> GetKey() const
261     {
262         CDataStream ss;
263         ss.reserve(18);
264         ss << FLATDATA(pchReserved) << ip << port;
265
266         #if defined(_MSC_VER) && _MSC_VER < 1300
267         return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
268         #else
269         return vector<unsigned char>(ss.begin(), ss.end());
270         #endif
271     }
272
273     struct sockaddr_in GetSockAddr() const
274     {
275         struct sockaddr_in sockaddr;
276         memset(&sockaddr, 0, sizeof(sockaddr));
277         sockaddr.sin_family = AF_INET;
278         sockaddr.sin_addr.s_addr = ip;
279         sockaddr.sin_port = port;
280         return sockaddr;
281     }
282
283     bool IsIPv4() const
284     {
285         return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
286     }
287
288     bool IsRoutable() const
289     {
290         return IsValid() &&
291             !(GetByte(3) == 10 ||
292               (GetByte(3) == 192 && GetByte(2) == 168) ||
293               GetByte(3) == 127 ||
294               GetByte(3) == 0);
295     }
296
297     bool IsValid() const
298     {
299         // Clean up 3-byte shifted addresses caused by garbage in size field
300         // of addr messages from versions before 0.2.9 checksum.
301         // Two consecutive addr messages look like this:
302         // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
303         // so if the first length field is garbled, it reads the second batch
304         // of addr misaligned by 3 bytes.
305         if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
306             return false;
307
308         return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
309     }
310
311     unsigned char GetByte(int n) const
312     {
313         return ((unsigned char*)&ip)[3-n];
314     }
315
316     string ToStringIPPort() const
317     {
318         return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
319     }
320
321     string ToStringIP() const
322     {
323         return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
324     }
325
326     string ToStringPort() const
327     {
328         return strprintf("%u", ntohs(port));
329     }
330
331     string ToStringLog() const
332     {
333         return "";
334     }
335
336     string ToString() const
337     {
338         return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
339     }
340
341     void print() const
342     {
343         printf("CAddress(%s)\n", ToString().c_str());
344     }
345 };
346
347
348
349
350
351
352
353 enum
354 {
355     MSG_TX = 1,
356     MSG_BLOCK,
357 };
358
359 static const char* ppszTypeName[] =
360 {
361     "ERROR",
362     "tx",
363     "block",
364 };
365
366 class CInv
367 {
368 public:
369     int type;
370     uint256 hash;
371
372     CInv()
373     {
374         type = 0;
375         hash = 0;
376     }
377
378     CInv(int typeIn, const uint256& hashIn)
379     {
380         type = typeIn;
381         hash = hashIn;
382     }
383
384     CInv(const string& strType, const uint256& hashIn)
385     {
386         int i;
387         for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
388         {
389             if (strType == ppszTypeName[i])
390             {
391                 type = i;
392                 break;
393             }
394         }
395         if (i == ARRAYLEN(ppszTypeName))
396             throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
397         hash = hashIn;
398     }
399
400     IMPLEMENT_SERIALIZE
401     (
402         READWRITE(type);
403         READWRITE(hash);
404     )
405
406     friend inline bool operator<(const CInv& a, const CInv& b)
407     {
408         return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
409     }
410
411     bool IsKnownType() const
412     {
413         return (type >= 1 && type < ARRAYLEN(ppszTypeName));
414     }
415
416     const char* GetCommand() const
417     {
418         if (!IsKnownType())
419             throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
420         return ppszTypeName[type];
421     }
422
423     string ToString() const
424     {
425         return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
426     }
427
428     void print() const
429     {
430         printf("CInv(%s)\n", ToString().c_str());
431     }
432 };
433
434
435
436
437
438 class CRequestTracker
439 {
440 public:
441     void (*fn)(void*, CDataStream&);
442     void* param1;
443
444     explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
445     {
446         fn = fnIn;
447         param1 = param1In;
448     }
449
450     bool IsNull()
451     {
452         return fn == NULL;
453     }
454 };
455
456
457
458
459
460 extern bool fClient;
461 extern uint64 nLocalServices;
462 extern CAddress addrLocalHost;
463 extern CNode* pnodeLocalHost;
464 extern uint64 nLocalHostNonce;
465 extern array<int, 10> vnThreadsRunning;
466 extern SOCKET hListenSocket;
467
468 extern vector<CNode*> vNodes;
469 extern CCriticalSection cs_vNodes;
470 extern map<vector<unsigned char>, CAddress> mapAddresses;
471 extern CCriticalSection cs_mapAddresses;
472 extern map<CInv, CDataStream> mapRelay;
473 extern deque<pair<int64, CInv> > vRelayExpiration;
474 extern CCriticalSection cs_mapRelay;
475 extern map<CInv, int64> mapAlreadyAskedFor;
476
477 // Settings
478 extern int fUseProxy;
479 extern CAddress addrProxy;
480
481
482
483
484
485
486 class CNode
487 {
488 public:
489     // socket
490     uint64 nServices;
491     SOCKET hSocket;
492     CDataStream vSend;
493     CDataStream vRecv;
494     CCriticalSection cs_vSend;
495     CCriticalSection cs_vRecv;
496     int64 nLastSend;
497     int64 nLastRecv;
498     int64 nLastSendEmpty;
499     int64 nTimeConnected;
500     unsigned int nHeaderStart;
501     unsigned int nMessageStart;
502     CAddress addr;
503     int nVersion;
504     string strSubVer;
505     bool fClient;
506     bool fInbound;
507     bool fNetworkNode;
508     bool fSuccessfullyConnected;
509     bool fDisconnect;
510 protected:
511     int nRefCount;
512 public:
513     int64 nReleaseTime;
514     map<uint256, CRequestTracker> mapRequests;
515     CCriticalSection cs_mapRequests;
516     uint256 hashContinue;
517     CBlockIndex* pindexLastGetBlocksBegin;
518     uint256 hashLastGetBlocksEnd;
519     int nStartingHeight;
520
521     // flood relay
522     vector<CAddress> vAddrToSend;
523     set<CAddress> setAddrKnown;
524     bool fGetAddr;
525     set<uint256> setKnown;
526
527     // inventory based relay
528     set<CInv> setInventoryKnown;
529     vector<CInv> vInventoryToSend;
530     CCriticalSection cs_inventory;
531     multimap<int64, CInv> mapAskFor;
532
533     // publish and subscription
534     vector<char> vfSubscribe;
535
536
537     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
538     {
539         nServices = 0;
540         hSocket = hSocketIn;
541         vSend.SetType(SER_NETWORK);
542         vSend.SetVersion(0);
543         vRecv.SetType(SER_NETWORK);
544         vRecv.SetVersion(0);
545         // Version 0.2 obsoletes 20 Feb 2012
546         if (GetTime() > 1329696000)
547         {
548             vSend.SetVersion(209);
549             vRecv.SetVersion(209);
550         }
551         nLastSend = 0;
552         nLastRecv = 0;
553         nLastSendEmpty = GetTime();
554         nTimeConnected = GetTime();
555         nHeaderStart = -1;
556         nMessageStart = -1;
557         addr = addrIn;
558         nVersion = 0;
559         strSubVer = "";
560         fClient = false; // set by version message
561         fInbound = fInboundIn;
562         fNetworkNode = false;
563         fSuccessfullyConnected = false;
564         fDisconnect = false;
565         nRefCount = 0;
566         nReleaseTime = 0;
567         hashContinue = 0;
568         pindexLastGetBlocksBegin = 0;
569         hashLastGetBlocksEnd = 0;
570         nStartingHeight = -1;
571         fGetAddr = false;
572         vfSubscribe.assign(256, false);
573
574         // Be shy and don't send version until we hear
575         if (!fInbound)
576             PushVersion();
577     }
578
579     ~CNode()
580     {
581         if (hSocket != INVALID_SOCKET)
582         {
583             closesocket(hSocket);
584             hSocket = INVALID_SOCKET;
585         }
586     }
587
588 private:
589     CNode(const CNode&);
590     void operator=(const CNode&);
591 public:
592
593
594     int GetRefCount()
595     {
596         return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
597     }
598
599     CNode* AddRef(int64 nTimeout=0)
600     {
601         if (nTimeout != 0)
602             nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
603         else
604             nRefCount++;
605         return this;
606     }
607
608     void Release()
609     {
610         nRefCount--;
611     }
612
613
614
615     void AddAddressKnown(const CAddress& addr)
616     {
617         setAddrKnown.insert(addr);
618     }
619
620     void PushAddress(const CAddress& addr)
621     {
622         // Known checking here is only to save space from duplicates.
623         // SendMessages will filter it again for knowns that were added
624         // after addresses were pushed.
625         if (addr.IsValid() && !setAddrKnown.count(addr))
626             vAddrToSend.push_back(addr);
627     }
628
629
630     void AddInventoryKnown(const CInv& inv)
631     {
632         CRITICAL_BLOCK(cs_inventory)
633             setInventoryKnown.insert(inv);
634     }
635
636     void PushInventory(const CInv& inv)
637     {
638         CRITICAL_BLOCK(cs_inventory)
639             if (!setInventoryKnown.count(inv))
640                 vInventoryToSend.push_back(inv);
641     }
642
643     void AskFor(const CInv& inv)
644     {
645         // We're using mapAskFor as a priority queue,
646         // the key is the earliest time the request can be sent
647         int64& nRequestTime = mapAlreadyAskedFor[inv];
648         printf("askfor %s   %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
649
650         // Make sure not to reuse time indexes to keep things in the same order
651         int64 nNow = (GetTime() - 1) * 1000000;
652         static int64 nLastTime;
653         nLastTime = nNow = max(nNow, ++nLastTime);
654
655         // Each retry is 2 minutes after the last
656         nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
657         mapAskFor.insert(make_pair(nRequestTime, inv));
658     }
659
660
661
662     void BeginMessage(const char* pszCommand)
663     {
664         cs_vSend.Enter();
665         if (nHeaderStart != -1)
666             AbortMessage();
667         nHeaderStart = vSend.size();
668         vSend << CMessageHeader(pszCommand, 0);
669         nMessageStart = vSend.size();
670         if (fDebug)
671             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
672         printf("sending: %s ", pszCommand);
673     }
674
675     void AbortMessage()
676     {
677         if (nHeaderStart == -1)
678             return;
679         vSend.resize(nHeaderStart);
680         nHeaderStart = -1;
681         nMessageStart = -1;
682         cs_vSend.Leave();
683         printf("(aborted)\n");
684     }
685
686     void EndMessage()
687     {
688         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
689         {
690             printf("dropmessages DROPPING SEND MESSAGE\n");
691             AbortMessage();
692             return;
693         }
694
695         if (nHeaderStart == -1)
696             return;
697
698         // Set the size
699         unsigned int nSize = vSend.size() - nMessageStart;
700         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
701
702         // Set the checksum
703         if (vSend.GetVersion() >= 209)
704         {
705             uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
706             unsigned int nChecksum = 0;
707             memcpy(&nChecksum, &hash, sizeof(nChecksum));
708             assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
709             memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
710         }
711
712         printf("(%d bytes) ", nSize);
713         printf("\n");
714
715         nHeaderStart = -1;
716         nMessageStart = -1;
717         cs_vSend.Leave();
718     }
719
720     void EndMessageAbortIfEmpty()
721     {
722         if (nHeaderStart == -1)
723             return;
724         int nSize = vSend.size() - nMessageStart;
725         if (nSize > 0)
726             EndMessage();
727         else
728             AbortMessage();
729     }
730
731
732
733     void PushVersion()
734     {
735         /// when NTP implemented, change to just nTime = GetAdjustedTime()
736         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
737         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
738         CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
739         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
740         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
741                 nLocalHostNonce, string(pszSubVer), nBestHeight);
742     }
743
744
745
746
747     void PushMessage(const char* pszCommand)
748     {
749         try
750         {
751             BeginMessage(pszCommand);
752             EndMessage();
753         }
754         catch (...)
755         {
756             AbortMessage();
757             throw;
758         }
759     }
760
761     template<typename T1>
762     void PushMessage(const char* pszCommand, const T1& a1)
763     {
764         try
765         {
766             BeginMessage(pszCommand);
767             vSend << a1;
768             EndMessage();
769         }
770         catch (...)
771         {
772             AbortMessage();
773             throw;
774         }
775     }
776
777     template<typename T1, typename T2>
778     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
779     {
780         try
781         {
782             BeginMessage(pszCommand);
783             vSend << a1 << a2;
784             EndMessage();
785         }
786         catch (...)
787         {
788             AbortMessage();
789             throw;
790         }
791     }
792
793     template<typename T1, typename T2, typename T3>
794     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
795     {
796         try
797         {
798             BeginMessage(pszCommand);
799             vSend << a1 << a2 << a3;
800             EndMessage();
801         }
802         catch (...)
803         {
804             AbortMessage();
805             throw;
806         }
807     }
808
809     template<typename T1, typename T2, typename T3, typename T4>
810     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
811     {
812         try
813         {
814             BeginMessage(pszCommand);
815             vSend << a1 << a2 << a3 << a4;
816             EndMessage();
817         }
818         catch (...)
819         {
820             AbortMessage();
821             throw;
822         }
823     }
824
825     template<typename T1, typename T2, typename T3, typename T4, typename T5>
826     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
827     {
828         try
829         {
830             BeginMessage(pszCommand);
831             vSend << a1 << a2 << a3 << a4 << a5;
832             EndMessage();
833         }
834         catch (...)
835         {
836             AbortMessage();
837             throw;
838         }
839     }
840
841     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
842     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
843     {
844         try
845         {
846             BeginMessage(pszCommand);
847             vSend << a1 << a2 << a3 << a4 << a5 << a6;
848             EndMessage();
849         }
850         catch (...)
851         {
852             AbortMessage();
853             throw;
854         }
855     }
856
857     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
858     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)
859     {
860         try
861         {
862             BeginMessage(pszCommand);
863             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
864             EndMessage();
865         }
866         catch (...)
867         {
868             AbortMessage();
869             throw;
870         }
871     }
872
873     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
874     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)
875     {
876         try
877         {
878             BeginMessage(pszCommand);
879             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
880             EndMessage();
881         }
882         catch (...)
883         {
884             AbortMessage();
885             throw;
886         }
887     }
888
889     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
890     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)
891     {
892         try
893         {
894             BeginMessage(pszCommand);
895             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
896             EndMessage();
897         }
898         catch (...)
899         {
900             AbortMessage();
901             throw;
902         }
903     }
904
905
906     void PushRequest(const char* pszCommand,
907                      void (*fn)(void*, CDataStream&), void* param1)
908     {
909         uint256 hashReply;
910         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
911
912         CRITICAL_BLOCK(cs_mapRequests)
913             mapRequests[hashReply] = CRequestTracker(fn, param1);
914
915         PushMessage(pszCommand, hashReply);
916     }
917
918     template<typename T1>
919     void PushRequest(const char* pszCommand, const T1& a1,
920                      void (*fn)(void*, CDataStream&), void* param1)
921     {
922         uint256 hashReply;
923         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
924
925         CRITICAL_BLOCK(cs_mapRequests)
926             mapRequests[hashReply] = CRequestTracker(fn, param1);
927
928         PushMessage(pszCommand, hashReply, a1);
929     }
930
931     template<typename T1, typename T2>
932     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
933                      void (*fn)(void*, CDataStream&), void* param1)
934     {
935         uint256 hashReply;
936         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
937
938         CRITICAL_BLOCK(cs_mapRequests)
939             mapRequests[hashReply] = CRequestTracker(fn, param1);
940
941         PushMessage(pszCommand, hashReply, a1, a2);
942     }
943
944
945
946     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
947     bool IsSubscribed(unsigned int nChannel);
948     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
949     void CancelSubscribe(unsigned int nChannel);
950     void CloseSocketDisconnect();
951     void Cleanup();
952 };
953
954
955
956
957
958
959
960
961
962
963 inline void RelayInventory(const CInv& inv)
964 {
965     // Put on lists to offer to the other nodes
966     CRITICAL_BLOCK(cs_vNodes)
967         foreach(CNode* pnode, vNodes)
968             pnode->PushInventory(inv);
969 }
970
971 template<typename T>
972 void RelayMessage(const CInv& inv, const T& a)
973 {
974     CDataStream ss(SER_NETWORK);
975     ss.reserve(10000);
976     ss << a;
977     RelayMessage(inv, ss);
978 }
979
980 template<>
981 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
982 {
983     CRITICAL_BLOCK(cs_mapRelay)
984     {
985         // Expire old relay messages
986         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
987         {
988             mapRelay.erase(vRelayExpiration.front().second);
989             vRelayExpiration.pop_front();
990         }
991
992         // Save original serialized message so newer versions are preserved
993         mapRelay[inv] = ss;
994         vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
995     }
996
997     RelayInventory(inv);
998 }
999
1000
1001
1002
1003
1004
1005
1006
1007 //
1008 // Templates for the publish and subscription system.
1009 // The object being published as T& obj needs to have:
1010 //   a set<unsigned int> setSources member
1011 //   specializations of AdvertInsert and AdvertErase
1012 // Currently implemented for CTable and CProduct.
1013 //
1014
1015 template<typename T>
1016 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1017 {
1018     // Add to sources
1019     obj.setSources.insert(pfrom->addr.ip);
1020
1021     if (!AdvertInsert(obj))
1022         return;
1023
1024     // Relay
1025     CRITICAL_BLOCK(cs_vNodes)
1026         foreach(CNode* pnode, vNodes)
1027             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1028                 pnode->PushMessage("publish", nChannel, nHops, obj);
1029 }
1030
1031 template<typename T>
1032 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1033 {
1034     uint256 hash = obj.GetHash();
1035
1036     CRITICAL_BLOCK(cs_vNodes)
1037         foreach(CNode* pnode, vNodes)
1038             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1039                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1040
1041     AdvertErase(obj);
1042 }
1043
1044 template<typename T>
1045 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1046 {
1047     // Remove a source
1048     obj.setSources.erase(pfrom->addr.ip);
1049
1050     // If no longer supported by any sources, cancel it
1051     if (obj.setSources.empty())
1052         AdvertStopPublish(pfrom, nChannel, nHops, obj);
1053 }