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