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