Move CInv to protocol.[ch]pp
[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     void AbortMessage()
291     {
292         if (nHeaderStart == -1)
293             return;
294         vSend.resize(nHeaderStart);
295         nHeaderStart = -1;
296         nMessageStart = -1;
297         cs_vSend.Leave();
298         printf("(aborted)\n");
299     }
300
301     void EndMessage()
302     {
303         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
304         {
305             printf("dropmessages DROPPING SEND MESSAGE\n");
306             AbortMessage();
307             return;
308         }
309
310         if (nHeaderStart == -1)
311             return;
312
313         // Set the size
314         unsigned int nSize = vSend.size() - nMessageStart;
315         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
316
317         // Set the checksum
318         if (vSend.GetVersion() >= 209)
319         {
320             uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
321             unsigned int nChecksum = 0;
322             memcpy(&nChecksum, &hash, sizeof(nChecksum));
323             assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
324             memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
325         }
326
327         printf("(%d bytes) ", nSize);
328         printf("\n");
329
330         nHeaderStart = -1;
331         nMessageStart = -1;
332         cs_vSend.Leave();
333     }
334
335     void EndMessageAbortIfEmpty()
336     {
337         if (nHeaderStart == -1)
338             return;
339         int nSize = vSend.size() - nMessageStart;
340         if (nSize > 0)
341             EndMessage();
342         else
343             AbortMessage();
344     }
345
346
347
348     void PushVersion()
349     {
350         /// when NTP implemented, change to just nTime = GetAdjustedTime()
351         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
352         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
353         CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
354         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
355         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
356                     nLocalHostNonce, std::string(pszSubVer), nBestHeight);
357     }
358
359
360
361
362     void PushMessage(const char* pszCommand)
363     {
364         try
365         {
366             BeginMessage(pszCommand);
367             EndMessage();
368         }
369         catch (...)
370         {
371             AbortMessage();
372             throw;
373         }
374     }
375
376     template<typename T1>
377     void PushMessage(const char* pszCommand, const T1& a1)
378     {
379         try
380         {
381             BeginMessage(pszCommand);
382             vSend << a1;
383             EndMessage();
384         }
385         catch (...)
386         {
387             AbortMessage();
388             throw;
389         }
390     }
391
392     template<typename T1, typename T2>
393     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
394     {
395         try
396         {
397             BeginMessage(pszCommand);
398             vSend << a1 << a2;
399             EndMessage();
400         }
401         catch (...)
402         {
403             AbortMessage();
404             throw;
405         }
406     }
407
408     template<typename T1, typename T2, typename T3>
409     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
410     {
411         try
412         {
413             BeginMessage(pszCommand);
414             vSend << a1 << a2 << a3;
415             EndMessage();
416         }
417         catch (...)
418         {
419             AbortMessage();
420             throw;
421         }
422     }
423
424     template<typename T1, typename T2, typename T3, typename T4>
425     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
426     {
427         try
428         {
429             BeginMessage(pszCommand);
430             vSend << a1 << a2 << a3 << a4;
431             EndMessage();
432         }
433         catch (...)
434         {
435             AbortMessage();
436             throw;
437         }
438     }
439
440     template<typename T1, typename T2, typename T3, typename T4, typename T5>
441     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
442     {
443         try
444         {
445             BeginMessage(pszCommand);
446             vSend << a1 << a2 << a3 << a4 << a5;
447             EndMessage();
448         }
449         catch (...)
450         {
451             AbortMessage();
452             throw;
453         }
454     }
455
456     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
457     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
458     {
459         try
460         {
461             BeginMessage(pszCommand);
462             vSend << a1 << a2 << a3 << a4 << a5 << a6;
463             EndMessage();
464         }
465         catch (...)
466         {
467             AbortMessage();
468             throw;
469         }
470     }
471
472     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
473     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)
474     {
475         try
476         {
477             BeginMessage(pszCommand);
478             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
479             EndMessage();
480         }
481         catch (...)
482         {
483             AbortMessage();
484             throw;
485         }
486     }
487
488     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
489     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)
490     {
491         try
492         {
493             BeginMessage(pszCommand);
494             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
495             EndMessage();
496         }
497         catch (...)
498         {
499             AbortMessage();
500             throw;
501         }
502     }
503
504     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
505     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)
506     {
507         try
508         {
509             BeginMessage(pszCommand);
510             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
511             EndMessage();
512         }
513         catch (...)
514         {
515             AbortMessage();
516             throw;
517         }
518     }
519
520
521     void PushRequest(const char* pszCommand,
522                      void (*fn)(void*, CDataStream&), void* param1)
523     {
524         uint256 hashReply;
525         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
526
527         CRITICAL_BLOCK(cs_mapRequests)
528             mapRequests[hashReply] = CRequestTracker(fn, param1);
529
530         PushMessage(pszCommand, hashReply);
531     }
532
533     template<typename T1>
534     void PushRequest(const char* pszCommand, const T1& a1,
535                      void (*fn)(void*, CDataStream&), void* param1)
536     {
537         uint256 hashReply;
538         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
539
540         CRITICAL_BLOCK(cs_mapRequests)
541             mapRequests[hashReply] = CRequestTracker(fn, param1);
542
543         PushMessage(pszCommand, hashReply, a1);
544     }
545
546     template<typename T1, typename T2>
547     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
548                      void (*fn)(void*, CDataStream&), void* param1)
549     {
550         uint256 hashReply;
551         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
552
553         CRITICAL_BLOCK(cs_mapRequests)
554             mapRequests[hashReply] = CRequestTracker(fn, param1);
555
556         PushMessage(pszCommand, hashReply, a1, a2);
557     }
558
559
560
561     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
562     bool IsSubscribed(unsigned int nChannel);
563     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
564     void CancelSubscribe(unsigned int nChannel);
565     void CloseSocketDisconnect();
566     void Cleanup();
567 };
568
569
570
571
572
573
574
575
576
577
578 inline void RelayInventory(const CInv& inv)
579 {
580     // Put on lists to offer to the other nodes
581     CRITICAL_BLOCK(cs_vNodes)
582         BOOST_FOREACH(CNode* pnode, vNodes)
583             pnode->PushInventory(inv);
584 }
585
586 template<typename T>
587 void RelayMessage(const CInv& inv, const T& a)
588 {
589     CDataStream ss(SER_NETWORK);
590     ss.reserve(10000);
591     ss << a;
592     RelayMessage(inv, ss);
593 }
594
595 template<>
596 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
597 {
598     CRITICAL_BLOCK(cs_mapRelay)
599     {
600         // Expire old relay messages
601         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
602         {
603             mapRelay.erase(vRelayExpiration.front().second);
604             vRelayExpiration.pop_front();
605         }
606
607         // Save original serialized message so newer versions are preserved
608         mapRelay[inv] = ss;
609         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
610     }
611
612     RelayInventory(inv);
613 }
614
615
616
617
618
619
620
621
622 //
623 // Templates for the publish and subscription system.
624 // The object being published as T& obj needs to have:
625 //   a set<unsigned int> setSources member
626 //   specializations of AdvertInsert and AdvertErase
627 // Currently implemented for CTable and CProduct.
628 //
629
630 template<typename T>
631 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
632 {
633     // Add to sources
634     obj.setSources.insert(pfrom->addr.ip);
635
636     if (!AdvertInsert(obj))
637         return;
638
639     // Relay
640     CRITICAL_BLOCK(cs_vNodes)
641         BOOST_FOREACH(CNode* pnode, vNodes)
642             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
643                 pnode->PushMessage("publish", nChannel, nHops, obj);
644 }
645
646 template<typename T>
647 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
648 {
649     uint256 hash = obj.GetHash();
650
651     CRITICAL_BLOCK(cs_vNodes)
652         BOOST_FOREACH(CNode* pnode, vNodes)
653             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
654                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
655
656     AdvertErase(obj);
657 }
658
659 template<typename T>
660 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
661 {
662     // Remove a source
663     obj.setSources.erase(pfrom->addr.ip);
664
665     // If no longer supported by any sources, cancel it
666     if (obj.setSources.empty())
667         AdvertStopPublish(pfrom, nChannel, nHops, obj);
668 }
669
670 #endif