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