]> Git Repo - VerusCoin.git/blob - src/net.h
move functions in main and net to implementation files
[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 "util.h"
20
21 #include <deque>
22 #include <stdint.h>
23
24 #ifndef WIN32
25 #include <arpa/inet.h>
26 #endif
27
28 #include <boost/foreach.hpp>
29 #include <boost/signals2/signal.hpp>
30
31 class CAddrMan;
32 class CBlockIndex;
33 class CNode;
34
35 namespace boost {
36     class thread_group;
37 } // namespace boost
38
39 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
40 static const int PING_INTERVAL = 2 * 60;
41 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
42 static const int TIMEOUT_INTERVAL = 20 * 60;
43 /** The maximum number of entries in an 'inv' protocol message */
44 static const unsigned int MAX_INV_SZ = 50000;
45 /** -listen default */
46 static const bool DEFAULT_LISTEN = true;
47 /** -upnp default */
48 #ifdef USE_UPNP
49 static const bool DEFAULT_UPNP = USE_UPNP;
50 #else
51 static const bool DEFAULT_UPNP = false;
52 #endif
53
54 unsigned int ReceiveFloodSize();
55 unsigned int SendBufferSize();
56
57 void AddOneShot(std::string strDest);
58 bool RecvLine(SOCKET hSocket, std::string& strLine);
59 bool GetMyExternalIP(CNetAddr& ipRet);
60 void AddressCurrentlyConnected(const CService& addr);
61 CNode* FindNode(const CNetAddr& ip);
62 CNode* FindNode(const std::string& addrName);
63 CNode* FindNode(const CService& ip);
64 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
65 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
66 void MapPort(bool fUseUPnP);
67 unsigned short GetListenPort();
68 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
69 void StartNode(boost::thread_group& threadGroup);
70 bool StopNode();
71 void SocketSendData(CNode *pnode);
72
73 typedef int NodeId;
74
75 // Signals for message handling
76 struct CNodeSignals
77 {
78     boost::signals2::signal<int ()> GetHeight;
79     boost::signals2::signal<bool (CNode*)> ProcessMessages;
80     boost::signals2::signal<bool (CNode*, bool)> SendMessages;
81     boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
82     boost::signals2::signal<void (NodeId)> FinalizeNode;
83 };
84
85
86 CNodeSignals& GetNodeSignals();
87
88
89 enum
90 {
91     LOCAL_NONE,   // unknown
92     LOCAL_IF,     // address a local interface listens on
93     LOCAL_BIND,   // address explicit bound to
94     LOCAL_UPNP,   // address reported by UPnP
95     LOCAL_HTTP,   // address reported by whatismyip.com and similar
96     LOCAL_MANUAL, // address explicitly specified (-externalip=)
97
98     LOCAL_MAX
99 };
100
101 void SetLimited(enum Network net, bool fLimited = true);
102 bool IsLimited(enum Network net);
103 bool IsLimited(const CNetAddr& addr);
104 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
105 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
106 bool SeenLocal(const CService& addr);
107 bool IsLocal(const CService& addr);
108 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
109 bool IsReachable(enum Network net);
110 bool IsReachable(const CNetAddr &addr);
111 void SetReachable(enum Network net, bool fFlag = true);
112 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
113
114
115 extern bool fDiscover;
116 extern bool fListen;
117 extern uint64_t nLocalServices;
118 extern uint64_t nLocalHostNonce;
119 extern CAddrMan addrman;
120 extern int nMaxConnections;
121
122 extern std::vector<CNode*> vNodes;
123 extern CCriticalSection cs_vNodes;
124 extern std::map<CInv, CDataStream> mapRelay;
125 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
126 extern CCriticalSection cs_mapRelay;
127 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
128
129 extern std::vector<std::string> vAddedNodes;
130 extern CCriticalSection cs_vAddedNodes;
131
132 extern NodeId nLastNodeId;
133 extern CCriticalSection cs_nLastNodeId;
134
135 struct LocalServiceInfo {
136     int nScore;
137     int nPort;
138 };
139
140 extern CCriticalSection cs_mapLocalHost;
141 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
142
143 class CNodeStats
144 {
145 public:
146     NodeId nodeid;
147     uint64_t nServices;
148     int64_t nLastSend;
149     int64_t nLastRecv;
150     int64_t nTimeConnected;
151     std::string addrName;
152     int nVersion;
153     std::string cleanSubVer;
154     bool fInbound;
155     int nStartingHeight;
156     uint64_t nSendBytes;
157     uint64_t nRecvBytes;
158     bool fSyncNode;
159     bool fWhitelisted;
160     double dPingTime;
161     double dPingWait;
162     std::string addrLocal;
163 };
164
165
166
167
168 class CNetMessage {
169 public:
170     bool in_data;                   // parsing header (false) or data (true)
171
172     CDataStream hdrbuf;             // partially received header
173     CMessageHeader hdr;             // complete header
174     unsigned int nHdrPos;
175
176     CDataStream vRecv;              // received message data
177     unsigned int nDataPos;
178
179     int64_t nTime;                  // time (in microseconds) of message receipt.
180
181     CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
182         hdrbuf.resize(24);
183         in_data = false;
184         nHdrPos = 0;
185         nDataPos = 0;
186         nTime = 0;
187     }
188
189     bool complete() const
190     {
191         if (!in_data)
192             return false;
193         return (hdr.nMessageSize == nDataPos);
194     }
195
196     void SetVersion(int nVersionIn)
197     {
198         hdrbuf.SetVersion(nVersionIn);
199         vRecv.SetVersion(nVersionIn);
200     }
201
202     int readHeader(const char *pch, unsigned int nBytes);
203     int readData(const char *pch, unsigned int nBytes);
204 };
205
206
207
208
209
210 /** Information about a peer */
211 class CNode
212 {
213 public:
214     // socket
215     uint64_t nServices;
216     SOCKET hSocket;
217     CDataStream ssSend;
218     size_t nSendSize; // total size of all vSendMsg entries
219     size_t nSendOffset; // offset inside the first vSendMsg already sent
220     uint64_t nSendBytes;
221     std::deque<CSerializeData> vSendMsg;
222     CCriticalSection cs_vSend;
223
224     std::deque<CInv> vRecvGetData;
225     std::deque<CNetMessage> vRecvMsg;
226     CCriticalSection cs_vRecvMsg;
227     uint64_t nRecvBytes;
228     int nRecvVersion;
229
230     int64_t nLastSend;
231     int64_t nLastRecv;
232     int64_t nTimeConnected;
233     CAddress addr;
234     std::string addrName;
235     CService addrLocal;
236     int nVersion;
237     // strSubVer is whatever byte array we read from the wire. However, this field is intended
238     // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
239     // store the sanitized version in cleanSubVer. The original should be used when dealing with
240     // the network or wire types and the cleaned string used when displayed or logged.
241     std::string strSubVer, cleanSubVer;
242     bool fWhitelisted; // This peer can bypass DoS banning.
243     bool fOneShot;
244     bool fClient;
245     bool fInbound;
246     bool fNetworkNode;
247     bool fSuccessfullyConnected;
248     bool fDisconnect;
249     // We use fRelayTxes for two purposes -
250     // a) it allows us to not relay tx invs before receiving the peer's version message
251     // b) the peer may tell us in their version message that we should not relay tx invs
252     //    until they have initialized their bloom filter.
253     bool fRelayTxes;
254     CSemaphoreGrant grantOutbound;
255     CCriticalSection cs_filter;
256     CBloomFilter* pfilter;
257     int nRefCount;
258     NodeId id;
259 protected:
260
261     // Denial-of-service detection/prevention
262     // Key is IP address, value is banned-until-time
263     static std::map<CNetAddr, int64_t> setBanned;
264     static CCriticalSection cs_setBanned;
265
266     // Whitelisted ranges. Any node connecting from these is automatically
267     // whitelisted (as well as those connecting to whitelisted binds).
268     static std::vector<CSubNet> vWhitelistedRange;
269     static CCriticalSection cs_vWhitelistedRange;
270
271     // Basic fuzz-testing
272     void Fuzz(int nChance); // modifies ssSend
273
274 public:
275     uint256 hashContinue;
276     CBlockIndex* pindexLastGetBlocksBegin;
277     uint256 hashLastGetBlocksEnd;
278     int nStartingHeight;
279     bool fStartSync;
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
This page took 0.05803 seconds and 4 git commands to generate.