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