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