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