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