Merge #11743: qa: Add multiwallet prefix test
[bitcoinplatinum.git] / src / net.h
bloba7223050e77436b5ce7a80f4281d6bb90e3e75bc
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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;
161 nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
162 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
163 vWhitelistedRange = connOptions.vWhitelistedRange;
164 vAddedNodes = connOptions.m_added_nodes;
167 CConnman(uint64_t seed0, uint64_t seed1);
168 ~CConnman();
169 bool Start(CScheduler& scheduler, const Options& options);
170 void Stop();
171 void Interrupt();
172 bool GetNetworkActive() const { return fNetworkActive; };
173 void SetNetworkActive(bool active);
174 bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool manual_connection = false);
175 bool CheckIncomingNonce(uint64_t nonce);
177 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
179 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
181 template<typename Callable>
182 void ForEachNode(Callable&& func)
184 LOCK(cs_vNodes);
185 for (auto&& node : vNodes) {
186 if (NodeFullyConnected(node))
187 func(node);
191 template<typename Callable>
192 void ForEachNode(Callable&& func) const
194 LOCK(cs_vNodes);
195 for (auto&& node : vNodes) {
196 if (NodeFullyConnected(node))
197 func(node);
201 template<typename Callable, typename CallableAfter>
202 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
204 LOCK(cs_vNodes);
205 for (auto&& node : vNodes) {
206 if (NodeFullyConnected(node))
207 pre(node);
209 post();
212 template<typename Callable, typename CallableAfter>
213 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
215 LOCK(cs_vNodes);
216 for (auto&& node : vNodes) {
217 if (NodeFullyConnected(node))
218 pre(node);
220 post();
223 // Addrman functions
224 size_t GetAddressCount() const;
225 void SetServices(const CService &addr, ServiceFlags nServices);
226 void MarkAddressGood(const CAddress& addr);
227 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
228 std::vector<CAddress> GetAddresses();
230 // Denial-of-service detection/prevention
231 // The idea is to detect peers that are behaving
232 // badly and disconnect/ban them, but do it in a
233 // one-coding-mistake-won't-shatter-the-entire-network
234 // way.
235 // IMPORTANT: There should be nothing I can give a
236 // node that it will forward on that will make that
237 // node's peers drop it. If there is, an attacker
238 // can isolate a node and/or try to split the network.
239 // Dropping a node for sending stuff that is invalid
240 // now but might be valid in a later version is also
241 // dangerous, because it can cause a network split
242 // between nodes running old code and nodes running
243 // new code.
244 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
245 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
246 void ClearBanned(); // needed for unit testing
247 bool IsBanned(CNetAddr ip);
248 bool IsBanned(CSubNet subnet);
249 bool Unban(const CNetAddr &ip);
250 bool Unban(const CSubNet &ip);
251 void GetBanned(banmap_t &banmap);
252 void SetBanned(const banmap_t &banmap);
254 // This allows temporarily exceeding nMaxOutbound, with the goal of finding
255 // a peer that is better than all our current peers.
256 void SetTryNewOutboundPeer(bool flag);
257 bool GetTryNewOutboundPeer();
259 // Return the number of outbound peers we have in excess of our target (eg,
260 // if we previously called SetTryNewOutboundPeer(true), and have since set
261 // to false, we may have extra peers that we wish to disconnect). This may
262 // return a value less than (num_outbound_connections - num_outbound_slots)
263 // in cases where some outbound connections are not yet fully connected, or
264 // not yet fully disconnected.
265 int GetExtraOutboundCount();
267 bool AddNode(const std::string& node);
268 bool RemoveAddedNode(const std::string& node);
269 std::vector<AddedNodeInfo> GetAddedNodeInfo();
271 size_t GetNodeCount(NumConnections num);
272 void GetNodeStats(std::vector<CNodeStats>& vstats);
273 bool DisconnectNode(const std::string& node);
274 bool DisconnectNode(NodeId id);
276 ServiceFlags GetLocalServices() const;
278 //!set the max outbound target in bytes
279 void SetMaxOutboundTarget(uint64_t limit);
280 uint64_t GetMaxOutboundTarget();
282 //!set the timeframe for the max outbound target
283 void SetMaxOutboundTimeframe(uint64_t timeframe);
284 uint64_t GetMaxOutboundTimeframe();
286 //!check if the outbound target is reached
287 // if param historicalBlockServingLimit is set true, the function will
288 // response true if the limit for serving historical blocks has been reached
289 bool OutboundTargetReached(bool historicalBlockServingLimit);
291 //!response the bytes left in the current max outbound cycle
292 // in case of no limit, it will always response 0
293 uint64_t GetOutboundTargetBytesLeft();
295 //!response the time in second left in the current max outbound cycle
296 // in case of no limit, it will always response 0
297 uint64_t GetMaxOutboundTimeLeftInCycle();
299 uint64_t GetTotalBytesRecv();
300 uint64_t GetTotalBytesSent();
302 void SetBestHeight(int height);
303 int GetBestHeight() const;
305 /** Get a unique deterministic randomizer. */
306 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
308 unsigned int GetReceiveFloodSize() const;
310 void WakeMessageHandler();
311 private:
312 struct ListenSocket {
313 SOCKET socket;
314 bool whitelisted;
316 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
319 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
320 bool Bind(const CService &addr, unsigned int flags);
321 bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
322 void ThreadOpenAddedConnections();
323 void AddOneShot(const std::string& strDest);
324 void ProcessOneShot();
325 void ThreadOpenConnections(std::vector<std::string> connect);
326 void ThreadMessageHandler();
327 void AcceptConnection(const ListenSocket& hListenSocket);
328 void ThreadSocketHandler();
329 void ThreadDNSAddressSeed();
331 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
333 CNode* FindNode(const CNetAddr& ip);
334 CNode* FindNode(const CSubNet& subNet);
335 CNode* FindNode(const std::string& addrName);
336 CNode* FindNode(const CService& addr);
338 bool AttemptToEvictConnection();
339 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
340 bool IsWhitelistedRange(const CNetAddr &addr);
342 void DeleteNode(CNode* pnode);
344 NodeId GetNewNodeId();
346 size_t SocketSendData(CNode *pnode) const;
347 //!check is the banlist has unwritten changes
348 bool BannedSetIsDirty();
349 //!set the "dirty" flag for the banlist
350 void SetBannedSetDirty(bool dirty=true);
351 //!clean unused entries (if bantime has expired)
352 void SweepBanned();
353 void DumpAddresses();
354 void DumpData();
355 void DumpBanlist();
357 // Network stats
358 void RecordBytesRecv(uint64_t bytes);
359 void RecordBytesSent(uint64_t bytes);
361 // Whether the node should be passed out in ForEach* callbacks
362 static bool NodeFullyConnected(const CNode* pnode);
364 // Network usage totals
365 CCriticalSection cs_totalBytesRecv;
366 CCriticalSection cs_totalBytesSent;
367 uint64_t nTotalBytesRecv;
368 uint64_t nTotalBytesSent;
370 // outbound limit & stats
371 uint64_t nMaxOutboundTotalBytesSentInCycle;
372 uint64_t nMaxOutboundCycleStartTime;
373 uint64_t nMaxOutboundLimit;
374 uint64_t nMaxOutboundTimeframe;
376 // Whitelisted ranges. Any node connecting from these is automatically
377 // whitelisted (as well as those connecting to whitelisted binds).
378 std::vector<CSubNet> vWhitelistedRange;
380 unsigned int nSendBufferMaxSize;
381 unsigned int nReceiveFloodSize;
383 std::vector<ListenSocket> vhListenSocket;
384 std::atomic<bool> fNetworkActive;
385 banmap_t setBanned;
386 CCriticalSection cs_setBanned;
387 bool setBannedIsDirty;
388 bool fAddressesInitialized;
389 CAddrMan addrman;
390 std::deque<std::string> vOneShots;
391 CCriticalSection cs_vOneShots;
392 std::vector<std::string> vAddedNodes;
393 CCriticalSection cs_vAddedNodes;
394 std::vector<CNode*> vNodes;
395 std::list<CNode*> vNodesDisconnected;
396 mutable CCriticalSection cs_vNodes;
397 std::atomic<NodeId> nLastNodeId;
399 /** Services this instance offers */
400 ServiceFlags nLocalServices;
402 std::unique_ptr<CSemaphore> semOutbound;
403 std::unique_ptr<CSemaphore> semAddnode;
404 int nMaxConnections;
405 int nMaxOutbound;
406 int nMaxAddnode;
407 int nMaxFeeler;
408 std::atomic<int> nBestHeight;
409 CClientUIInterface* clientInterface;
410 NetEventsInterface* m_msgproc;
412 /** SipHasher seeds for deterministic randomness */
413 const uint64_t nSeed0, nSeed1;
415 /** flag for waking the message processor. */
416 bool fMsgProcWake;
418 std::condition_variable condMsgProc;
419 std::mutex mutexMsgProc;
420 std::atomic<bool> flagInterruptMsgProc;
422 CThreadInterrupt interruptNet;
424 std::thread threadDNSAddressSeed;
425 std::thread threadSocketHandler;
426 std::thread threadOpenAddedConnections;
427 std::thread threadOpenConnections;
428 std::thread threadMessageHandler;
430 /** flag for deciding to connect to an extra outbound peer,
431 * in excess of nMaxOutbound
432 * This takes the place of a feeler connection */
433 std::atomic_bool m_try_another_outbound_peer;
435 friend struct CConnmanTest;
437 extern std::unique_ptr<CConnman> g_connman;
438 void Discover(boost::thread_group& threadGroup);
439 void MapPort(bool fUseUPnP);
440 unsigned short GetListenPort();
441 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
443 struct CombinerAll
445 typedef bool result_type;
447 template<typename I>
448 bool operator()(I first, I last) const
450 while (first != last) {
451 if (!(*first)) return false;
452 ++first;
454 return true;
459 * Interface for message handling
461 class NetEventsInterface
463 public:
464 virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
465 virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
466 virtual void InitializeNode(CNode* pnode) = 0;
467 virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
470 enum
472 LOCAL_NONE, // unknown
473 LOCAL_IF, // address a local interface listens on
474 LOCAL_BIND, // address explicit bound to
475 LOCAL_UPNP, // address reported by UPnP
476 LOCAL_MANUAL, // address explicitly specified (-externalip=)
478 LOCAL_MAX
481 bool IsPeerAddrLocalGood(CNode *pnode);
482 void AdvertiseLocal(CNode *pnode);
483 void SetLimited(enum Network net, bool fLimited = true);
484 bool IsLimited(enum Network net);
485 bool IsLimited(const CNetAddr& addr);
486 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
487 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
488 bool RemoveLocal(const CService& addr);
489 bool SeenLocal(const CService& addr);
490 bool IsLocal(const CService& addr);
491 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
492 bool IsReachable(enum Network net);
493 bool IsReachable(const CNetAddr &addr);
494 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
497 extern bool fDiscover;
498 extern bool fListen;
499 extern bool fRelayTxes;
501 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
503 /** Subversion as sent to the P2P network in `version` messages */
504 extern std::string strSubVersion;
506 struct LocalServiceInfo {
507 int nScore;
508 int nPort;
511 extern CCriticalSection cs_mapLocalHost;
512 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
513 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
515 class CNodeStats
517 public:
518 NodeId nodeid;
519 ServiceFlags nServices;
520 bool fRelayTxes;
521 int64_t nLastSend;
522 int64_t nLastRecv;
523 int64_t nTimeConnected;
524 int64_t nTimeOffset;
525 std::string addrName;
526 int nVersion;
527 std::string cleanSubVer;
528 bool fInbound;
529 bool m_manual_connection;
530 int nStartingHeight;
531 uint64_t nSendBytes;
532 mapMsgCmdSize mapSendBytesPerMsgCmd;
533 uint64_t nRecvBytes;
534 mapMsgCmdSize mapRecvBytesPerMsgCmd;
535 bool fWhitelisted;
536 double dPingTime;
537 double dPingWait;
538 double dMinPing;
539 // Our address, as reported by the peer
540 std::string addrLocal;
541 // Address of this peer
542 CAddress addr;
543 // Bind address of our side of the connection
544 CAddress addrBind;
550 class CNetMessage {
551 private:
552 mutable CHash256 hasher;
553 mutable uint256 data_hash;
554 public:
555 bool in_data; // parsing header (false) or data (true)
557 CDataStream hdrbuf; // partially received header
558 CMessageHeader hdr; // complete header
559 unsigned int nHdrPos;
561 CDataStream vRecv; // received message data
562 unsigned int nDataPos;
564 int64_t nTime; // time (in microseconds) of message receipt.
566 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
567 hdrbuf.resize(24);
568 in_data = false;
569 nHdrPos = 0;
570 nDataPos = 0;
571 nTime = 0;
574 bool complete() const
576 if (!in_data)
577 return false;
578 return (hdr.nMessageSize == nDataPos);
581 const uint256& GetMessageHash() const;
583 void SetVersion(int nVersionIn)
585 hdrbuf.SetVersion(nVersionIn);
586 vRecv.SetVersion(nVersionIn);
589 int readHeader(const char *pch, unsigned int nBytes);
590 int readData(const char *pch, unsigned int nBytes);
594 /** Information about a peer */
595 class CNode
597 friend class CConnman;
598 public:
599 // socket
600 std::atomic<ServiceFlags> nServices;
601 SOCKET hSocket;
602 size_t nSendSize; // total size of all vSendMsg entries
603 size_t nSendOffset; // offset inside the first vSendMsg already sent
604 uint64_t nSendBytes;
605 std::deque<std::vector<unsigned char>> vSendMsg;
606 CCriticalSection cs_vSend;
607 CCriticalSection cs_hSocket;
608 CCriticalSection cs_vRecv;
610 CCriticalSection cs_vProcessMsg;
611 std::list<CNetMessage> vProcessMsg;
612 size_t nProcessQueueSize;
614 CCriticalSection cs_sendProcessing;
616 std::deque<CInv> vRecvGetData;
617 uint64_t nRecvBytes;
618 std::atomic<int> nRecvVersion;
620 std::atomic<int64_t> nLastSend;
621 std::atomic<int64_t> nLastRecv;
622 const int64_t nTimeConnected;
623 std::atomic<int64_t> nTimeOffset;
624 // Address of this peer
625 const CAddress addr;
626 // Bind address of our side of the connection
627 const CAddress addrBind;
628 std::atomic<int> nVersion;
629 // strSubVer is whatever byte array we read from the wire. However, this field is intended
630 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
631 // store the sanitized version in cleanSubVer. The original should be used when dealing with
632 // the network or wire types and the cleaned string used when displayed or logged.
633 std::string strSubVer, cleanSubVer;
634 CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
635 bool fWhitelisted; // This peer can bypass DoS banning.
636 bool fFeeler; // If true this node is being used as a short lived feeler.
637 bool fOneShot;
638 bool m_manual_connection;
639 bool fClient;
640 const bool fInbound;
641 std::atomic_bool fSuccessfullyConnected;
642 std::atomic_bool fDisconnect;
643 // We use fRelayTxes for two purposes -
644 // a) it allows us to not relay tx invs before receiving the peer's version message
645 // b) the peer may tell us in its version message that we should not relay tx invs
646 // unless it loads a bloom filter.
647 bool fRelayTxes; //protected by cs_filter
648 bool fSentAddr;
649 CSemaphoreGrant grantOutbound;
650 CCriticalSection cs_filter;
651 std::unique_ptr<CBloomFilter> pfilter;
652 std::atomic<int> nRefCount;
654 const uint64_t nKeyedNetGroup;
655 std::atomic_bool fPauseRecv;
656 std::atomic_bool fPauseSend;
657 protected:
659 mapMsgCmdSize mapSendBytesPerMsgCmd;
660 mapMsgCmdSize mapRecvBytesPerMsgCmd;
662 public:
663 uint256 hashContinue;
664 std::atomic<int> nStartingHeight;
666 // flood relay
667 std::vector<CAddress> vAddrToSend;
668 CRollingBloomFilter addrKnown;
669 bool fGetAddr;
670 std::set<uint256> setKnown;
671 int64_t nNextAddrSend;
672 int64_t nNextLocalAddrSend;
674 // inventory based relay
675 CRollingBloomFilter filterInventoryKnown;
676 // Set of transaction ids we still have to announce.
677 // They are sorted by the mempool before relay, so the order is not important.
678 std::set<uint256> setInventoryTxToSend;
679 // List of block ids we still have announce.
680 // There is no final sorting before sending, as they are always sent immediately
681 // and in the order requested.
682 std::vector<uint256> vInventoryBlockToSend;
683 CCriticalSection cs_inventory;
684 std::set<uint256> setAskFor;
685 std::multimap<int64_t, CInv> mapAskFor;
686 int64_t nNextInvSend;
687 // Used for headers announcements - unfiltered blocks to relay
688 // Also protected by cs_inventory
689 std::vector<uint256> vBlockHashesToAnnounce;
690 // Used for BIP35 mempool sending, also protected by cs_inventory
691 bool fSendMempool;
693 // Last time a "MEMPOOL" request was serviced.
694 std::atomic<int64_t> timeLastMempoolReq;
696 // Block and TXN accept times
697 std::atomic<int64_t> nLastBlockTime;
698 std::atomic<int64_t> nLastTXTime;
700 // Ping time measurement:
701 // The pong reply we're expecting, or 0 if no pong expected.
702 std::atomic<uint64_t> nPingNonceSent;
703 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
704 std::atomic<int64_t> nPingUsecStart;
705 // Last measured round-trip time.
706 std::atomic<int64_t> nPingUsecTime;
707 // Best measured round-trip time.
708 std::atomic<int64_t> nMinPingUsecTime;
709 // Whether a ping is requested.
710 std::atomic<bool> fPingQueued;
711 // Minimum fee rate with which to filter inv's to this node
712 CAmount minFeeFilter;
713 CCriticalSection cs_feeFilter;
714 CAmount lastSentFeeFilter;
715 int64_t nextSendTimeFeeFilter;
717 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);
718 ~CNode();
719 CNode(const CNode&) = delete;
720 CNode& operator=(const CNode&) = delete;
722 private:
723 const NodeId id;
724 const uint64_t nLocalHostNonce;
725 // Services offered to this peer
726 const ServiceFlags nLocalServices;
727 const int nMyStartingHeight;
728 int nSendVersion;
729 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
731 mutable CCriticalSection cs_addrName;
732 std::string addrName;
734 // Our address, as reported by the peer
735 CService addrLocal;
736 mutable CCriticalSection cs_addrLocal;
737 public:
739 NodeId GetId() const {
740 return id;
743 uint64_t GetLocalNonce() const {
744 return nLocalHostNonce;
747 int GetMyStartingHeight() const {
748 return nMyStartingHeight;
751 int GetRefCount() const
753 assert(nRefCount >= 0);
754 return nRefCount;
757 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
759 void SetRecvVersion(int nVersionIn)
761 nRecvVersion = nVersionIn;
763 int GetRecvVersion() const
765 return nRecvVersion;
767 void SetSendVersion(int nVersionIn);
768 int GetSendVersion() const;
770 CService GetAddrLocal() const;
771 //! May not be called more than once
772 void SetAddrLocal(const CService& addrLocalIn);
774 CNode* AddRef()
776 nRefCount++;
777 return this;
780 void Release()
782 nRefCount--;
787 void AddAddressKnown(const CAddress& _addr)
789 addrKnown.insert(_addr.GetKey());
792 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
794 // Known checking here is only to save space from duplicates.
795 // SendMessages will filter it again for knowns that were added
796 // after addresses were pushed.
797 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
798 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
799 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
800 } else {
801 vAddrToSend.push_back(_addr);
807 void AddInventoryKnown(const CInv& inv)
810 LOCK(cs_inventory);
811 filterInventoryKnown.insert(inv.hash);
815 void PushInventory(const CInv& inv)
817 LOCK(cs_inventory);
818 if (inv.type == MSG_TX) {
819 if (!filterInventoryKnown.contains(inv.hash)) {
820 setInventoryTxToSend.insert(inv.hash);
822 } else if (inv.type == MSG_BLOCK) {
823 vInventoryBlockToSend.push_back(inv.hash);
827 void PushBlockHash(const uint256 &hash)
829 LOCK(cs_inventory);
830 vBlockHashesToAnnounce.push_back(hash);
833 void AskFor(const CInv& inv);
835 void CloseSocketDisconnect();
837 void copyStats(CNodeStats &stats);
839 ServiceFlags GetLocalServices() const
841 return nLocalServices;
844 std::string GetAddrName() const;
845 //! Sets the addrName only if it was not previously set
846 void MaybeSetAddrName(const std::string& addrNameIn);
853 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
854 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
856 #endif // BITCOIN_NET_H