]> Git Repo - VerusCoin.git/blob - src/net.h
Merge remote-tracking branch 'asher/dev'
[VerusCoin.git] / src / net.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
8
9 #include "bloom.h"
10 #include "compat.h"
11 #include "hash.h"
12 #include "limitedmap.h"
13 #include "mruset.h"
14 #include "netbase.h"
15 #include "protocol.h"
16 #include "random.h"
17 #include "streams.h"
18 #include "sync.h"
19 #include "uint256.h"
20 #include "utilstrencodings.h"
21
22 #include <deque>
23 #include <stdint.h>
24
25 #ifndef _WIN32
26 #include <arpa/inet.h>
27 #endif
28
29 #include <boost/filesystem/path.hpp>
30 #include <boost/foreach.hpp>
31 #include <boost/signals2/signal.hpp>
32
33 class CAddrMan;
34 class CBlockIndex;
35 class CScheduler;
36 class CNode;
37
38 namespace boost {
39     class thread_group;
40 } // namespace boost
41
42 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
43 static const int PING_INTERVAL = 2 * 60;
44 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
45 static const int TIMEOUT_INTERVAL = 20 * 60;
46 /** The maximum number of entries in an 'inv' protocol message */
47 static const unsigned int MAX_INV_SZ = 50000;
48 /** The maximum number of new addresses to accumulate before announcing. */
49 static const unsigned int MAX_ADDR_TO_SEND = 1000;
50 /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */
51 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024;
52 /** Maximum length of strSubVer in `version` message */
53 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
54 /** -listen default */
55 static const bool DEFAULT_LISTEN = true;
56 /** The maximum number of entries in mapAskFor */
57 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
58 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
59 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
60 /** The maximum number of peer connections to maintain. */
61 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 384;
62 /** The period before a network upgrade activates, where connections to upgrading peers are preferred (in blocks). */
63 static const int NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD = 24 * 24 * 3;
64
65 unsigned int ReceiveFloodSize();
66 unsigned int SendBufferSize();
67
68 void AddOneShot(const std::string& strDest);
69 void AddressCurrentlyConnected(const CService& addr);
70 CNode* FindNode(const CNetAddr& ip);
71 CNode* FindNode(const CSubNet& subNet);
72 CNode* FindNode(const std::string& addrName);
73 CNode* FindNode(const CService& ip);
74 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
75 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
76 unsigned short GetListenPort();
77 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
78 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler);
79 bool StopNode();
80 void SocketSendData(CNode *pnode);
81
82 typedef int NodeId;
83
84 struct CombinerAll
85 {
86     typedef bool result_type;
87
88     template<typename I>
89     bool operator()(I first, I last) const
90     {
91         while (first != last) {
92             if (!(*first)) return false;
93             ++first;
94         }
95         return true;
96     }
97 };
98
99 // Signals for message handling
100 struct CNodeSignals
101 {
102     boost::signals2::signal<int ()> GetHeight;
103     boost::signals2::signal<bool (CNode*), CombinerAll> ProcessMessages;
104     boost::signals2::signal<bool (CNode*, bool), CombinerAll> SendMessages;
105     boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
106     boost::signals2::signal<void (NodeId)> FinalizeNode;
107 };
108
109
110 CNodeSignals& GetNodeSignals();
111
112
113 enum
114 {
115     LOCAL_NONE,   // unknown
116     LOCAL_IF,     // address a local interface listens on
117     LOCAL_BIND,   // address explicit bound to
118     LOCAL_UPNP,   // unused (was: address reported by UPnP)
119     LOCAL_MANUAL, // address explicitly specified (-externalip=)
120
121     LOCAL_MAX
122 };
123
124 bool IsPeerAddrLocalGood(CNode *pnode);
125 void AdvertizeLocal(CNode *pnode);
126 void SetLimited(enum Network net, bool fLimited = true);
127 bool IsLimited(enum Network net);
128 bool IsLimited(const CNetAddr& addr);
129 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
130 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
131 bool RemoveLocal(const CService& addr);
132 bool SeenLocal(const CService& addr);
133 bool IsLocal(const CService& addr);
134 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
135 bool IsReachable(enum Network net);
136 bool IsReachable(const CNetAddr &addr);
137 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
138
139
140 extern bool fDiscover;
141 extern bool fListen;
142 extern uint64_t nLocalServices;
143 extern uint64_t nLocalHostNonce;
144 extern CAddrMan addrman;
145 /** Maximum number of connections to simultaneously allow (aka connection slots) */
146 extern int nMaxConnections;
147
148 extern std::vector<CNode*> vNodes;
149 extern CCriticalSection cs_vNodes;
150 extern std::map<CInv, CDataStream> mapRelay;
151 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
152 extern CCriticalSection cs_mapRelay;
153 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
154
155 extern std::vector<std::string> vAddedNodes;
156 extern CCriticalSection cs_vAddedNodes;
157
158 extern NodeId nLastNodeId;
159 extern CCriticalSection cs_nLastNodeId;
160
161 /** Subversion as sent to the P2P network in `version` messages */
162 extern std::string strSubVersion;
163
164 struct LocalServiceInfo {
165     int nScore;
166     int nPort;
167 };
168
169 extern CCriticalSection cs_mapLocalHost;
170 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
171
172 class CNodeStats
173 {
174 public:
175     NodeId nodeid;
176     uint64_t nServices;
177     int64_t nLastSend;
178     int64_t nLastRecv;
179     int64_t nTimeConnected;
180     int64_t nTimeOffset;
181     std::string addrName;
182     int nVersion;
183     std::string cleanSubVer;
184     bool fInbound;
185     int nStartingHeight;
186     uint64_t nSendBytes;
187     uint64_t nRecvBytes;
188     bool fWhitelisted;
189     double dPingTime;
190     double dPingWait;
191     std::string addrLocal;
192 };
193
194
195
196
197 class CNetMessage {
198 public:
199     bool in_data;                   // parsing header (false) or data (true)
200
201     CDataStream hdrbuf;             // partially received header
202     CMessageHeader hdr;             // complete header
203     unsigned int nHdrPos;
204
205     CDataStream vRecv;              // received message data
206     unsigned int nDataPos;
207
208     int64_t nTime;                  // time (in microseconds) of message receipt.
209
210     CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
211         hdrbuf.resize(24);
212         in_data = false;
213         nHdrPos = 0;
214         nDataPos = 0;
215         nTime = 0;
216     }
217
218     bool complete() const
219     {
220         if (!in_data)
221             return false;
222         return (hdr.nMessageSize == nDataPos);
223     }
224
225     void SetVersion(int nVersionIn)
226     {
227         hdrbuf.SetVersion(nVersionIn);
228         vRecv.SetVersion(nVersionIn);
229     }
230
231     int readHeader(const char *pch, unsigned int nBytes);
232     int readData(const char *pch, unsigned int nBytes);
233 };
234
235
236
237
238
239 /** Information about a peer */
240 class CNode
241 {
242 public:
243     // socket
244     uint64_t nServices;
245     SOCKET hSocket;
246     CDataStream ssSend;
247     size_t nSendSize; // total size of all vSendMsg entries
248     size_t nSendOffset; // offset inside the first vSendMsg already sent
249     uint64_t nSendBytes;
250     std::deque<CSerializeData> vSendMsg;
251     CCriticalSection cs_vSend;
252
253     std::deque<CInv> vRecvGetData;
254     std::deque<CNetMessage> vRecvMsg;
255     CCriticalSection cs_vRecvMsg;
256     uint64_t nRecvBytes;
257     int nRecvVersion;
258
259     int64_t nLastSend;
260     int64_t nLastRecv;
261     int64_t nTimeConnected;
262     int64_t nTimeOffset;
263     CAddress addr;
264     std::string addrName;
265     CService addrLocal;
266     int nVersion;
267     int lasthdrsreq,sendhdrsreq;
268     // strSubVer is whatever byte array we read from the wire. However, this field is intended
269     // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
270     // store the sanitized version in cleanSubVer. The original should be used when dealing with
271     // the network or wire types and the cleaned string used when displayed or logged.
272     std::string strSubVer, cleanSubVer;
273     bool fWhitelisted; // This peer can bypass DoS banning.
274     bool fOneShot;
275     bool fClient;
276     bool fInbound;
277     bool fNetworkNode;
278     bool fSuccessfullyConnected;
279     bool fDisconnect;
280     // We use fRelayTxes for two purposes -
281     // a) it allows us to not relay tx invs before receiving the peer's version message
282     // b) the peer may tell us in its version message that we should not relay tx invs
283     //    until it has initialized its bloom filter.
284     bool fRelayTxes;
285     bool fSentAddr;
286     CSemaphoreGrant grantOutbound;
287     CCriticalSection cs_filter;
288     CBloomFilter* pfilter;
289
290     int nRefCount;
291     NodeId id;
292 protected:
293
294     // Denial-of-service detection/prevention
295     // Key is IP address, value is banned-until-time
296     static std::map<CSubNet, int64_t> setBanned;
297     static CCriticalSection cs_setBanned;
298
299     // Whitelisted ranges. Any node connecting from these is automatically
300     // whitelisted (as well as those connecting to whitelisted binds).
301     static std::vector<CSubNet> vWhitelistedRange;
302     static CCriticalSection cs_vWhitelistedRange;
303
304     // Basic fuzz-testing
305     void Fuzz(int nChance); // modifies ssSend
306
307 public:
308     // for PBaaS nodes, each node may be associated with the hash of a pubkey as a payment address to receive rewards for supporting a
309     // PBaaS chain
310     uint160 hashPaymentAddress;
311
312     uint256 hashContinue;
313     int nStartingHeight;
314
315     // flood relay
316     std::vector<CAddress> vAddrToSend;
317     CRollingBloomFilter addrKnown;
318     bool fGetAddr;
319     std::set<uint256> setKnown;
320
321     // inventory based relay
322     mruset<CInv> setInventoryKnown;
323     std::vector<CInv> vInventoryToSend;
324     CCriticalSection cs_inventory;
325     std::set<uint256> setAskFor;
326     std::multimap<int64_t, CInv> mapAskFor;
327
328     // Ping time measurement:
329     // The pong reply we're expecting, or 0 if no pong expected.
330     uint64_t nPingNonceSent;
331     // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
332     int64_t nPingUsecStart;
333     // Last measured round-trip time.
334     int64_t nPingUsecTime;
335     // Best measured round-trip time.
336     int64_t nMinPingUsecTime;
337     // Whether a ping is requested.
338     bool fPingQueued;
339
340     CNode(SOCKET hSocketIn, const CAddress &addrIn, const std::string &addrNameIn = "", bool fInboundIn = false);
341     ~CNode();
342
343 private:
344     // Network usage totals
345     static CCriticalSection cs_totalBytesRecv;
346     static CCriticalSection cs_totalBytesSent;
347     static uint64_t nTotalBytesRecv;
348     static uint64_t nTotalBytesSent;
349
350     CNode(const CNode&);
351     void operator=(const CNode&);
352
353 public:
354
355     NodeId GetId() const {
356       return id;
357     }
358
359     int GetRefCount()
360     {
361         assert(nRefCount >= 0);
362         return nRefCount;
363     }
364
365     // requires LOCK(cs_vRecvMsg)
366     unsigned int GetTotalRecvSize()
367     {
368         unsigned int total = 0;
369         BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
370             total += msg.vRecv.size() + 24;
371         return total;
372     }
373
374     // requires LOCK(cs_vRecvMsg)
375     bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
376
377     // requires LOCK(cs_vRecvMsg)
378     void SetRecvVersion(int nVersionIn)
379     {
380         nRecvVersion = nVersionIn;
381         BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
382             msg.SetVersion(nVersionIn);
383     }
384
385     CNode* AddRef()
386     {
387         nRefCount++;
388         return this;
389     }
390
391     void Release()
392     {
393         nRefCount--;
394     }
395
396
397
398     void AddAddressKnown(const CAddress& addr)
399     {
400         addrKnown.insert(addr.GetKey());
401     }
402
403     void PushAddress(const CAddress& addr)
404     {
405         // Known checking here is only to save space from duplicates.
406         // SendMessages will filter it again for knowns that were added
407         // after addresses were pushed.
408         if (addr.IsValid() && !addrKnown.contains(addr.GetKey())) {
409             if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
410                 vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
411             } else {
412                 vAddrToSend.push_back(addr);
413             }
414         }
415     }
416
417
418     void AddInventoryKnown(const CInv& inv)
419     {
420         {
421             LOCK(cs_inventory);
422             setInventoryKnown.insert(inv);
423         }
424     }
425
426     void PushInventory(const CInv& inv)
427     {
428         {
429             LOCK(cs_inventory);
430             if (!setInventoryKnown.count(inv))
431                 vInventoryToSend.push_back(inv);
432         }
433     }
434
435     void AskFor(const CInv& inv);
436
437     // TODO: Document the postcondition of this function.  Is cs_vSend locked?
438     void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
439
440     // TODO: Document the precondition of this function.  Is cs_vSend locked?
441     void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
442
443     // TODO: Document the precondition of this function.  Is cs_vSend locked?
444     void EndMessage() UNLOCK_FUNCTION(cs_vSend);
445
446     void PushVersion();
447
448
449     void PushMessage(const char* pszCommand)
450     {
451         try
452         {
453             BeginMessage(pszCommand);
454             EndMessage();
455         }
456         catch (...)
457         {
458             AbortMessage();
459             throw;
460         }
461     }
462
463     template<typename T1>
464     void PushMessage(const char* pszCommand, const T1& a1)
465     {
466         try
467         {
468             BeginMessage(pszCommand);
469             ssSend << a1;
470             EndMessage();
471         }
472         catch (...)
473         {
474             AbortMessage();
475             throw;
476         }
477     }
478
479     template<typename T1, typename T2>
480     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
481     {
482         try
483         {
484             BeginMessage(pszCommand);
485             ssSend << a1 << a2;
486             EndMessage();
487         }
488         catch (...)
489         {
490             AbortMessage();
491             throw;
492         }
493     }
494
495     template<typename T1, typename T2, typename T3>
496     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
497     {
498         try
499         {
500             BeginMessage(pszCommand);
501             ssSend << a1 << a2 << a3;
502             EndMessage();
503         }
504         catch (...)
505         {
506             AbortMessage();
507             throw;
508         }
509     }
510
511     template<typename T1, typename T2, typename T3, typename T4>
512     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
513     {
514         try
515         {
516             BeginMessage(pszCommand);
517             ssSend << a1 << a2 << a3 << a4;
518             EndMessage();
519         }
520         catch (...)
521         {
522             AbortMessage();
523             throw;
524         }
525     }
526
527     template<typename T1, typename T2, typename T3, typename T4, typename T5>
528     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
529     {
530         try
531         {
532             BeginMessage(pszCommand);
533             ssSend << a1 << a2 << a3 << a4 << a5;
534             EndMessage();
535         }
536         catch (...)
537         {
538             AbortMessage();
539             throw;
540         }
541     }
542
543     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
544     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
545     {
546         try
547         {
548             BeginMessage(pszCommand);
549             ssSend << a1 << a2 << a3 << a4 << a5 << a6;
550             EndMessage();
551         }
552         catch (...)
553         {
554             AbortMessage();
555             throw;
556         }
557     }
558
559     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
560     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)
561     {
562         try
563         {
564             BeginMessage(pszCommand);
565             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
566             EndMessage();
567         }
568         catch (...)
569         {
570             AbortMessage();
571             throw;
572         }
573     }
574
575     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
576     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)
577     {
578         try
579         {
580             BeginMessage(pszCommand);
581             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
582             EndMessage();
583         }
584         catch (...)
585         {
586             AbortMessage();
587             throw;
588         }
589     }
590
591     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
592     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)
593     {
594         try
595         {
596             BeginMessage(pszCommand);
597             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
598             EndMessage();
599         }
600         catch (...)
601         {
602             AbortMessage();
603             throw;
604         }
605     }
606
607     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10>
608     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, const T10& a10)
609     {
610         try
611         {
612             BeginMessage(pszCommand);
613             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10;
614             EndMessage();
615         }
616         catch (...)
617         {
618             AbortMessage();
619             throw;
620         }
621     }
622
623     void CloseSocketDisconnect();
624
625     // Denial-of-service detection/prevention
626     // The idea is to detect peers that are behaving
627     // badly and disconnect/ban them, but do it in a
628     // one-coding-mistake-won't-shatter-the-entire-network
629     // way.
630     // IMPORTANT:  There should be nothing I can give a
631     // node that it will forward on that will make that
632     // node's peers drop it. If there is, an attacker
633     // can isolate a node and/or try to split the network.
634     // Dropping a node for sending stuff that is invalid
635     // now but might be valid in a later version is also
636     // dangerous, because it can cause a network split
637     // between nodes running old code and nodes running
638     // new code.
639     static void ClearBanned(); // needed for unit testing
640     static bool IsBanned(CNetAddr ip);
641     static bool IsBanned(CSubNet subnet);
642     static void Ban(const CNetAddr &ip, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
643     static void Ban(const CSubNet &subNet, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
644     static bool Unban(const CNetAddr &ip);
645     static bool Unban(const CSubNet &ip);
646     static void GetBanned(std::map<CSubNet, int64_t> &banmap);
647
648     void copyStats(CNodeStats &stats);
649
650     static bool IsWhitelistedRange(const CNetAddr &ip);
651     static void AddWhitelistedRange(const CSubNet &subnet);
652
653     // Network stats
654     static void RecordBytesRecv(uint64_t bytes);
655     static void RecordBytesSent(uint64_t bytes);
656
657     static uint64_t GetTotalBytesRecv();
658     static uint64_t GetTotalBytesSent();
659 };
660
661
662
663 class CTransaction;
664 void RelayTransaction(const CTransaction& tx);
665 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
666
667 /** Access to the (IP) address database (peers.dat) */
668 class CAddrDB
669 {
670 private:
671     boost::filesystem::path pathAddr;
672 public:
673     CAddrDB();
674     bool Write(const CAddrMan& addr);
675     bool Read(CAddrMan& addr);
676 };
677
678 #endif // BITCOIN_NET_H
This page took 0.061482 seconds and 4 git commands to generate.