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