CAddrMan: stochastic address manager
[novacoin.git] / src / net.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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 WIN32
14 #include <arpa/inet.h>
15 #endif
16
17 #include "netbase.h"
18 #include "protocol.h"
19 #include "addrman.h"
20
21 class CAddrDB;
22 class CRequestTracker;
23 class CNode;
24 class CBlockIndex;
25 extern int nBestHeight;
26
27
28
29 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
30 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
31 static const unsigned int PUBLISH_HOPS = 5;
32
33 bool RecvLine(SOCKET hSocket, std::string& strLine);
34 bool GetMyExternalIP(CNetAddr& ipRet);
35 void AddressCurrentlyConnected(const CService& addr);
36 CNode* FindNode(const CNetAddr& ip);
37 CNode* FindNode(const CService& ip);
38 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
39 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
40 bool AnySubscribed(unsigned int nChannel);
41 void MapPort(bool fMapPort);
42 bool BindListenPort(std::string& strError=REF(std::string()));
43 void StartNode(void* parg);
44 bool StopNode();
45
46 enum
47 {
48     MSG_TX = 1,
49     MSG_BLOCK,
50 };
51
52 class CRequestTracker
53 {
54 public:
55     void (*fn)(void*, CDataStream&);
56     void* param1;
57
58     explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
59     {
60         fn = fnIn;
61         param1 = param1In;
62     }
63
64     bool IsNull()
65     {
66         return fn == NULL;
67     }
68 };
69
70
71
72 enum threadId
73 {
74     THREAD_SOCKETHANDLER,
75     THREAD_OPENCONNECTIONS,
76     THREAD_MESSAGEHANDLER,
77     THREAD_MINER,
78     THREAD_RPCSERVER,
79     THREAD_UPNP,
80     THREAD_DNSSEED,
81     THREAD_ADDEDCONNECTIONS,
82     THREAD_DUMPADDRESS,
83
84     THREAD_MAX
85 };
86
87 extern bool fClient;
88 extern bool fAllowDNS;
89 extern uint64 nLocalServices;
90 extern CAddress addrLocalHost;
91 extern uint64 nLocalHostNonce;
92 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
93 extern CAddrMan addrman;
94
95 extern std::vector<CNode*> vNodes;
96 extern CCriticalSection cs_vNodes;
97 extern std::map<CInv, CDataStream> mapRelay;
98 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
99 extern CCriticalSection cs_mapRelay;
100 extern std::map<CInv, int64> mapAlreadyAskedFor;
101
102
103
104
105
106
107
108 class CNode
109 {
110 public:
111     // socket
112     uint64 nServices;
113     SOCKET hSocket;
114     CDataStream vSend;
115     CDataStream vRecv;
116     CCriticalSection cs_vSend;
117     CCriticalSection cs_vRecv;
118     int64 nLastSend;
119     int64 nLastRecv;
120     int64 nLastSendEmpty;
121     int64 nTimeConnected;
122     unsigned int nHeaderStart;
123     unsigned int nMessageStart;
124     CAddress addr;
125     int nVersion;
126     std::string strSubVer;
127     bool fClient;
128     bool fInbound;
129     bool fNetworkNode;
130     bool fSuccessfullyConnected;
131     bool fDisconnect;
132 protected:
133     int nRefCount;
134
135     // Denial-of-service detection/prevention
136     // Key is ip address, value is banned-until-time
137     static std::map<CNetAddr, int64> setBanned;
138     static CCriticalSection cs_setBanned;
139     int nMisbehavior;
140
141 public:
142     int64 nReleaseTime;
143     std::map<uint256, CRequestTracker> mapRequests;
144     CCriticalSection cs_mapRequests;
145     uint256 hashContinue;
146     CBlockIndex* pindexLastGetBlocksBegin;
147     uint256 hashLastGetBlocksEnd;
148     int nStartingHeight;
149
150     // flood relay
151     std::vector<CAddress> vAddrToSend;
152     std::set<CAddress> setAddrKnown;
153     bool fGetAddr;
154     std::set<uint256> setKnown;
155
156     // inventory based relay
157     std::set<CInv> setInventoryKnown;
158     std::vector<CInv> vInventoryToSend;
159     CCriticalSection cs_inventory;
160     std::multimap<int64, CInv> mapAskFor;
161
162     // publish and subscription
163     std::vector<char> vfSubscribe;
164
165     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
166     {
167         nServices = 0;
168         hSocket = hSocketIn;
169         vSend.SetType(SER_NETWORK);
170         vRecv.SetType(SER_NETWORK);
171         vSend.SetVersion(209);
172         vRecv.SetVersion(209);
173         nLastSend = 0;
174         nLastRecv = 0;
175         nLastSendEmpty = GetTime();
176         nTimeConnected = GetTime();
177         nHeaderStart = -1;
178         nMessageStart = -1;
179         addr = addrIn;
180         nVersion = 0;
181         strSubVer = "";
182         fClient = false; // set by version message
183         fInbound = fInboundIn;
184         fNetworkNode = false;
185         fSuccessfullyConnected = false;
186         fDisconnect = false;
187         nRefCount = 0;
188         nReleaseTime = 0;
189         hashContinue = 0;
190         pindexLastGetBlocksBegin = 0;
191         hashLastGetBlocksEnd = 0;
192         nStartingHeight = -1;
193         fGetAddr = false;
194         vfSubscribe.assign(256, false);
195         nMisbehavior = 0;
196
197         // Be shy and don't send version until we hear
198         if (!fInbound)
199             PushVersion();
200     }
201
202     ~CNode()
203     {
204         if (hSocket != INVALID_SOCKET)
205         {
206             closesocket(hSocket);
207             hSocket = INVALID_SOCKET;
208         }
209     }
210
211 private:
212     CNode(const CNode&);
213     void operator=(const CNode&);
214 public:
215
216
217     int GetRefCount()
218     {
219         return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
220     }
221
222     CNode* AddRef(int64 nTimeout=0)
223     {
224         if (nTimeout != 0)
225             nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
226         else
227             nRefCount++;
228         return this;
229     }
230
231     void Release()
232     {
233         nRefCount--;
234     }
235
236
237
238     void AddAddressKnown(const CAddress& addr)
239     {
240         setAddrKnown.insert(addr);
241     }
242
243     void PushAddress(const CAddress& addr)
244     {
245         // Known checking here is only to save space from duplicates.
246         // SendMessages will filter it again for knowns that were added
247         // after addresses were pushed.
248         if (addr.IsValid() && !setAddrKnown.count(addr))
249             vAddrToSend.push_back(addr);
250     }
251
252
253     void AddInventoryKnown(const CInv& inv)
254     {
255         CRITICAL_BLOCK(cs_inventory)
256             setInventoryKnown.insert(inv);
257     }
258
259     void PushInventory(const CInv& inv)
260     {
261         CRITICAL_BLOCK(cs_inventory)
262             if (!setInventoryKnown.count(inv))
263                 vInventoryToSend.push_back(inv);
264     }
265
266     void AskFor(const CInv& inv)
267     {
268         // We're using mapAskFor as a priority queue,
269         // the key is the earliest time the request can be sent
270         int64& nRequestTime = mapAlreadyAskedFor[inv];
271         printf("askfor %s   %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
272
273         // Make sure not to reuse time indexes to keep things in the same order
274         int64 nNow = (GetTime() - 1) * 1000000;
275         static int64 nLastTime;
276         ++nLastTime;
277         nNow = std::max(nNow, nLastTime);
278         nLastTime = nNow;
279
280         // Each retry is 2 minutes after the last
281         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
282         mapAskFor.insert(std::make_pair(nRequestTime, inv));
283     }
284
285
286
287     void BeginMessage(const char* pszCommand)
288     {
289         ENTER_CRITICAL_SECTION(cs_vSend);
290         if (nHeaderStart != -1)
291             AbortMessage();
292         nHeaderStart = vSend.size();
293         vSend << CMessageHeader(pszCommand, 0);
294         nMessageStart = vSend.size();
295         if (fDebug) {
296             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
297             printf("sending: %s ", pszCommand);
298         }
299     }
300
301     void AbortMessage()
302     {
303         if (nHeaderStart == -1)
304             return;
305         vSend.resize(nHeaderStart);
306         nHeaderStart = -1;
307         nMessageStart = -1;
308         LEAVE_CRITICAL_SECTION(cs_vSend);
309
310         if (fDebug)
311             printf("(aborted)\n");
312     }
313
314     void EndMessage()
315     {
316         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
317         {
318             printf("dropmessages DROPPING SEND MESSAGE\n");
319             AbortMessage();
320             return;
321         }
322
323         if (nHeaderStart == -1)
324             return;
325
326         // Set the size
327         unsigned int nSize = vSend.size() - nMessageStart;
328         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
329
330         // Set the checksum
331         uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
332         unsigned int nChecksum = 0;
333         memcpy(&nChecksum, &hash, sizeof(nChecksum));
334         assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
335         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
336
337         if (fDebug) {
338             printf("(%d bytes)\n", nSize);
339         }
340
341         nHeaderStart = -1;
342         nMessageStart = -1;
343         LEAVE_CRITICAL_SECTION(cs_vSend);
344     }
345
346     void EndMessageAbortIfEmpty()
347     {
348         if (nHeaderStart == -1)
349             return;
350         int nSize = vSend.size() - nMessageStart;
351         if (nSize > 0)
352             EndMessage();
353         else
354             AbortMessage();
355     }
356
357
358
359     void PushVersion();
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     // Denial-of-service detection/prevention
570     // The idea is to detect peers that are behaving
571     // badly and disconnect/ban them, but do it in a
572     // one-coding-mistake-won't-shatter-the-entire-network
573     // way.
574     // IMPORTANT:  There should be nothing I can give a
575     // node that it will forward on that will make that
576     // node's peers drop it. If there is, an attacker
577     // can isolate a node and/or try to split the network.
578     // Dropping a node for sending stuff that is invalid
579     // now but might be valid in a later version is also
580     // dangerous, because it can cause a network split
581     // between nodes running old code and nodes running
582     // new code.
583     static void ClearBanned(); // needed for unit testing
584     static bool IsBanned(CNetAddr ip);
585     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
586 };
587
588
589
590
591
592
593
594
595
596
597 inline void RelayInventory(const CInv& inv)
598 {
599     // Put on lists to offer to the other nodes
600     CRITICAL_BLOCK(cs_vNodes)
601         BOOST_FOREACH(CNode* pnode, vNodes)
602             pnode->PushInventory(inv);
603 }
604
605 template<typename T>
606 void RelayMessage(const CInv& inv, const T& a)
607 {
608     CDataStream ss(SER_NETWORK);
609     ss.reserve(10000);
610     ss << a;
611     RelayMessage(inv, ss);
612 }
613
614 template<>
615 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
616 {
617     CRITICAL_BLOCK(cs_mapRelay)
618     {
619         // Expire old relay messages
620         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
621         {
622             mapRelay.erase(vRelayExpiration.front().second);
623             vRelayExpiration.pop_front();
624         }
625
626         // Save original serialized message so newer versions are preserved
627         mapRelay[inv] = ss;
628         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
629     }
630
631     RelayInventory(inv);
632 }
633
634
635
636
637
638
639
640
641 //
642 // Templates for the publish and subscription system.
643 // The object being published as T& obj needs to have:
644 //   a set<unsigned int> setSources member
645 //   specializations of AdvertInsert and AdvertErase
646 // Currently implemented for CTable and CProduct.
647 //
648
649 template<typename T>
650 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
651 {
652     // Add to sources
653     obj.setSources.insert(pfrom->addr.ip);
654
655     if (!AdvertInsert(obj))
656         return;
657
658     // Relay
659     CRITICAL_BLOCK(cs_vNodes)
660         BOOST_FOREACH(CNode* pnode, vNodes)
661             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
662                 pnode->PushMessage("publish", nChannel, nHops, obj);
663 }
664
665 template<typename T>
666 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
667 {
668     uint256 hash = obj.GetHash();
669
670     CRITICAL_BLOCK(cs_vNodes)
671         BOOST_FOREACH(CNode* pnode, vNodes)
672             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
673                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
674
675     AdvertErase(obj);
676 }
677
678 template<typename T>
679 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
680 {
681     // Remove a source
682     obj.setSources.erase(pfrom->addr.ip);
683
684     // If no longer supported by any sources, cancel it
685     if (obj.setSources.empty())
686         AdvertStopPublish(pfrom, nChannel, nHops, obj);
687 }
688
689 #endif