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