Replace BOOST_FOREACH with range loop.
[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 COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_NET_H
6 #define BITCOIN_NET_H
7
8 #include <limits>
9 #include <deque>
10 #ifndef Q_MOC_RUN
11 #include <boost/array.hpp>
12 #endif
13 #include <openssl/rand.h>
14
15 #ifndef WIN32
16 #include <arpa/inet.h>
17 #endif
18
19 #include "mruset.h"
20 #include "netbase.h"
21 #include "addrman.h"
22 #include "hash.h"
23
24 class CRequestTracker;
25 class CNode;
26 class CBlockIndex;
27 extern int nBestHeight;
28
29 const uint16_t nSocksDefault = 9050;
30 const uint16_t nPortZero = 0;
31
32
33 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
34 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
35
36 void AddOneShot(std::string strDest);
37 bool RecvLine(SOCKET hSocket, std::string& strLine);
38 bool GetMyExternalIP(CNetAddr& ipRet);
39 void AddressCurrentlyConnected(const CService& addr);
40 CNode* FindNode(const CNetAddr& ip);
41 CNode* FindNode(const CService& ip);
42 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
43 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
44 void MapPort();
45 unsigned short GetListenPort();
46 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
47 void StartNode(void* parg);
48 bool StopNode();
49
50 enum
51 {
52     LOCAL_NONE,   // unknown
53     LOCAL_IF,     // address a local interface listens on
54     LOCAL_BIND,   // address explicit bound to
55     LOCAL_IRC,    // address reported by IRC (deprecated)
56     LOCAL_HTTP,   // address reported by whatismyip.com and similar
57     LOCAL_MANUAL, // address explicitly specified (-externalip=)
58
59     LOCAL_MAX
60 };
61
62
63 bool IsPeerAddrLocalGood(CNode *pnode);
64 void AdvertiseLocal(CNode *pnode);
65 void SetLimited(enum Network net, bool fLimited = true);
66 bool IsLimited(enum Network net);
67 bool IsLimited(const CNetAddr& addr);
68 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
69 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
70 bool SeenLocal(const CService& addr);
71 bool IsLocal(const CService& addr);
72 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
73 bool IsReachable(const CNetAddr &addr);
74 void SetReachable(enum Network net, bool fFlag = true);
75 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
76
77
78 enum
79 {
80     MSG_TX = 1,
81     MSG_BLOCK
82 };
83
84 class CRequestTracker
85 {
86 public:
87     void (*fn)(void*, CDataStream&);
88     void* param1;
89
90     explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
91     {
92         fn = fnIn;
93         param1 = param1In;
94     }
95
96     bool IsNull()
97     {
98         return fn == NULL;
99     }
100 };
101
102
103 /** Thread types */
104 enum threadId
105 {
106     THREAD_SOCKETHANDLER,
107     THREAD_OPENCONNECTIONS,
108     THREAD_MESSAGEHANDLER,
109     THREAD_RPCLISTENER,
110     THREAD_DNSSEED,
111     THREAD_ADDEDCONNECTIONS,
112     THREAD_DUMPADDRESS,
113     THREAD_RPCHANDLER,
114     THREAD_MINTER,
115     THREAD_SCRIPTCHECK,
116     THREAD_NTP,
117     THREAD_IPCOLLECTOR,
118
119     THREAD_MAX
120 };
121
122 extern bool fClient;
123 extern bool fDiscover;
124 extern bool fNoListen;
125
126 extern bool fDiscover;
127 extern uint64_t nLocalServices;
128 extern uint64_t nLocalHostNonce;
129 extern CAddress addrSeenByPeer;
130 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
131 extern CAddrMan addrman;
132
133 extern std::vector<CNode*> vNodes;
134 extern CCriticalSection cs_vNodes;
135 extern std::vector<std::string> vAddedNodes;
136 extern CCriticalSection cs_vAddedNodes;
137 extern std::map<CInv, CDataStream> mapRelay;
138 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
139 extern CCriticalSection cs_mapRelay;
140 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
141
142
143
144
145 class CNodeStats
146 {
147 public:
148     uint64_t nServices;
149     int64_t nLastSend;
150     int64_t nLastRecv;
151     int64_t nTimeConnected;
152     std::string addrName;
153     int32_t nVersion;
154     std::string strSubVer;
155     bool fInbound;
156     int64_t nReleaseTime;
157     int32_t nStartingHeight;
158     int32_t nMisbehavior;
159     uint64_t nSendBytes;
160     uint64_t nRecvBytes;
161     bool fSyncNode;
162 };
163
164
165
166
167
168 /** Information about a peer */
169 class CNode
170 {
171 public:
172     // socket
173     uint64_t nServices;
174     SOCKET hSocket;
175     CDataStream vSend;
176     CDataStream vRecv;
177     uint64_t nSendBytes;
178     uint64_t nRecvBytes;
179     CCriticalSection cs_vSend;
180     CCriticalSection cs_vRecv;
181     int64_t nLastSend;
182     int64_t nLastRecv;
183     int64_t nLastSendEmpty;
184     int64_t nTimeConnected;
185     int32_t nHeaderStart;
186     uint32_t nMessageStart;
187     CAddress addr;
188     std::string addrName;
189     CService addrLocal;
190     int32_t nVersion;
191     std::string strSubVer;
192     bool fOneShot;
193     bool fClient;
194     bool fInbound;
195     bool fNetworkNode;
196     bool fSuccessfullyConnected;
197     bool fDisconnect;
198     CSemaphoreGrant grantOutbound;
199 protected:
200     int nRefCount;
201
202     // Denial-of-service detection/prevention
203     // Key is IP address, value is banned-until-time
204     static std::map<CNetAddr, int64_t> setBanned;
205     static CCriticalSection cs_setBanned;
206     int nMisbehavior;
207
208 public:
209     int64_t nReleaseTime;
210     std::map<uint256, CRequestTracker> mapRequests;
211     CCriticalSection cs_mapRequests;
212     uint256 hashContinue;
213     CBlockIndex* pindexLastGetBlocksBegin;
214     uint256 hashLastGetBlocksEnd;
215     int32_t nStartingHeight;
216     bool fStartSync;
217
218     // flood relay
219     std::vector<CAddress> vAddrToSend;
220     std::set<CAddress> setAddrKnown;
221     bool fGetAddr;
222     std::set<uint256> setKnown;
223     uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
224     int64_t nNextAddrSend;
225     int64_t nNextLocalAddrSend;
226     int64_t nNextInvSend;
227
228     // inventory based relay
229     mruset<CInv> setInventoryKnown;
230     std::vector<CInv> vInventoryToSend;
231     CCriticalSection cs_inventory;
232     std::multimap<int64_t, CInv> mapAskFor;
233
234     CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
235     {
236         nServices = 0;
237         hSocket = hSocketIn;
238         nLastSend = 0;
239         nLastRecv = 0;
240         nSendBytes = 0;
241         nRecvBytes = 0;
242         nLastSendEmpty = GetTime();
243         nTimeConnected = GetTime();
244         nHeaderStart = -1;
245         nMessageStart = std::numeric_limits<uint32_t>::max();
246         addr = addrIn;
247         addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
248         nVersion = 0;
249         strSubVer.clear();
250         fOneShot = false;
251         fClient = false; // set by version message
252         fInbound = fInboundIn;
253         fNetworkNode = false;
254         fSuccessfullyConnected = false;
255         fDisconnect = false;
256         nRefCount = 0;
257         nReleaseTime = 0;
258         hashContinue = 0;
259         pindexLastGetBlocksBegin = 0;
260         hashLastGetBlocksEnd = 0;
261         nStartingHeight = -1;
262         nNextLocalAddrSend = 0;
263         nNextAddrSend = 0;
264         nNextInvSend = 0;
265         fStartSync = false;
266         fGetAddr = false;
267         nMisbehavior = 0;
268         hashCheckpointKnown = 0;
269         setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
270
271         // Be shy and don't send version until we hear
272         if (hSocket != INVALID_SOCKET && !fInbound)
273             PushVersion();
274     }
275
276     ~CNode()
277     {
278         if (hSocket != INVALID_SOCKET)
279         {
280             CloseSocket(hSocket);
281         }
282     }
283
284
285 private:
286     // Network usage totals
287     static CCriticalSection cs_totalBytesRecv;
288     static CCriticalSection cs_totalBytesSent;
289     static uint64_t nTotalBytesRecv;
290     static uint64_t nTotalBytesSent;
291     CNode(const CNode&);
292     void operator=(const CNode&);
293 public:
294
295
296     int GetRefCount()
297     {
298         return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
299     }
300
301     CNode* AddRef(int64_t nTimeout=0)
302     {
303         if (nTimeout != 0)
304             nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
305         else
306             nRefCount++;
307         return this;
308     }
309
310     void Release()
311     {
312         nRefCount--;
313     }
314
315
316
317     void AddAddressKnown(const CAddress& addr)
318     {
319         setAddrKnown.insert(addr);
320     }
321
322     void PushAddress(const CAddress& addr)
323     {
324         // Known checking here is only to save space from duplicates.
325         // SendMessages will filter it again for knowns that were added
326         // after addresses were pushed.
327         if (addr.IsValid() && !setAddrKnown.count(addr))
328             vAddrToSend.push_back(addr);
329     }
330
331
332     void AddInventoryKnown(const CInv& inv)
333     {
334         {
335             LOCK(cs_inventory);
336             setInventoryKnown.insert(inv);
337         }
338     }
339
340     void PushInventory(const CInv& inv)
341     {
342         {
343             LOCK(cs_inventory);
344             if (!setInventoryKnown.count(inv))
345                 vInventoryToSend.push_back(inv);
346         }
347     }
348
349     void AskFor(const CInv& inv)
350     {
351         // We're using mapAskFor as a priority queue,
352         // the key is the earliest time the request can be sent
353         int64_t& nRequestTime = mapAlreadyAskedFor[inv];
354         if (fDebugNet)
355             printf("askfor %s   %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
356
357         // Make sure not to reuse time indexes to keep things in the same order
358         int64_t nNow = (GetTime() - 1) * 1000000;
359         static int64_t nLastTime;
360         ++nLastTime;
361         nNow = std::max(nNow, nLastTime);
362         nLastTime = nNow;
363
364         // Each retry is 2 minutes after the last
365         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
366         mapAskFor.insert(std::make_pair(nRequestTime, inv));
367     }
368
369
370
371     void BeginMessage(const char* pszCommand)
372     {
373         ENTER_CRITICAL_SECTION(cs_vSend);
374         if (nHeaderStart != -1)
375             AbortMessage();
376         nHeaderStart = (int32_t)vSend.size();
377         vSend << CMessageHeader(pszCommand, 0);
378         nMessageStart = (uint32_t)vSend.size();
379         if (fDebug)
380             printf("sending: %s ", pszCommand);
381     }
382
383     void AbortMessage()
384     {
385         if (nHeaderStart < 0)
386             return;
387         vSend.resize(nHeaderStart);
388         nHeaderStart = -1;
389         nMessageStart = std::numeric_limits<uint32_t>::max();
390         LEAVE_CRITICAL_SECTION(cs_vSend);
391
392         if (fDebug)
393             printf("(aborted)\n");
394     }
395
396     void EndMessage()
397     {
398         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
399         {
400             printf("dropmessages DROPPING SEND MESSAGE\n");
401             AbortMessage();
402             return;
403         }
404
405         if (nHeaderStart < 0)
406             return;
407
408         // Set the size
409         uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
410         memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
411
412         // Set the checksum
413         uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
414         uint32_t nChecksum = 0;
415         memcpy(&nChecksum, &hash, sizeof(nChecksum));
416         assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
417         memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
418
419         if (fDebug) {
420             printf("(%d bytes)\n", nSize);
421         }
422
423         nHeaderStart = -1;
424         nMessageStart = std::numeric_limits<uint32_t>::max();
425         LEAVE_CRITICAL_SECTION(cs_vSend);
426     }
427
428     void EndMessageAbortIfEmpty()
429     {
430         if (nHeaderStart < 0)
431             return;
432         int nSize = (int) vSend.size() - nMessageStart;
433         if (nSize > 0)
434             EndMessage();
435         else
436             AbortMessage();
437     }
438
439
440
441     void PushVersion();
442
443
444     void PushMessage(const char* pszCommand)
445     {
446         try
447         {
448             BeginMessage(pszCommand);
449             EndMessage();
450         }
451         catch (...)
452         {
453             AbortMessage();
454             throw;
455         }
456     }
457
458     template<typename T1>
459     void PushMessage(const char* pszCommand, const T1& a1)
460     {
461         try
462         {
463             BeginMessage(pszCommand);
464             vSend << a1;
465             EndMessage();
466         }
467         catch (...)
468         {
469             AbortMessage();
470             throw;
471         }
472     }
473
474     template<typename T1, typename T2>
475     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
476     {
477         try
478         {
479             BeginMessage(pszCommand);
480             vSend << a1 << a2;
481             EndMessage();
482         }
483         catch (...)
484         {
485             AbortMessage();
486             throw;
487         }
488     }
489
490     template<typename T1, typename T2, typename T3>
491     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
492     {
493         try
494         {
495             BeginMessage(pszCommand);
496             vSend << a1 << a2 << a3;
497             EndMessage();
498         }
499         catch (...)
500         {
501             AbortMessage();
502             throw;
503         }
504     }
505
506     template<typename T1, typename T2, typename T3, typename T4>
507     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
508     {
509         try
510         {
511             BeginMessage(pszCommand);
512             vSend << a1 << a2 << a3 << a4;
513             EndMessage();
514         }
515         catch (...)
516         {
517             AbortMessage();
518             throw;
519         }
520     }
521
522     template<typename T1, typename T2, typename T3, typename T4, typename T5>
523     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
524     {
525         try
526         {
527             BeginMessage(pszCommand);
528             vSend << a1 << a2 << a3 << a4 << a5;
529             EndMessage();
530         }
531         catch (...)
532         {
533             AbortMessage();
534             throw;
535         }
536     }
537
538     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
539     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
540     {
541         try
542         {
543             BeginMessage(pszCommand);
544             vSend << a1 << a2 << a3 << a4 << a5 << a6;
545             EndMessage();
546         }
547         catch (...)
548         {
549             AbortMessage();
550             throw;
551         }
552     }
553
554     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
555     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)
556     {
557         try
558         {
559             BeginMessage(pszCommand);
560             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
561             EndMessage();
562         }
563         catch (...)
564         {
565             AbortMessage();
566             throw;
567         }
568     }
569
570     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
571     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)
572     {
573         try
574         {
575             BeginMessage(pszCommand);
576             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
577             EndMessage();
578         }
579         catch (...)
580         {
581             AbortMessage();
582             throw;
583         }
584     }
585
586     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
587     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)
588     {
589         try
590         {
591             BeginMessage(pszCommand);
592             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
593             EndMessage();
594         }
595         catch (...)
596         {
597             AbortMessage();
598             throw;
599         }
600     }
601
602
603     void PushRequest(const char* pszCommand,
604                      void (*fn)(void*, CDataStream&), void* param1)
605     {
606         uint256 hashReply;
607         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
608
609         {
610             LOCK(cs_mapRequests);
611             mapRequests[hashReply] = CRequestTracker(fn, param1);
612         }
613
614         PushMessage(pszCommand, hashReply);
615     }
616
617     template<typename T1>
618     void PushRequest(const char* pszCommand, const T1& a1,
619                      void (*fn)(void*, CDataStream&), void* param1)
620     {
621         uint256 hashReply;
622         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
623
624         {
625             LOCK(cs_mapRequests);
626             mapRequests[hashReply] = CRequestTracker(fn, param1);
627         }
628
629         PushMessage(pszCommand, hashReply, a1);
630     }
631
632     template<typename T1, typename T2>
633     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
634                      void (*fn)(void*, CDataStream&), void* param1)
635     {
636         uint256 hashReply;
637         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
638
639         {
640             LOCK(cs_mapRequests);
641             mapRequests[hashReply] = CRequestTracker(fn, param1);
642         }
643
644         PushMessage(pszCommand, hashReply, a1, a2);
645     }
646
647
648
649     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
650     bool IsSubscribed(unsigned int nChannel);
651     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
652     void CancelSubscribe(unsigned int nChannel);
653     void CloseSocketDisconnect();
654     void Cleanup();
655
656
657     // Denial-of-service detection/prevention
658     // The idea is to detect peers that are behaving
659     // badly and disconnect/ban them, but do it in a
660     // one-coding-mistake-won't-shatter-the-entire-network
661     // way.
662     // IMPORTANT:  There should be nothing I can give a
663     // node that it will forward on that will make that
664     // node's peers drop it. If there is, an attacker
665     // can isolate a node and/or try to split the network.
666     // Dropping a node for sending stuff that is invalid
667     // now but might be valid in a later version is also
668     // dangerous, because it can cause a network split
669     // between nodes running old code and nodes running
670     // new code.
671     static void ClearBanned(); // needed for unit testing
672     static bool IsBanned(CNetAddr ip);
673     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
674     void copyStats(CNodeStats &stats);
675     // Network stats
676     static void RecordBytesRecv(uint64_t bytes);
677     static void RecordBytesSent(uint64_t bytes);
678
679     static uint64_t GetTotalBytesRecv();
680     static uint64_t GetTotalBytesSent();
681 };
682
683 inline void RelayInventory(const CInv& inv)
684 {
685     // Put on lists to offer to the other nodes
686     {
687         LOCK(cs_vNodes);
688         for(CNode* pnode :  vNodes)
689             pnode->PushInventory(inv);
690     }
691 }
692
693 class CTransaction;
694 void RelayTransaction(const CTransaction& tx, const uint256& hash);
695 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
696
697
698 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
699 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
700
701 #endif