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