Merge #12063: [Trivial] Update license year range to 2018
[bitcoinplatinum.git] / src / net.h
blob317321b15014395481bb5ccdb7b840ab381fe3db
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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.
6 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
9 #include <addrdb.h>
10 #include <addrman.h>
11 #include <amount.h>
12 #include <bloom.h>
13 #include <compat.h>
14 #include <hash.h>
15 #include <limitedmap.h>
16 #include <netaddress.h>
17 #include <policy/feerate.h>
18 #include <protocol.h>
19 #include <random.h>
20 #include <streams.h>
21 #include <sync.h>
22 #include <uint256.h>
23 #include <threadinterrupt.h>
25 #include <atomic>
26 #include <deque>
27 #include <stdint.h>
28 #include <thread>
29 #include <memory>
30 #include <condition_variable>
32 #ifndef WIN32
33 #include <arpa/inet.h>
34 #endif
37 class CScheduler;
38 class CNode;
40 namespace boost {
41 class thread_group;
42 } // namespace boost
44 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
45 static const int PING_INTERVAL = 2 * 60;
46 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
47 static const int TIMEOUT_INTERVAL = 20 * 60;
48 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
49 static const int FEELER_INTERVAL = 120;
50 /** The maximum number of entries in an 'inv' protocol message */
51 static const unsigned int MAX_INV_SZ = 50000;
52 /** The maximum number of new addresses to accumulate before announcing. */
53 static const unsigned int MAX_ADDR_TO_SEND = 1000;
54 /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
55 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
56 /** Maximum length of strSubVer in `version` message */
57 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
58 /** Maximum number of automatic outgoing nodes */
59 static const int MAX_OUTBOUND_CONNECTIONS = 8;
60 /** Maximum number of addnode outgoing nodes */
61 static const int MAX_ADDNODE_CONNECTIONS = 8;
62 /** -listen default */
63 static const bool DEFAULT_LISTEN = true;
64 /** -upnp default */
65 #ifdef USE_UPNP
66 static const bool DEFAULT_UPNP = USE_UPNP;
67 #else
68 static const bool DEFAULT_UPNP = false;
69 #endif
70 /** The maximum number of entries in mapAskFor */
71 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
72 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
73 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
74 /** The maximum number of peer connections to maintain. */
75 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
76 /** The default for -maxuploadtarget. 0 = Unlimited */
77 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
78 /** The default timeframe for -maxuploadtarget. 1 day. */
79 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
80 /** Default for blocks only*/
81 static const bool DEFAULT_BLOCKSONLY = false;
83 static const bool DEFAULT_FORCEDNSSEED = false;
84 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
85 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
87 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
88 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
90 typedef int64_t NodeId;
92 struct AddedNodeInfo
94 std::string strAddedNode;
95 CService resolvedAddress;
96 bool fConnected;
97 bool fInbound;
100 class CNodeStats;
101 class CClientUIInterface;
103 struct CSerializedNetMsg
105 CSerializedNetMsg() = default;
106 CSerializedNetMsg(CSerializedNetMsg&&) = default;
107 CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
108 // No copying, only moves.
109 CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
110 CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
112 std::vector<unsigned char> data;
113 std::string command;
116 class NetEventsInterface;
117 class CConnman
119 public:
121 enum NumConnections {
122 CONNECTIONS_NONE = 0,
123 CONNECTIONS_IN = (1U << 0),
124 CONNECTIONS_OUT = (1U << 1),
125 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
128 struct Options
130 ServiceFlags nLocalServices = NODE_NONE;
131 int nMaxConnections = 0;
132 int nMaxOutbound = 0;
133 int nMaxAddnode = 0;
134 int nMaxFeeler = 0;
135 int nBestHeight = 0;
136 CClientUIInterface* uiInterface = nullptr;
137 NetEventsInterface* m_msgproc = nullptr;
138 unsigned int nSendBufferMaxSize = 0;
139 unsigned int nReceiveFloodSize = 0;
140 uint64_t nMaxOutboundTimeframe = 0;
141 uint64_t nMaxOutboundLimit = 0;
142 std::vector<std::string> vSeedNodes;
143 std::vector<CSubNet> vWhitelistedRange;
144 std::vector<CService> vBinds, vWhiteBinds;
145 bool m_use_addrman_outgoing = true;
146 std::vector<std::string> m_specified_outgoing;
147 std::vector<std::string> m_added_nodes;
150 void Init(const Options& connOptions) {
151 nLocalServices = connOptions.nLocalServices;
152 nMaxConnections = connOptions.nMaxConnections;
153 nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
154 nMaxAddnode = connOptions.nMaxAddnode;
155 nMaxFeeler = connOptions.nMaxFeeler;
156 nBestHeight = connOptions.nBestHeight;
157 clientInterface = connOptions.uiInterface;
158 m_msgproc = connOptions.m_msgproc;
159 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
160 nReceiveFloodSize = connOptions.nReceiveFloodSize;
162 LOCK(cs_totalBytesSent);
163 nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
164 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
166 vWhitelistedRange = connOptions.vWhitelistedRange;
168 LOCK(cs_vAddedNodes);
169 vAddedNodes = connOptions.m_added_nodes;
173 CConnman(uint64_t seed0, uint64_t seed1);
174 ~CConnman();
175 bool Start(CScheduler& scheduler, const Options& options);
176 void Stop();
177 void Interrupt();
178 bool GetNetworkActive() const { return fNetworkActive; };
179 void SetNetworkActive(bool active);
180 bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool manual_connection = false);
181 bool CheckIncomingNonce(uint64_t nonce);
183 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
185 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
187 template<typename Callable>
188 void ForEachNode(Callable&& func)
190 LOCK(cs_vNodes);
191 for (auto&& node : vNodes) {
192 if (NodeFullyConnected(node))
193 func(node);
197 template<typename Callable>
198 void ForEachNode(Callable&& func) const
200 LOCK(cs_vNodes);
201 for (auto&& node : vNodes) {
202 if (NodeFullyConnected(node))
203 func(node);
207 template<typename Callable, typename CallableAfter>
208 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
210 LOCK(cs_vNodes);
211 for (auto&& node : vNodes) {
212 if (NodeFullyConnected(node))
213 pre(node);
215 post();
218 template<typename Callable, typename CallableAfter>
219 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
221 LOCK(cs_vNodes);
222 for (auto&& node : vNodes) {
223 if (NodeFullyConnected(node))
224 pre(node);
226 post();
229 // Addrman functions
230 size_t GetAddressCount() const;
231 void SetServices(const CService &addr, ServiceFlags nServices);
232 void MarkAddressGood(const CAddress& addr);
233 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
234 std::vector<CAddress> GetAddresses();
236 // Denial-of-service detection/prevention
237 // The idea is to detect peers that are behaving
238 // badly and disconnect/ban them, but do it in a
239 // one-coding-mistake-won't-shatter-the-entire-network
240 // way.
241 // IMPORTANT: There should be nothing I can give a
242 // node that it will forward on that will make that
243 // node's peers drop it. If there is, an attacker
244 // can isolate a node and/or try to split the network.
245 // Dropping a node for sending stuff that is invalid
246 // now but might be valid in a later version is also
247 // dangerous, because it can cause a network split
248 // between nodes running old code and nodes running
249 // new code.
250 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
251 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
252 void ClearBanned(); // needed for unit testing
253 bool IsBanned(CNetAddr ip);
254 bool IsBanned(CSubNet subnet);
255 bool Unban(const CNetAddr &ip);
256 bool Unban(const CSubNet &ip);
257 void GetBanned(banmap_t &banmap);
258 void SetBanned(const banmap_t &banmap);
260 // This allows temporarily exceeding nMaxOutbound, with the goal of finding
261 // a peer that is better than all our current peers.
262 void SetTryNewOutboundPeer(bool flag);
263 bool GetTryNewOutboundPeer();
265 // Return the number of outbound peers we have in excess of our target (eg,
266 // if we previously called SetTryNewOutboundPeer(true), and have since set
267 // to false, we may have extra peers that we wish to disconnect). This may
268 // return a value less than (num_outbound_connections - num_outbound_slots)
269 // in cases where some outbound connections are not yet fully connected, or
270 // not yet fully disconnected.
271 int GetExtraOutboundCount();
273 bool AddNode(const std::string& node);
274 bool RemoveAddedNode(const std::string& node);
275 std::vector<AddedNodeInfo> GetAddedNodeInfo();
277 size_t GetNodeCount(NumConnections num);
278 void GetNodeStats(std::vector<CNodeStats>& vstats);
279 bool DisconnectNode(const std::string& node);
280 bool DisconnectNode(NodeId id);
282 ServiceFlags GetLocalServices() const;
284 //!set the max outbound target in bytes
285 void SetMaxOutboundTarget(uint64_t limit);
286 uint64_t GetMaxOutboundTarget();
288 //!set the timeframe for the max outbound target
289 void SetMaxOutboundTimeframe(uint64_t timeframe);
290 uint64_t GetMaxOutboundTimeframe();
292 //!check if the outbound target is reached
293 // if param historicalBlockServingLimit is set true, the function will
294 // response true if the limit for serving historical blocks has been reached
295 bool OutboundTargetReached(bool historicalBlockServingLimit);
297 //!response the bytes left in the current max outbound cycle
298 // in case of no limit, it will always response 0
299 uint64_t GetOutboundTargetBytesLeft();
301 //!response the time in second left in the current max outbound cycle
302 // in case of no limit, it will always response 0
303 uint64_t GetMaxOutboundTimeLeftInCycle();
305 uint64_t GetTotalBytesRecv();
306 uint64_t GetTotalBytesSent();
308 void SetBestHeight(int height);
309 int GetBestHeight() const;
311 /** Get a unique deterministic randomizer. */
312 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
314 unsigned int GetReceiveFloodSize() const;
316 void WakeMessageHandler();
317 private:
318 struct ListenSocket {
319 SOCKET socket;
320 bool whitelisted;
322 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
325 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
326 bool Bind(const CService &addr, unsigned int flags);
327 bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
328 void ThreadOpenAddedConnections();
329 void AddOneShot(const std::string& strDest);
330 void ProcessOneShot();
331 void ThreadOpenConnections(std::vector<std::string> connect);
332 void ThreadMessageHandler();
333 void AcceptConnection(const ListenSocket& hListenSocket);
334 void ThreadSocketHandler();
335 void ThreadDNSAddressSeed();
337 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
339 CNode* FindNode(const CNetAddr& ip);
340 CNode* FindNode(const CSubNet& subNet);
341 CNode* FindNode(const std::string& addrName);
342 CNode* FindNode(const CService& addr);
344 bool AttemptToEvictConnection();
345 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
346 bool IsWhitelistedRange(const CNetAddr &addr);
348 void DeleteNode(CNode* pnode);
350 NodeId GetNewNodeId();
352 size_t SocketSendData(CNode *pnode) const;
353 //!check is the banlist has unwritten changes
354 bool BannedSetIsDirty();
355 //!set the "dirty" flag for the banlist
356 void SetBannedSetDirty(bool dirty=true);
357 //!clean unused entries (if bantime has expired)
358 void SweepBanned();
359 void DumpAddresses();
360 void DumpData();
361 void DumpBanlist();
363 // Network stats
364 void RecordBytesRecv(uint64_t bytes);
365 void RecordBytesSent(uint64_t bytes);
367 // Whether the node should be passed out in ForEach* callbacks
368 static bool NodeFullyConnected(const CNode* pnode);
370 // Network usage totals
371 CCriticalSection cs_totalBytesRecv;
372 CCriticalSection cs_totalBytesSent;
373 uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv);
374 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent);
376 // outbound limit & stats
377 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
378 uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
379 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
380 uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
382 // Whitelisted ranges. Any node connecting from these is automatically
383 // whitelisted (as well as those connecting to whitelisted binds).
384 std::vector<CSubNet> vWhitelistedRange;
386 unsigned int nSendBufferMaxSize;
387 unsigned int nReceiveFloodSize;
389 std::vector<ListenSocket> vhListenSocket;
390 std::atomic<bool> fNetworkActive;
391 banmap_t setBanned;
392 CCriticalSection cs_setBanned;
393 bool setBannedIsDirty;
394 bool fAddressesInitialized;
395 CAddrMan addrman;
396 std::deque<std::string> vOneShots;
397 CCriticalSection cs_vOneShots;
398 std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
399 CCriticalSection cs_vAddedNodes;
400 std::vector<CNode*> vNodes;
401 std::list<CNode*> vNodesDisconnected;
402 mutable CCriticalSection cs_vNodes;
403 std::atomic<NodeId> nLastNodeId;
405 /** Services this instance offers */
406 ServiceFlags nLocalServices;
408 std::unique_ptr<CSemaphore> semOutbound;
409 std::unique_ptr<CSemaphore> semAddnode;
410 int nMaxConnections;
411 int nMaxOutbound;
412 int nMaxAddnode;
413 int nMaxFeeler;
414 std::atomic<int> nBestHeight;
415 CClientUIInterface* clientInterface;
416 NetEventsInterface* m_msgproc;
418 /** SipHasher seeds for deterministic randomness */
419 const uint64_t nSeed0, nSeed1;
421 /** flag for waking the message processor. */
422 bool fMsgProcWake;
424 std::condition_variable condMsgProc;
425 std::mutex mutexMsgProc;
426 std::atomic<bool> flagInterruptMsgProc;
428 CThreadInterrupt interruptNet;
430 std::thread threadDNSAddressSeed;
431 std::thread threadSocketHandler;
432 std::thread threadOpenAddedConnections;
433 std::thread threadOpenConnections;
434 std::thread threadMessageHandler;
436 /** flag for deciding to connect to an extra outbound peer,
437 * in excess of nMaxOutbound
438 * This takes the place of a feeler connection */
439 std::atomic_bool m_try_another_outbound_peer;
441 friend struct CConnmanTest;
443 extern std::unique_ptr<CConnman> g_connman;
444 void Discover(boost::thread_group& threadGroup);
445 void MapPort(bool fUseUPnP);
446 unsigned short GetListenPort();
447 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
449 struct CombinerAll
451 typedef bool result_type;
453 template<typename I>
454 bool operator()(I first, I last) const
456 while (first != last) {
457 if (!(*first)) return false;
458 ++first;
460 return true;
465 * Interface for message handling
467 class NetEventsInterface
469 public:
470 virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
471 virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
472 virtual void InitializeNode(CNode* pnode) = 0;
473 virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
476 enum
478 LOCAL_NONE, // unknown
479 LOCAL_IF, // address a local interface listens on
480 LOCAL_BIND, // address explicit bound to
481 LOCAL_UPNP, // address reported by UPnP
482 LOCAL_MANUAL, // address explicitly specified (-externalip=)
484 LOCAL_MAX
487 bool IsPeerAddrLocalGood(CNode *pnode);
488 void AdvertiseLocal(CNode *pnode);
489 void SetLimited(enum Network net, bool fLimited = true);
490 bool IsLimited(enum Network net);
491 bool IsLimited(const CNetAddr& addr);
492 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
493 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
494 bool RemoveLocal(const CService& addr);
495 bool SeenLocal(const CService& addr);
496 bool IsLocal(const CService& addr);
497 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
498 bool IsReachable(enum Network net);
499 bool IsReachable(const CNetAddr &addr);
500 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
503 extern bool fDiscover;
504 extern bool fListen;
505 extern bool fRelayTxes;
507 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
509 /** Subversion as sent to the P2P network in `version` messages */
510 extern std::string strSubVersion;
512 struct LocalServiceInfo {
513 int nScore;
514 int nPort;
517 extern CCriticalSection cs_mapLocalHost;
518 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
519 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
521 class CNodeStats
523 public:
524 NodeId nodeid;
525 ServiceFlags nServices;
526 bool fRelayTxes;
527 int64_t nLastSend;
528 int64_t nLastRecv;
529 int64_t nTimeConnected;
530 int64_t nTimeOffset;
531 std::string addrName;
532 int nVersion;
533 std::string cleanSubVer;
534 bool fInbound;
535 bool m_manual_connection;
536 int nStartingHeight;
537 uint64_t nSendBytes;
538 mapMsgCmdSize mapSendBytesPerMsgCmd;
539 uint64_t nRecvBytes;
540 mapMsgCmdSize mapRecvBytesPerMsgCmd;
541 bool fWhitelisted;
542 double dPingTime;
543 double dPingWait;
544 double dMinPing;
545 // Our address, as reported by the peer
546 std::string addrLocal;
547 // Address of this peer
548 CAddress addr;
549 // Bind address of our side of the connection
550 CAddress addrBind;
556 class CNetMessage {
557 private:
558 mutable CHash256 hasher;
559 mutable uint256 data_hash;
560 public:
561 bool in_data; // parsing header (false) or data (true)
563 CDataStream hdrbuf; // partially received header
564 CMessageHeader hdr; // complete header
565 unsigned int nHdrPos;
567 CDataStream vRecv; // received message data
568 unsigned int nDataPos;
570 int64_t nTime; // time (in microseconds) of message receipt.
572 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
573 hdrbuf.resize(24);
574 in_data = false;
575 nHdrPos = 0;
576 nDataPos = 0;
577 nTime = 0;
580 bool complete() const
582 if (!in_data)
583 return false;
584 return (hdr.nMessageSize == nDataPos);
587 const uint256& GetMessageHash() const;
589 void SetVersion(int nVersionIn)
591 hdrbuf.SetVersion(nVersionIn);
592 vRecv.SetVersion(nVersionIn);
595 int readHeader(const char *pch, unsigned int nBytes);
596 int readData(const char *pch, unsigned int nBytes);
600 /** Information about a peer */
601 class CNode
603 friend class CConnman;
604 public:
605 // socket
606 std::atomic<ServiceFlags> nServices;
607 SOCKET hSocket;
608 size_t nSendSize; // total size of all vSendMsg entries
609 size_t nSendOffset; // offset inside the first vSendMsg already sent
610 uint64_t nSendBytes;
611 std::deque<std::vector<unsigned char>> vSendMsg;
612 CCriticalSection cs_vSend;
613 CCriticalSection cs_hSocket;
614 CCriticalSection cs_vRecv;
616 CCriticalSection cs_vProcessMsg;
617 std::list<CNetMessage> vProcessMsg;
618 size_t nProcessQueueSize;
620 CCriticalSection cs_sendProcessing;
622 std::deque<CInv> vRecvGetData;
623 uint64_t nRecvBytes;
624 std::atomic<int> nRecvVersion;
626 std::atomic<int64_t> nLastSend;
627 std::atomic<int64_t> nLastRecv;
628 const int64_t nTimeConnected;
629 std::atomic<int64_t> nTimeOffset;
630 // Address of this peer
631 const CAddress addr;
632 // Bind address of our side of the connection
633 const CAddress addrBind;
634 std::atomic<int> nVersion;
635 // strSubVer is whatever byte array we read from the wire. However, this field is intended
636 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
637 // store the sanitized version in cleanSubVer. The original should be used when dealing with
638 // the network or wire types and the cleaned string used when displayed or logged.
639 std::string strSubVer, cleanSubVer;
640 CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
641 bool fWhitelisted; // This peer can bypass DoS banning.
642 bool fFeeler; // If true this node is being used as a short lived feeler.
643 bool fOneShot;
644 bool m_manual_connection;
645 bool fClient;
646 const bool fInbound;
647 std::atomic_bool fSuccessfullyConnected;
648 std::atomic_bool fDisconnect;
649 // We use fRelayTxes for two purposes -
650 // a) it allows us to not relay tx invs before receiving the peer's version message
651 // b) the peer may tell us in its version message that we should not relay tx invs
652 // unless it loads a bloom filter.
653 bool fRelayTxes; //protected by cs_filter
654 bool fSentAddr;
655 CSemaphoreGrant grantOutbound;
656 CCriticalSection cs_filter;
657 std::unique_ptr<CBloomFilter> pfilter;
658 std::atomic<int> nRefCount;
660 const uint64_t nKeyedNetGroup;
661 std::atomic_bool fPauseRecv;
662 std::atomic_bool fPauseSend;
663 protected:
665 mapMsgCmdSize mapSendBytesPerMsgCmd;
666 mapMsgCmdSize mapRecvBytesPerMsgCmd;
668 public:
669 uint256 hashContinue;
670 std::atomic<int> nStartingHeight;
672 // flood relay
673 std::vector<CAddress> vAddrToSend;
674 CRollingBloomFilter addrKnown;
675 bool fGetAddr;
676 std::set<uint256> setKnown;
677 int64_t nNextAddrSend;
678 int64_t nNextLocalAddrSend;
680 // inventory based relay
681 CRollingBloomFilter filterInventoryKnown;
682 // Set of transaction ids we still have to announce.
683 // They are sorted by the mempool before relay, so the order is not important.
684 std::set<uint256> setInventoryTxToSend;
685 // List of block ids we still have announce.
686 // There is no final sorting before sending, as they are always sent immediately
687 // and in the order requested.
688 std::vector<uint256> vInventoryBlockToSend;
689 CCriticalSection cs_inventory;
690 std::set<uint256> setAskFor;
691 std::multimap<int64_t, CInv> mapAskFor;
692 int64_t nNextInvSend;
693 // Used for headers announcements - unfiltered blocks to relay
694 // Also protected by cs_inventory
695 std::vector<uint256> vBlockHashesToAnnounce;
696 // Used for BIP35 mempool sending, also protected by cs_inventory
697 bool fSendMempool;
699 // Last time a "MEMPOOL" request was serviced.
700 std::atomic<int64_t> timeLastMempoolReq;
702 // Block and TXN accept times
703 std::atomic<int64_t> nLastBlockTime;
704 std::atomic<int64_t> nLastTXTime;
706 // Ping time measurement:
707 // The pong reply we're expecting, or 0 if no pong expected.
708 std::atomic<uint64_t> nPingNonceSent;
709 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
710 std::atomic<int64_t> nPingUsecStart;
711 // Last measured round-trip time.
712 std::atomic<int64_t> nPingUsecTime;
713 // Best measured round-trip time.
714 std::atomic<int64_t> nMinPingUsecTime;
715 // Whether a ping is requested.
716 std::atomic<bool> fPingQueued;
717 // Minimum fee rate with which to filter inv's to this node
718 CAmount minFeeFilter;
719 CCriticalSection cs_feeFilter;
720 CAmount lastSentFeeFilter;
721 int64_t nextSendTimeFeeFilter;
723 CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn = "", bool fInboundIn = false);
724 ~CNode();
725 CNode(const CNode&) = delete;
726 CNode& operator=(const CNode&) = delete;
728 private:
729 const NodeId id;
730 const uint64_t nLocalHostNonce;
731 // Services offered to this peer
732 const ServiceFlags nLocalServices;
733 const int nMyStartingHeight;
734 int nSendVersion;
735 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
737 mutable CCriticalSection cs_addrName;
738 std::string addrName;
740 // Our address, as reported by the peer
741 CService addrLocal;
742 mutable CCriticalSection cs_addrLocal;
743 public:
745 NodeId GetId() const {
746 return id;
749 uint64_t GetLocalNonce() const {
750 return nLocalHostNonce;
753 int GetMyStartingHeight() const {
754 return nMyStartingHeight;
757 int GetRefCount() const
759 assert(nRefCount >= 0);
760 return nRefCount;
763 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
765 void SetRecvVersion(int nVersionIn)
767 nRecvVersion = nVersionIn;
769 int GetRecvVersion() const
771 return nRecvVersion;
773 void SetSendVersion(int nVersionIn);
774 int GetSendVersion() const;
776 CService GetAddrLocal() const;
777 //! May not be called more than once
778 void SetAddrLocal(const CService& addrLocalIn);
780 CNode* AddRef()
782 nRefCount++;
783 return this;
786 void Release()
788 nRefCount--;
793 void AddAddressKnown(const CAddress& _addr)
795 addrKnown.insert(_addr.GetKey());
798 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
800 // Known checking here is only to save space from duplicates.
801 // SendMessages will filter it again for knowns that were added
802 // after addresses were pushed.
803 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
804 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
805 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
806 } else {
807 vAddrToSend.push_back(_addr);
813 void AddInventoryKnown(const CInv& inv)
816 LOCK(cs_inventory);
817 filterInventoryKnown.insert(inv.hash);
821 void PushInventory(const CInv& inv)
823 LOCK(cs_inventory);
824 if (inv.type == MSG_TX) {
825 if (!filterInventoryKnown.contains(inv.hash)) {
826 setInventoryTxToSend.insert(inv.hash);
828 } else if (inv.type == MSG_BLOCK) {
829 vInventoryBlockToSend.push_back(inv.hash);
833 void PushBlockHash(const uint256 &hash)
835 LOCK(cs_inventory);
836 vBlockHashesToAnnounce.push_back(hash);
839 void AskFor(const CInv& inv);
841 void CloseSocketDisconnect();
843 void copyStats(CNodeStats &stats);
845 ServiceFlags GetLocalServices() const
847 return nLocalServices;
850 std::string GetAddrName() const;
851 //! Sets the addrName only if it was not previously set
852 void MaybeSetAddrName(const std::string& addrNameIn);
859 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
860 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
862 #endif // BITCOIN_NET_H