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