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