]> Git Repo - VerusCoin.git/blob - src/net.h
Merge commit 'd48555b36ac512161b81f9b6bca7bea16a0cd806' as 'src/secp256k1'
[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 "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 CNode;
36
37 namespace boost {
38     class thread_group;
39 } // namespace boost
40
41 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
42 static const int PING_INTERVAL = 2 * 60;
43 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
44 static const int TIMEOUT_INTERVAL = 20 * 60;
45 /** The maximum number of entries in an 'inv' protocol message */
46 static const unsigned int MAX_INV_SZ = 50000;
47 /** -listen default */
48 static const bool DEFAULT_LISTEN = true;
49 /** -upnp default */
50 #ifdef USE_UPNP
51 static const bool DEFAULT_UPNP = USE_UPNP;
52 #else
53 static const bool DEFAULT_UPNP = false;
54 #endif
55 /** The maximum number of entries in mapAskFor */
56 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
57
58 unsigned int ReceiveFloodSize();
59 unsigned int SendBufferSize();
60
61 void AddOneShot(std::string strDest);
62 bool RecvLine(SOCKET hSocket, std::string& strLine);
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_MANUAL, // address explicitly specified (-externalip=)
99
100     LOCAL_MAX
101 };
102
103 bool IsPeerAddrLocalGood(CNode *pnode);
104 void AdvertizeLocal(CNode *pnode);
105 void SetLimited(enum Network net, bool fLimited = true);
106 bool IsLimited(enum Network net);
107 bool IsLimited(const CNetAddr& addr);
108 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
109 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
110 bool SeenLocal(const CService& addr);
111 bool IsLocal(const CService& addr);
112 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
113 bool IsReachable(enum Network net);
114 bool IsReachable(const CNetAddr &addr);
115 void SetReachable(enum Network net, bool fFlag = true);
116 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
117
118
119 extern bool fDiscover;
120 extern bool fListen;
121 extern uint64_t nLocalServices;
122 extern uint64_t nLocalHostNonce;
123 extern CAddrMan addrman;
124 extern int nMaxConnections;
125
126 extern std::vector<CNode*> vNodes;
127 extern CCriticalSection cs_vNodes;
128 extern std::map<CInv, CDataStream> mapRelay;
129 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
130 extern CCriticalSection cs_mapRelay;
131 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
132
133 extern std::vector<std::string> vAddedNodes;
134 extern CCriticalSection cs_vAddedNodes;
135
136 extern NodeId nLastNodeId;
137 extern CCriticalSection cs_nLastNodeId;
138
139 struct LocalServiceInfo {
140     int nScore;
141     int nPort;
142 };
143
144 extern CCriticalSection cs_mapLocalHost;
145 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
146
147 class CNodeStats
148 {
149 public:
150     NodeId nodeid;
151     uint64_t nServices;
152     int64_t nLastSend;
153     int64_t nLastRecv;
154     int64_t nTimeConnected;
155     std::string addrName;
156     int nVersion;
157     std::string cleanSubVer;
158     bool fInbound;
159     int nStartingHeight;
160     uint64_t nSendBytes;
161     uint64_t nRecvBytes;
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     int nStartingHeight;
280
281     // flood relay
282     std::vector<CAddress> vAddrToSend;
283     mruset<CAddress> setAddrKnown;
284     bool fGetAddr;
285     std::set<uint256> setKnown;
286
287     // inventory based relay
288     mruset<CInv> setInventoryKnown;
289     std::vector<CInv> vInventoryToSend;
290     CCriticalSection cs_inventory;
291     std::multimap<int64_t, CInv> mapAskFor;
292
293     // Ping time measurement:
294     // The pong reply we're expecting, or 0 if no pong expected.
295     uint64_t nPingNonceSent;
296     // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
297     int64_t nPingUsecStart;
298     // Last measured round-trip time.
299     int64_t nPingUsecTime;
300     // Whether a ping is requested.
301     bool fPingQueued;
302
303     CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false);
304     ~CNode();
305
306 private:
307     // Network usage totals
308     static CCriticalSection cs_totalBytesRecv;
309     static CCriticalSection cs_totalBytesSent;
310     static uint64_t nTotalBytesRecv;
311     static uint64_t nTotalBytesSent;
312
313     CNode(const CNode&);
314     void operator=(const CNode&);
315
316 public:
317
318     NodeId GetId() const {
319       return id;
320     }
321
322     int GetRefCount()
323     {
324         assert(nRefCount >= 0);
325         return nRefCount;
326     }
327
328     // requires LOCK(cs_vRecvMsg)
329     unsigned int GetTotalRecvSize()
330     {
331         unsigned int total = 0;
332         BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
333             total += msg.vRecv.size() + 24;
334         return total;
335     }
336
337     // requires LOCK(cs_vRecvMsg)
338     bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
339
340     // requires LOCK(cs_vRecvMsg)
341     void SetRecvVersion(int nVersionIn)
342     {
343         nRecvVersion = nVersionIn;
344         BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
345             msg.SetVersion(nVersionIn);
346     }
347
348     CNode* AddRef()
349     {
350         nRefCount++;
351         return this;
352     }
353
354     void Release()
355     {
356         nRefCount--;
357     }
358
359
360
361     void AddAddressKnown(const CAddress& addr)
362     {
363         setAddrKnown.insert(addr);
364     }
365
366     void PushAddress(const CAddress& addr)
367     {
368         // Known checking here is only to save space from duplicates.
369         // SendMessages will filter it again for knowns that were added
370         // after addresses were pushed.
371         if (addr.IsValid() && !setAddrKnown.count(addr))
372             vAddrToSend.push_back(addr);
373     }
374
375
376     void AddInventoryKnown(const CInv& inv)
377     {
378         {
379             LOCK(cs_inventory);
380             setInventoryKnown.insert(inv);
381         }
382     }
383
384     void PushInventory(const CInv& inv)
385     {
386         {
387             LOCK(cs_inventory);
388             if (!setInventoryKnown.count(inv))
389                 vInventoryToSend.push_back(inv);
390         }
391     }
392
393     void AskFor(const CInv& inv);
394
395     // TODO: Document the postcondition of this function.  Is cs_vSend locked?
396     void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
397
398     // TODO: Document the precondition of this function.  Is cs_vSend locked?
399     void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
400
401     // TODO: Document the precondition of this function.  Is cs_vSend locked?
402     void EndMessage() UNLOCK_FUNCTION(cs_vSend);
403
404     void PushVersion();
405
406
407     void PushMessage(const char* pszCommand)
408     {
409         try
410         {
411             BeginMessage(pszCommand);
412             EndMessage();
413         }
414         catch (...)
415         {
416             AbortMessage();
417             throw;
418         }
419     }
420
421     template<typename T1>
422     void PushMessage(const char* pszCommand, const T1& a1)
423     {
424         try
425         {
426             BeginMessage(pszCommand);
427             ssSend << a1;
428             EndMessage();
429         }
430         catch (...)
431         {
432             AbortMessage();
433             throw;
434         }
435     }
436
437     template<typename T1, typename T2>
438     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
439     {
440         try
441         {
442             BeginMessage(pszCommand);
443             ssSend << a1 << a2;
444             EndMessage();
445         }
446         catch (...)
447         {
448             AbortMessage();
449             throw;
450         }
451     }
452
453     template<typename T1, typename T2, typename T3>
454     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
455     {
456         try
457         {
458             BeginMessage(pszCommand);
459             ssSend << a1 << a2 << a3;
460             EndMessage();
461         }
462         catch (...)
463         {
464             AbortMessage();
465             throw;
466         }
467     }
468
469     template<typename T1, typename T2, typename T3, typename T4>
470     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
471     {
472         try
473         {
474             BeginMessage(pszCommand);
475             ssSend << a1 << a2 << a3 << a4;
476             EndMessage();
477         }
478         catch (...)
479         {
480             AbortMessage();
481             throw;
482         }
483     }
484
485     template<typename T1, typename T2, typename T3, typename T4, typename T5>
486     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
487     {
488         try
489         {
490             BeginMessage(pszCommand);
491             ssSend << a1 << a2 << a3 << a4 << a5;
492             EndMessage();
493         }
494         catch (...)
495         {
496             AbortMessage();
497             throw;
498         }
499     }
500
501     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
502     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
503     {
504         try
505         {
506             BeginMessage(pszCommand);
507             ssSend << a1 << a2 << a3 << a4 << a5 << a6;
508             EndMessage();
509         }
510         catch (...)
511         {
512             AbortMessage();
513             throw;
514         }
515     }
516
517     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
518     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)
519     {
520         try
521         {
522             BeginMessage(pszCommand);
523             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
524             EndMessage();
525         }
526         catch (...)
527         {
528             AbortMessage();
529             throw;
530         }
531     }
532
533     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
534     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)
535     {
536         try
537         {
538             BeginMessage(pszCommand);
539             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
540             EndMessage();
541         }
542         catch (...)
543         {
544             AbortMessage();
545             throw;
546         }
547     }
548
549     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
550     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)
551     {
552         try
553         {
554             BeginMessage(pszCommand);
555             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
556             EndMessage();
557         }
558         catch (...)
559         {
560             AbortMessage();
561             throw;
562         }
563     }
564
565     bool IsSubscribed(unsigned int nChannel);
566     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
567     void CancelSubscribe(unsigned int nChannel);
568     void CloseSocketDisconnect();
569
570     // Denial-of-service detection/prevention
571     // The idea is to detect peers that are behaving
572     // badly and disconnect/ban them, but do it in a
573     // one-coding-mistake-won't-shatter-the-entire-network
574     // way.
575     // IMPORTANT:  There should be nothing I can give a
576     // node that it will forward on that will make that
577     // node's peers drop it. If there is, an attacker
578     // can isolate a node and/or try to split the network.
579     // Dropping a node for sending stuff that is invalid
580     // now but might be valid in a later version is also
581     // dangerous, because it can cause a network split
582     // between nodes running old code and nodes running
583     // new code.
584     static void ClearBanned(); // needed for unit testing
585     static bool IsBanned(CNetAddr ip);
586     static bool Ban(const CNetAddr &ip);
587     void copyStats(CNodeStats &stats);
588
589     static bool IsWhitelistedRange(const CNetAddr &ip);
590     static void AddWhitelistedRange(const CSubNet &subnet);
591
592     // Network stats
593     static void RecordBytesRecv(uint64_t bytes);
594     static void RecordBytesSent(uint64_t bytes);
595
596     static uint64_t GetTotalBytesRecv();
597     static uint64_t GetTotalBytesSent();
598 };
599
600
601
602 class CTransaction;
603 void RelayTransaction(const CTransaction& tx);
604 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
605
606 /** Access to the (IP) address database (peers.dat) */
607 class CAddrDB
608 {
609 private:
610     boost::filesystem::path pathAddr;
611 public:
612     CAddrDB();
613     bool Write(const CAddrMan& addr);
614     bool Read(CAddrMan& addr);
615 };
616
617 #endif // BITCOIN_NET_H
This page took 0.054472 seconds and 4 git commands to generate.