1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <addrdb.h>
10 #include <addrman.h>
11 #include <amount.h>
12 #include <bloom.h>
13 #include <chainparams.h>
14 #include <compat.h>
15 #include <crypto/siphash.h>
16 #include <hash.h>
17 #include <net_permissions.h>
18 #include <netaddress.h>
19 #include <optional.h>
20 #include <policy/feerate.h>
21 #include <protocol.h>
22 #include <random.h>
23 #include <streams.h>
24 #include <sync.h>
25 #include <threadinterrupt.h>
26 #include <uint256.h>
27 
28 #include <atomic>
29 #include <cstdint>
30 #include <deque>
31 #include <map>
32 #include <thread>
33 #include <memory>
34 #include <condition_variable>
35 
36 #ifndef WIN32
37 #include <arpa/inet.h>
38 #endif
39 
40 
41 class CScheduler;
42 class CNode;
43 class BanMan;
44 struct bilingual_str;
45 
46 /** Default for -whitelistrelay. */
47 static const bool DEFAULT_WHITELISTRELAY = true;
48 /** Default for -whitelistforcerelay. */
49 static const bool DEFAULT_WHITELISTFORCERELAY = false;
50 
51 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
52 static const int TIMEOUT_INTERVAL = 20 * 60;
53 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
54 static const int FEELER_INTERVAL = 120;
55 /** The maximum number of addresses from our addrman to return in response to a getaddr message. */
56 static constexpr size_t MAX_ADDR_TO_SEND = 1000;
57 /**
58  * Maximum length of incoming protocol messages (no message over 32 MiB is
59  * currently acceptable).  Bitcoin has 4 MiB here, but we need more space
60  * to allow for 2,000 block headers with auxpow.
61  */
62 /* FIXME: Once the headers size limit is deployed sufficiently in the network,
63    we may want to lower this again if it seems useful.  */
64 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 32 * 1024 * 1024;
65 /** Maximum length of the user agent string in `version` message */
66 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
67 /** Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc) */
68 static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
69 /** Maximum number of addnode outgoing nodes */
70 static const int MAX_ADDNODE_CONNECTIONS = 8;
71 /** Maximum number of block-relay-only outgoing connections */
72 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
73 /** Maximum number of feeler connections */
74 static const int MAX_FEELER_CONNECTIONS = 1;
75 /** -listen default */
76 static const bool DEFAULT_LISTEN = true;
77 /** -upnp default */
78 #ifdef USE_UPNP
79 static const bool DEFAULT_UPNP = USE_UPNP;
80 #else
81 static const bool DEFAULT_UPNP = false;
82 #endif
83 /** The maximum number of peer connections to maintain. */
84 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
85 /** The default for -maxuploadtarget. 0 = Unlimited */
86 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
87 /** The default timeframe for -maxuploadtarget. 1 day. */
88 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
89 /** Default for blocks only*/
90 static const bool DEFAULT_BLOCKSONLY = false;
91 /** -peertimeout default */
92 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
93 
94 static const bool DEFAULT_FORCEDNSSEED = false;
95 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
96 static const size_t DEFAULT_MAXSENDBUFFER    = 1 * 1000;
97 
98 typedef int64_t NodeId;
99 
100 struct AddedNodeInfo
101 {
102     std::string strAddedNode;
103     CService resolvedAddress;
104     bool fConnected;
105     bool fInbound;
106 };
107 
108 class CNodeStats;
109 class CClientUIInterface;
110 
111 struct CSerializedNetMsg
112 {
113     CSerializedNetMsg() = default;
114     CSerializedNetMsg(CSerializedNetMsg&&) = default;
115     CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
116     // No copying, only moves.
117     CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
118     CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
119 
120     std::vector<unsigned char> data;
121     std::string m_type;
122 };
123 
124 /** Different types of connections to a peer. This enum encapsulates the
125  * information we have available at the time of opening or accepting the
126  * connection. Aside from INBOUND, all types are initiated by us.
127  *
128  * If adding or removing types, please update CONNECTION_TYPE_DOC in
129  * src/rpc/net.cpp. */
130 enum class ConnectionType {
131     /**
132      * Inbound connections are those initiated by a peer. This is the only
133      * property we know at the time of connection, until P2P messages are
134      * exchanged.
135      */
136     INBOUND,
137 
138     /**
139      * These are the default connections that we use to connect with the
140      * network. There is no restriction on what is relayed- by default we relay
141      * blocks, addresses & transactions. We automatically attempt to open
142      * MAX_OUTBOUND_FULL_RELAY_CONNECTIONS using addresses from our AddrMan.
143      */
144     OUTBOUND_FULL_RELAY,
145 
146 
147     /**
148      * We open manual connections to addresses that users explicitly inputted
149      * via the addnode RPC, or the -connect command line argument. Even if a
150      * manual connection is misbehaving, we do not automatically disconnect or
151      * add it to our discouragement filter.
152      */
153     MANUAL,
154 
155     /**
156      * Feeler connections are short-lived connections made to check that a node
157      * is alive. They can be useful for:
158      * - test-before-evict: if one of the peers is considered for eviction from
159      *   our AddrMan because another peer is mapped to the same slot in the tried table,
160      *   evict only if this longer-known peer is offline.
161      * - move node addresses from New to Tried table, so that we have more
162      *   connectable addresses in our AddrMan.
163      * Note that in the literature ("Eclipse Attacks on Bitcoin’s Peer-to-Peer Network")
164      * only the latter feature is referred to as "feeler connections",
165      * although in our codebase feeler connections encompass test-before-evict as well.
166      * We make these connections approximately every FEELER_INTERVAL:
167      * first we resolve previously found collisions if they exist (test-before-evict),
168      * otherwise connect to a node from the new table.
169      */
170     FEELER,
171 
172     /**
173      * We use block-relay-only connections to help prevent against partition
174      * attacks. By not relaying transactions or addresses, these connections
175      * are harder to detect by a third party, thus helping obfuscate the
176      * network topology. We automatically attempt to open
177      * MAX_BLOCK_RELAY_ONLY_ANCHORS using addresses from our anchors.dat. Then
178      * addresses from our AddrMan if MAX_BLOCK_RELAY_ONLY_CONNECTIONS
179      * isn't reached yet.
180      */
181     BLOCK_RELAY,
182 
183     /**
184      * AddrFetch connections are short lived connections used to solicit
185      * addresses from peers. These are initiated to addresses submitted via the
186      * -seednode command line argument, or under certain conditions when the
187      * AddrMan is empty.
188      */
189     ADDR_FETCH,
190 };
191 
192 class NetEventsInterface;
193 class CConnman
194 {
195 public:
196 
197     enum NumConnections {
198         CONNECTIONS_NONE = 0,
199         CONNECTIONS_IN = (1U << 0),
200         CONNECTIONS_OUT = (1U << 1),
201         CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
202     };
203 
204     struct Options
205     {
206         ServiceFlags nLocalServices = NODE_NONE;
207         int nMaxConnections = 0;
208         int m_max_outbound_full_relay = 0;
209         int m_max_outbound_block_relay = 0;
210         int nMaxAddnode = 0;
211         int nMaxFeeler = 0;
212         int nBestHeight = 0;
213         CClientUIInterface* uiInterface = nullptr;
214         NetEventsInterface* m_msgproc = nullptr;
215         BanMan* m_banman = nullptr;
216         unsigned int nSendBufferMaxSize = 0;
217         unsigned int nReceiveFloodSize = 0;
218         uint64_t nMaxOutboundTimeframe = 0;
219         uint64_t nMaxOutboundLimit = 0;
220         int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
221         std::vector<std::string> vSeedNodes;
222         std::vector<NetWhitelistPermissions> vWhitelistedRange;
223         std::vector<NetWhitebindPermissions> vWhiteBinds;
224         std::vector<CService> vBinds;
225         std::vector<CService> onion_binds;
226         bool m_use_addrman_outgoing = true;
227         std::vector<std::string> m_specified_outgoing;
228         std::vector<std::string> m_added_nodes;
229         std::vector<bool> m_asmap;
230     };
231 
Init(const Options & connOptions)232     void Init(const Options& connOptions) {
233         nLocalServices = connOptions.nLocalServices;
234         nMaxConnections = connOptions.nMaxConnections;
235         m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
236         m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
237         m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
238         nMaxAddnode = connOptions.nMaxAddnode;
239         nMaxFeeler = connOptions.nMaxFeeler;
240         m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
241         nBestHeight = connOptions.nBestHeight;
242         clientInterface = connOptions.uiInterface;
243         m_banman = connOptions.m_banman;
244         m_msgproc = connOptions.m_msgproc;
245         nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
246         nReceiveFloodSize = connOptions.nReceiveFloodSize;
247         m_peer_connect_timeout = connOptions.m_peer_connect_timeout;
248         {
249             LOCK(cs_totalBytesSent);
250             nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
251             nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
252         }
253         vWhitelistedRange = connOptions.vWhitelistedRange;
254         {
255             LOCK(cs_vAddedNodes);
256             vAddedNodes = connOptions.m_added_nodes;
257         }
258         m_onion_binds = connOptions.onion_binds;
259     }
260 
261     CConnman(uint64_t seed0, uint64_t seed1, bool network_active = true);
262     ~CConnman();
263     bool Start(CScheduler& scheduler, const Options& options);
264 
265     void StopThreads();
266     void StopNodes();
Stop()267     void Stop()
268     {
269         StopThreads();
270         StopNodes();
271     };
272 
273     void Interrupt();
GetNetworkActive()274     bool GetNetworkActive() const { return fNetworkActive; };
GetUseAddrmanOutgoing()275     bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
276     void SetNetworkActive(bool active);
277     void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
278     bool CheckIncomingNonce(uint64_t nonce);
279 
280     bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
281 
282     void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
283 
284     using NodeFn = std::function<void(CNode*)>;
ForEachNode(const NodeFn & func)285     void ForEachNode(const NodeFn& func)
286     {
287         LOCK(cs_vNodes);
288         for (auto&& node : vNodes) {
289             if (NodeFullyConnected(node))
290                 func(node);
291         }
292     };
293 
ForEachNode(const NodeFn & func)294     void ForEachNode(const NodeFn& func) const
295     {
296         LOCK(cs_vNodes);
297         for (auto&& node : vNodes) {
298             if (NodeFullyConnected(node))
299                 func(node);
300         }
301     };
302 
303     template<typename Callable, typename CallableAfter>
ForEachNodeThen(Callable && pre,CallableAfter && post)304     void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
305     {
306         LOCK(cs_vNodes);
307         for (auto&& node : vNodes) {
308             if (NodeFullyConnected(node))
309                 pre(node);
310         }
311         post();
312     };
313 
314     template<typename Callable, typename CallableAfter>
ForEachNodeThen(Callable && pre,CallableAfter && post)315     void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
316     {
317         LOCK(cs_vNodes);
318         for (auto&& node : vNodes) {
319             if (NodeFullyConnected(node))
320                 pre(node);
321         }
322         post();
323     };
324 
325     // Addrman functions
326     void SetServices(const CService &addr, ServiceFlags nServices);
327     void MarkAddressGood(const CAddress& addr);
328     bool AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
329     std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct);
330     /**
331      * Cache is used to minimize topology leaks, so it should
332      * be used for all non-trusted calls, for example, p2p.
333      * A non-malicious call (from RPC or a peer with addr permission) should
334      * call the function without a parameter to avoid using the cache.
335      */
336     std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
337 
338     // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
339     // a peer that is better than all our current peers.
340     void SetTryNewOutboundPeer(bool flag);
341     bool GetTryNewOutboundPeer();
342 
343     // Return the number of outbound peers we have in excess of our target (eg,
344     // if we previously called SetTryNewOutboundPeer(true), and have since set
345     // to false, we may have extra peers that we wish to disconnect). This may
346     // return a value less than (num_outbound_connections - num_outbound_slots)
347     // in cases where some outbound connections are not yet fully connected, or
348     // not yet fully disconnected.
349     int GetExtraOutboundCount();
350 
351     bool AddNode(const std::string& node);
352     bool RemoveAddedNode(const std::string& node);
353     std::vector<AddedNodeInfo> GetAddedNodeInfo();
354 
355     size_t GetNodeCount(NumConnections num);
356     void GetNodeStats(std::vector<CNodeStats>& vstats);
357     bool DisconnectNode(const std::string& node);
358     bool DisconnectNode(const CSubNet& subnet);
359     bool DisconnectNode(const CNetAddr& addr);
360     bool DisconnectNode(NodeId id);
361 
362     //! Used to convey which local services we are offering peers during node
363     //! connection.
364     //!
365     //! The data returned by this is used in CNode construction,
366     //! which is used to advertise which services we are offering
367     //! that peer during `net_processing.cpp:PushNodeVersion()`.
368     ServiceFlags GetLocalServices() const;
369 
370     //!set the max outbound target in bytes
371     void SetMaxOutboundTarget(uint64_t limit);
372     uint64_t GetMaxOutboundTarget();
373 
374     //!set the timeframe for the max outbound target
375     void SetMaxOutboundTimeframe(uint64_t timeframe);
376     uint64_t GetMaxOutboundTimeframe();
377 
378     //! check if the outbound target is reached
379     //! if param historicalBlockServingLimit is set true, the function will
380     //! response true if the limit for serving historical blocks has been reached
381     bool OutboundTargetReached(bool historicalBlockServingLimit);
382 
383     //! response the bytes left in the current max outbound cycle
384     //! in case of no limit, it will always response 0
385     uint64_t GetOutboundTargetBytesLeft();
386 
387     //! response the time in second left in the current max outbound cycle
388     //! in case of no limit, it will always response 0
389     uint64_t GetMaxOutboundTimeLeftInCycle();
390 
391     uint64_t GetTotalBytesRecv();
392     uint64_t GetTotalBytesSent();
393 
394     void SetBestHeight(int height);
395     int GetBestHeight() const;
396 
397     /** Get a unique deterministic randomizer. */
398     CSipHasher GetDeterministicRandomizer(uint64_t id) const;
399 
400     unsigned int GetReceiveFloodSize() const;
401 
402     void WakeMessageHandler();
403 
404     /** Attempts to obfuscate tx time through exponentially distributed emitting.
405         Works assuming that a single interval is used.
406         Variable intervals will result in privacy decrease.
407     */
408     int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds);
409 
SetAsmap(std::vector<bool> asmap)410     void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
411 
412 private:
413     struct ListenSocket {
414     public:
415         SOCKET socket;
AddSocketPermissionFlagsListenSocket416         inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
ListenSocketListenSocket417         ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
418     private:
419         NetPermissionFlags m_permissions;
420     };
421 
422     bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
423     bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
424     bool InitBinds(
425         const std::vector<CService>& binds,
426         const std::vector<NetWhitebindPermissions>& whiteBinds,
427         const std::vector<CService>& onion_binds);
428 
429     void ThreadOpenAddedConnections();
430     void AddAddrFetch(const std::string& strDest);
431     void ProcessAddrFetch();
432     void ThreadOpenConnections(std::vector<std::string> connect);
433     void ThreadMessageHandler();
434     void AcceptConnection(const ListenSocket& hListenSocket);
435     void DisconnectNodes();
436     void NotifyNumConnectionsChanged();
437     void InactivityCheck(CNode *pnode);
438     bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
439     void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
440     void SocketHandler();
441     void ThreadSocketHandler();
442     void ThreadDNSAddressSeed();
443 
444     uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
445 
446     CNode* FindNode(const CNetAddr& ip);
447     CNode* FindNode(const CSubNet& subNet);
448     CNode* FindNode(const std::string& addrName);
449     CNode* FindNode(const CService& addr);
450 
451     /**
452      * Determine whether we're already connected to a given address, in order to
453      * avoid initiating duplicate connections.
454      */
455     bool AlreadyConnectedToAddress(const CAddress& addr);
456 
457     bool AttemptToEvictConnection();
458     CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
459     void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
460 
461     void DeleteNode(CNode* pnode);
462 
463     NodeId GetNewNodeId();
464 
465     size_t SocketSendData(CNode *pnode) const;
466     void DumpAddresses();
467 
468     // Network stats
469     void RecordBytesRecv(uint64_t bytes);
470     void RecordBytesSent(uint64_t bytes);
471 
472     /**
473      * Return vector of current BLOCK_RELAY peers.
474      */
475     std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
476 
477     // Whether the node should be passed out in ForEach* callbacks
478     static bool NodeFullyConnected(const CNode* pnode);
479 
480     // Network usage totals
481     RecursiveMutex cs_totalBytesRecv;
482     RecursiveMutex cs_totalBytesSent;
GUARDED_BY(cs_totalBytesRecv)483     uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
GUARDED_BY(cs_totalBytesSent)484     uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
485 
486     // outbound limit & stats
487     uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
488     uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
489     uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
490     uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
491 
492     // P2P timeout in seconds
493     int64_t m_peer_connect_timeout;
494 
495     // Whitelisted ranges. Any node connecting from these is automatically
496     // whitelisted (as well as those connecting to whitelisted binds).
497     std::vector<NetWhitelistPermissions> vWhitelistedRange;
498 
499     unsigned int nSendBufferMaxSize{0};
500     unsigned int nReceiveFloodSize{0};
501 
502     std::vector<ListenSocket> vhListenSocket;
503     std::atomic<bool> fNetworkActive{true};
504     bool fAddressesInitialized{false};
505     CAddrMan addrman;
506     std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
507     RecursiveMutex m_addr_fetches_mutex;
508     std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
509     RecursiveMutex cs_vAddedNodes;
510     std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
511     std::list<CNode*> vNodesDisconnected;
512     mutable RecursiveMutex cs_vNodes;
513     std::atomic<NodeId> nLastNodeId{0};
514     unsigned int nPrevNodeCount{0};
515 
516     /**
517      * Cache responses to addr requests to minimize privacy leak.
518      * Attack example: scraping addrs in real-time may allow an attacker
519      * to infer new connections of the victim by detecting new records
520      * with fresh timestamps (per self-announcement).
521      */
522     struct CachedAddrResponse {
523         std::vector<CAddress> m_addrs_response_cache;
524         std::chrono::microseconds m_cache_entry_expiration{0};
525     };
526 
527     /**
528      * Addr responses stored in different caches
529      * per (network, local socket) prevent cross-network node identification.
530      * If a node for example is multi-homed under Tor and IPv6,
531      * a single cache (or no cache at all) would let an attacker
532      * to easily detect that it is the same node by comparing responses.
533      * Indexing by local socket prevents leakage when a node has multiple
534      * listening addresses on the same network.
535      *
536      * The used memory equals to 1000 CAddress records (or around 40 bytes) per
537      * distinct Network (up to 5) we have/had an inbound peer from,
538      * resulting in at most ~196 KB. Every separate local socket may
539      * add up to ~196 KB extra.
540      */
541     std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
542 
543     /**
544      * Services this instance offers.
545      *
546      * This data is replicated in each CNode instance we create during peer
547      * connection (in ConnectNode()) under a member also called
548      * nLocalServices.
549      *
550      * This data is not marked const, but after being set it should not
551      * change. See the note in CNode::nLocalServices documentation.
552      *
553      * \sa CNode::nLocalServices
554      */
555     ServiceFlags nLocalServices;
556 
557     std::unique_ptr<CSemaphore> semOutbound;
558     std::unique_ptr<CSemaphore> semAddnode;
559     int nMaxConnections;
560 
561     // How many full-relay (tx, block, addr) outbound peers we want
562     int m_max_outbound_full_relay;
563 
564     // How many block-relay only outbound peers we want
565     // We do not relay tx or addr messages with these peers
566     int m_max_outbound_block_relay;
567 
568     int nMaxAddnode;
569     int nMaxFeeler;
570     int m_max_outbound;
571     bool m_use_addrman_outgoing;
572     std::atomic<int> nBestHeight;
573     CClientUIInterface* clientInterface;
574     NetEventsInterface* m_msgproc;
575     /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
576     BanMan* m_banman;
577 
578     /**
579      * Addresses that were saved during the previous clean shutdown. We'll
580      * attempt to make block-relay-only connections to them.
581      */
582     std::vector<CAddress> m_anchors;
583 
584     /** SipHasher seeds for deterministic randomness */
585     const uint64_t nSeed0, nSeed1;
586 
587     /** flag for waking the message processor. */
588     bool fMsgProcWake GUARDED_BY(mutexMsgProc);
589 
590     std::condition_variable condMsgProc;
591     Mutex mutexMsgProc;
592     std::atomic<bool> flagInterruptMsgProc{false};
593 
594     CThreadInterrupt interruptNet;
595 
596     std::thread threadDNSAddressSeed;
597     std::thread threadSocketHandler;
598     std::thread threadOpenAddedConnections;
599     std::thread threadOpenConnections;
600     std::thread threadMessageHandler;
601 
602     /** flag for deciding to connect to an extra outbound peer,
603      *  in excess of m_max_outbound_full_relay
604      *  This takes the place of a feeler connection */
605     std::atomic_bool m_try_another_outbound_peer;
606 
607     std::atomic<int64_t> m_next_send_inv_to_incoming{0};
608 
609     /**
610      * A vector of -bind=<address>:<port>=onion arguments each of which is
611      * an address and port that are designated for incoming Tor connections.
612      */
613     std::vector<CService> m_onion_binds;
614 
615     friend struct CConnmanTest;
616     friend struct ConnmanTestMsg;
617 };
618 void Discover();
619 void StartMapPort();
620 void InterruptMapPort();
621 void StopMapPort();
622 uint16_t GetListenPort();
623 
624 /**
625  * Interface for message handling
626  */
627 class NetEventsInterface
628 {
629 public:
630     virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
631     virtual bool SendMessages(CNode* pnode) = 0;
632     virtual void InitializeNode(CNode* pnode) = 0;
633     virtual void FinalizeNode(const CNode& node, bool& update_connection_time) = 0;
634 
635 protected:
636     /**
637      * Protected destructor so that instances can only be deleted by derived classes.
638      * If that restriction is no longer desired, this should be made public and virtual.
639      */
640     ~NetEventsInterface() = default;
641 };
642 
643 enum
644 {
645     LOCAL_NONE,   // unknown
646     LOCAL_IF,     // address a local interface listens on
647     LOCAL_BIND,   // address explicit bound to
648     LOCAL_UPNP,   // address reported by UPnP
649     LOCAL_MANUAL, // address explicitly specified (-externalip=)
650 
651     LOCAL_MAX
652 };
653 
654 bool IsPeerAddrLocalGood(CNode *pnode);
655 void AdvertiseLocal(CNode *pnode);
656 
657 /**
658  * Mark a network as reachable or unreachable (no automatic connects to it)
659  * @note Networks are reachable by default
660  */
661 void SetReachable(enum Network net, bool reachable);
662 /** @returns true if the network is reachable, false otherwise */
663 bool IsReachable(enum Network net);
664 /** @returns true if the address is in a reachable network, false otherwise */
665 bool IsReachable(const CNetAddr& addr);
666 
667 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
668 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
669 void RemoveLocal(const CService& addr);
670 bool SeenLocal(const CService& addr);
671 bool IsLocal(const CService& addr);
672 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
673 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
674 
675 
676 extern bool fDiscover;
677 extern bool fListen;
678 extern bool g_relay_txes;
679 
680 /** Subversion as sent to the P2P network in `version` messages */
681 extern std::string strSubVersion;
682 
683 struct LocalServiceInfo {
684     int nScore;
685     int nPort;
686 };
687 
688 extern RecursiveMutex cs_mapLocalHost;
689 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
690 
691 extern const std::string NET_MESSAGE_COMMAND_OTHER;
692 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
693 
694 class CNodeStats
695 {
696 public:
697     NodeId nodeid;
698     ServiceFlags nServices;
699     bool fRelayTxes;
700     int64_t nLastSend;
701     int64_t nLastRecv;
702     int64_t nLastTXTime;
703     int64_t nLastBlockTime;
704     int64_t nTimeConnected;
705     int64_t nTimeOffset;
706     std::string addrName;
707     int nVersion;
708     std::string cleanSubVer;
709     bool fInbound;
710     bool m_manual_connection;
711     int nStartingHeight;
712     uint64_t nSendBytes;
713     mapMsgCmdSize mapSendBytesPerMsgCmd;
714     uint64_t nRecvBytes;
715     mapMsgCmdSize mapRecvBytesPerMsgCmd;
716     NetPermissionFlags m_permissionFlags;
717     bool m_legacyWhitelisted;
718     int64_t m_ping_usec;
719     int64_t m_ping_wait_usec;
720     int64_t m_min_ping_usec;
721     CAmount minFeeFilter;
722     // Our address, as reported by the peer
723     std::string addrLocal;
724     // Address of this peer
725     CAddress addr;
726     // Bind address of our side of the connection
727     CAddress addrBind;
728     // Name of the network the peer connected through
729     std::string m_network;
730     uint32_t m_mapped_as;
731     std::string m_conn_type_string;
732 };
733 
734 
735 
736 /** Transport protocol agnostic message container.
737  * Ideally it should only contain receive time, payload,
738  * command and size.
739  */
740 class CNetMessage {
741 public:
742     CDataStream m_recv;                  //!< received message data
743     std::chrono::microseconds m_time{0}; //!< time of message receipt
744     uint32_t m_message_size{0};          //!< size of the payload
745     uint32_t m_raw_message_size{0};      //!< used wire size of the message (including header/checksum)
746     std::string m_command;
747 
CNetMessage(CDataStream && recv_in)748     CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
749 
SetVersion(int nVersionIn)750     void SetVersion(int nVersionIn)
751     {
752         m_recv.SetVersion(nVersionIn);
753     }
754 };
755 
756 /** The TransportDeserializer takes care of holding and deserializing the
757  * network receive buffer. It can deserialize the network buffer into a
758  * transport protocol agnostic CNetMessage (command & payload)
759  */
760 class TransportDeserializer {
761 public:
762     // returns true if the current deserialization is complete
763     virtual bool Complete() const = 0;
764     // set the serialization context version
765     virtual void SetVersion(int version) = 0;
766     // read and deserialize data
767     virtual int Read(const char *data, unsigned int bytes) = 0;
768     // decomposes a message from the context
769     virtual Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
~TransportDeserializer()770     virtual ~TransportDeserializer() {}
771 };
772 
773 class V1TransportDeserializer final : public TransportDeserializer
774 {
775 private:
776     const CChainParams& m_chain_params;
777     const NodeId m_node_id; // Only for logging
778     mutable CHash256 hasher;
779     mutable uint256 data_hash;
780     bool in_data;                   // parsing header (false) or data (true)
781     CDataStream hdrbuf;             // partially received header
782     CMessageHeader hdr;             // complete header
783     CDataStream vRecv;              // received message data
784     unsigned int nHdrPos;
785     unsigned int nDataPos;
786 
787     const uint256& GetMessageHash() const;
788     int readHeader(const char *pch, unsigned int nBytes);
789     int readData(const char *pch, unsigned int nBytes);
790 
Reset()791     void Reset() {
792         vRecv.clear();
793         hdrbuf.clear();
794         hdrbuf.resize(24);
795         in_data = false;
796         nHdrPos = 0;
797         nDataPos = 0;
798         data_hash.SetNull();
799         hasher.Reset();
800     }
801 
802 public:
V1TransportDeserializer(const CChainParams & chain_params,const NodeId node_id,int nTypeIn,int nVersionIn)803     V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
804         : m_chain_params(chain_params),
805           m_node_id(node_id),
806           hdrbuf(nTypeIn, nVersionIn),
807           vRecv(nTypeIn, nVersionIn)
808     {
809         Reset();
810     }
811 
Complete()812     bool Complete() const override
813     {
814         if (!in_data)
815             return false;
816         return (hdr.nMessageSize == nDataPos);
817     }
SetVersion(int nVersionIn)818     void SetVersion(int nVersionIn) override
819     {
820         hdrbuf.SetVersion(nVersionIn);
821         vRecv.SetVersion(nVersionIn);
822     }
Read(const char * pch,unsigned int nBytes)823     int Read(const char *pch, unsigned int nBytes) override {
824         int ret = in_data ? readData(pch, nBytes) : readHeader(pch, nBytes);
825         if (ret < 0) Reset();
826         return ret;
827     }
828     Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size) override;
829 };
830 
831 /** The TransportSerializer prepares messages for the network transport
832  */
833 class TransportSerializer {
834 public:
835     // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
836     virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
~TransportSerializer()837     virtual ~TransportSerializer() {}
838 };
839 
840 class V1TransportSerializer  : public TransportSerializer {
841 public:
842     void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
843 };
844 
845 /** Information about a peer */
846 class CNode
847 {
848     friend class CConnman;
849     friend struct ConnmanTestMsg;
850 
851 public:
852     std::unique_ptr<TransportDeserializer> m_deserializer;
853     std::unique_ptr<TransportSerializer> m_serializer;
854 
855     // socket
856     std::atomic<ServiceFlags> nServices{NODE_NONE};
857     SOCKET hSocket GUARDED_BY(cs_hSocket);
858     size_t nSendSize{0}; // total size of all vSendMsg entries
859     size_t nSendOffset{0}; // offset inside the first vSendMsg already sent
GUARDED_BY(cs_vSend)860     uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
861     std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
862     RecursiveMutex cs_vSend;
863     RecursiveMutex cs_hSocket;
864     RecursiveMutex cs_vRecv;
865 
866     RecursiveMutex cs_vProcessMsg;
867     std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
868     size_t nProcessQueueSize{0};
869 
870     RecursiveMutex cs_sendProcessing;
871 
GUARDED_BY(cs_vRecv)872     uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
873 
874     std::atomic<int64_t> nLastSend{0};
875     std::atomic<int64_t> nLastRecv{0};
876     const int64_t nTimeConnected;
877     std::atomic<int64_t> nTimeOffset{0};
878     // Address of this peer
879     const CAddress addr;
880     // Bind address of our side of the connection
881     const CAddress addrBind;
882     std::atomic<int> nVersion{0};
883     RecursiveMutex cs_SubVer;
884     /**
885      * cleanSubVer is a sanitized string of the user agent byte array we read
886      * from the wire. This cleaned string can safely be logged or displayed.
887      */
GUARDED_BY(cs_SubVer)888     std::string cleanSubVer GUARDED_BY(cs_SubVer){};
889     bool m_prefer_evict{false}; // This peer is preferred for eviction.
HasPermission(NetPermissionFlags permission)890     bool HasPermission(NetPermissionFlags permission) const {
891         return NetPermissions::HasFlag(m_permissionFlags, permission);
892     }
893     // This boolean is unusued in actual processing, only present for backward compatibility at RPC/QT level
894     bool m_legacyWhitelisted{false};
895     bool fClient{false}; // set by version message
896     bool m_limited_node{false}; //after BIP159, set by version message
897     /**
898      * Whether the peer has signaled support for receiving ADDRv2 (BIP155)
899      * messages, implying a preference to receive ADDRv2 instead of ADDR ones.
900      */
901     std::atomic_bool m_wants_addrv2{false};
902     std::atomic_bool fSuccessfullyConnected{false};
903     // Setting fDisconnect to true will cause the node to be disconnected the
904     // next time DisconnectNodes() runs
905     std::atomic_bool fDisconnect{false};
906     bool fSentAddr{false};
907     CSemaphoreGrant grantOutbound;
908     std::atomic<int> nRefCount{0};
909 
910     const uint64_t nKeyedNetGroup;
911     std::atomic_bool fPauseRecv{false};
912     std::atomic_bool fPauseSend{false};
913 
IsOutboundOrBlockRelayConn()914     bool IsOutboundOrBlockRelayConn() const {
915         switch (m_conn_type) {
916             case ConnectionType::OUTBOUND_FULL_RELAY:
917             case ConnectionType::BLOCK_RELAY:
918                 return true;
919             case ConnectionType::INBOUND:
920             case ConnectionType::MANUAL:
921             case ConnectionType::ADDR_FETCH:
922             case ConnectionType::FEELER:
923                 return false;
924         } // no default case, so the compiler can warn about missing cases
925 
926         assert(false);
927     }
928 
IsFullOutboundConn()929     bool IsFullOutboundConn() const {
930         return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
931     }
932 
IsManualConn()933     bool IsManualConn() const {
934         return m_conn_type == ConnectionType::MANUAL;
935     }
936 
IsBlockOnlyConn()937     bool IsBlockOnlyConn() const {
938         return m_conn_type == ConnectionType::BLOCK_RELAY;
939     }
940 
IsFeelerConn()941     bool IsFeelerConn() const {
942         return m_conn_type == ConnectionType::FEELER;
943     }
944 
IsAddrFetchConn()945     bool IsAddrFetchConn() const {
946         return m_conn_type == ConnectionType::ADDR_FETCH;
947     }
948 
IsInboundConn()949     bool IsInboundConn() const {
950         return m_conn_type == ConnectionType::INBOUND;
951     }
952 
953     /* Whether we send addr messages over this connection */
RelayAddrsWithConn()954     bool RelayAddrsWithConn() const
955     {
956         return m_conn_type != ConnectionType::BLOCK_RELAY;
957     }
958 
ExpectServicesFromConn()959     bool ExpectServicesFromConn() const {
960         switch (m_conn_type) {
961             case ConnectionType::INBOUND:
962             case ConnectionType::MANUAL:
963             case ConnectionType::FEELER:
964                 return false;
965             case ConnectionType::OUTBOUND_FULL_RELAY:
966             case ConnectionType::BLOCK_RELAY:
967             case ConnectionType::ADDR_FETCH:
968                 return true;
969         } // no default case, so the compiler can warn about missing cases
970 
971         assert(false);
972     }
973 
974     /**
975      * Get network the peer connected through.
976      *
977      * Returns Network::NET_ONION for *inbound* onion connections,
978      * and CNetAddr::GetNetClass() otherwise. The latter cannot be used directly
979      * because it doesn't detect the former, and it's not the responsibility of
980      * the CNetAddr class to know the actual network a peer is connected through.
981      *
982      * @return network the peer connected through.
983      */
984     Network ConnectedThroughNetwork() const;
985 
986 protected:
987     mapMsgCmdSize mapSendBytesPerMsgCmd;
988     mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
989 
990 public:
991     uint256 hashContinue;
992     std::atomic<int> nStartingHeight{-1};
993 
994     // flood relay
995     std::vector<CAddress> vAddrToSend;
996     std::unique_ptr<CRollingBloomFilter> m_addr_known{nullptr};
997     bool fGetAddr{false};
GUARDED_BY(cs_sendProcessing)998     std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
GUARDED_BY(cs_sendProcessing)999     std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
1000 
1001     // List of block ids we still have announce.
1002     // There is no final sorting before sending, as they are always sent immediately
1003     // and in the order requested.
1004     std::vector<uint256> vInventoryBlockToSend GUARDED_BY(cs_inventory);
1005     Mutex cs_inventory;
1006 
1007     struct TxRelay {
1008         mutable RecursiveMutex cs_filter;
1009         // We use fRelayTxes for two purposes -
1010         // a) it allows us to not relay tx invs before receiving the peer's version message
1011         // b) the peer may tell us in its version message that we should not relay tx invs
1012         //    unless it loads a bloom filter.
GUARDED_BYTxRelay1013         bool fRelayTxes GUARDED_BY(cs_filter){false};
PT_GUARDED_BYTxRelay1014         std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
1015 
1016         mutable RecursiveMutex cs_tx_inventory;
GUARDED_BYTxRelay1017         CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
1018         // Set of transaction ids we still have to announce.
1019         // They are sorted by the mempool before relay, so the order is not important.
1020         std::set<uint256> setInventoryTxToSend;
1021         // Used for BIP35 mempool sending
GUARDED_BYTxRelay1022         bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
1023         // Last time a "MEMPOOL" request was serviced.
1024         std::atomic<std::chrono::seconds> m_last_mempool_req{std::chrono::seconds{0}};
1025         std::chrono::microseconds nNextInvSend{0};
1026 
1027         RecursiveMutex cs_feeFilter;
1028         // Minimum fee rate with which to filter inv's to this node
GUARDED_BYTxRelay1029         CAmount minFeeFilter GUARDED_BY(cs_feeFilter){0};
1030         CAmount lastSentFeeFilter{0};
1031         int64_t nextSendTimeFeeFilter{0};
1032     };
1033 
1034     // m_tx_relay == nullptr if we're not relaying transactions with this peer
1035     std::unique_ptr<TxRelay> m_tx_relay;
1036 
1037     // Used for headers announcements - unfiltered blocks to relay
1038     std::vector<uint256> vBlockHashesToAnnounce GUARDED_BY(cs_inventory);
1039 
1040     /** UNIX epoch time of the last block received from this peer that we had
1041      * not yet seen (e.g. not already received from another peer), that passed
1042      * preliminary validity checks and was saved to disk, even if we don't
1043      * connect the block or it eventually fails connection. Used as an inbound
1044      * peer eviction criterium in CConnman::AttemptToEvictConnection. */
1045     std::atomic<int64_t> nLastBlockTime{0};
1046 
1047     /** UNIX epoch time of the last transaction received from this peer that we
1048      * had not yet seen (e.g. not already received from another peer) and that
1049      * was accepted into our mempool. Used as an inbound peer eviction criterium
1050      * in CConnman::AttemptToEvictConnection. */
1051     std::atomic<int64_t> nLastTXTime{0};
1052 
1053     // Ping time measurement:
1054     // The pong reply we're expecting, or 0 if no pong expected.
1055     std::atomic<uint64_t> nPingNonceSent{0};
1056     /** When the last ping was sent, or 0 if no ping was ever sent */
1057     std::atomic<std::chrono::microseconds> m_ping_start{std::chrono::microseconds{0}};
1058     // Last measured round-trip time.
1059     std::atomic<int64_t> nPingUsecTime{0};
1060     // Best measured round-trip time.
1061     std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
1062     // Whether a ping is requested.
1063     std::atomic<bool> fPingQueued{false};
1064 
1065     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, ConnectionType conn_type_in, bool inbound_onion = false);
1066     ~CNode();
1067     CNode(const CNode&) = delete;
1068     CNode& operator=(const CNode&) = delete;
1069 
1070 private:
1071     const NodeId id;
1072     const uint64_t nLocalHostNonce;
1073     const ConnectionType m_conn_type;
1074     std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
1075 
1076     //! Services offered to this peer.
1077     //!
1078     //! This is supplied by the parent CConnman during peer connection
1079     //! (CConnman::ConnectNode()) from its attribute of the same name.
1080     //!
1081     //! This is const because there is no protocol defined for renegotiating
1082     //! services initially offered to a peer. The set of local services we
1083     //! offer should not change after initialization.
1084     //!
1085     //! An interesting example of this is NODE_NETWORK and initial block
1086     //! download: a node which starts up from scratch doesn't have any blocks
1087     //! to serve, but still advertises NODE_NETWORK because it will eventually
1088     //! fulfill this role after IBD completes. P2P code is written in such a
1089     //! way that it can gracefully handle peers who don't make good on their
1090     //! service advertisements.
1091     const ServiceFlags nLocalServices;
1092 
1093     const int nMyStartingHeight;
1094     NetPermissionFlags m_permissionFlags{ PF_NONE };
1095     std::list<CNetMessage> vRecvMsg;  // Used only by SocketHandler thread
1096 
1097     mutable RecursiveMutex cs_addrName;
1098     std::string addrName GUARDED_BY(cs_addrName);
1099 
1100     // Our address, as reported by the peer
1101     CService addrLocal GUARDED_BY(cs_addrLocal);
1102     mutable RecursiveMutex cs_addrLocal;
1103 
1104     //! Whether this peer connected via our Tor onion service.
1105     const bool m_inbound_onion{false};
1106 
1107 public:
1108 
GetId()1109     NodeId GetId() const {
1110         return id;
1111     }
1112 
GetLocalNonce()1113     uint64_t GetLocalNonce() const {
1114         return nLocalHostNonce;
1115     }
1116 
GetMyStartingHeight()1117     int GetMyStartingHeight() const {
1118         return nMyStartingHeight;
1119     }
1120 
GetRefCount()1121     int GetRefCount() const
1122     {
1123         assert(nRefCount >= 0);
1124         return nRefCount;
1125     }
1126 
1127     bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
1128 
SetCommonVersion(int greatest_common_version)1129     void SetCommonVersion(int greatest_common_version)
1130     {
1131         m_greatest_common_version = greatest_common_version;
1132     }
GetCommonVersion()1133     int GetCommonVersion() const
1134     {
1135         return m_greatest_common_version;
1136     }
1137 
1138     CService GetAddrLocal() const;
1139     //! May not be called more than once
1140     void SetAddrLocal(const CService& addrLocalIn);
1141 
AddRef()1142     CNode* AddRef()
1143     {
1144         nRefCount++;
1145         return this;
1146     }
1147 
Release()1148     void Release()
1149     {
1150         nRefCount--;
1151     }
1152 
1153 
1154 
AddAddressKnown(const CAddress & _addr)1155     void AddAddressKnown(const CAddress& _addr)
1156     {
1157         assert(m_addr_known);
1158         m_addr_known->insert(_addr.GetKey());
1159     }
1160 
PushAddress(const CAddress & _addr,FastRandomContext & insecure_rand)1161     void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
1162     {
1163         // Whether the peer supports the address in `_addr`. For example,
1164         // nodes that do not implement BIP155 cannot receive Tor v3 addresses
1165         // because they require ADDRv2 (BIP155) encoding.
1166         const bool addr_format_supported = m_wants_addrv2 || _addr.IsAddrV1Compatible();
1167 
1168         // Known checking here is only to save space from duplicates.
1169         // SendMessages will filter it again for knowns that were added
1170         // after addresses were pushed.
1171         assert(m_addr_known);
1172         if (_addr.IsValid() && !m_addr_known->contains(_addr.GetKey()) && addr_format_supported) {
1173             if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
1174                 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
1175             } else {
1176                 vAddrToSend.push_back(_addr);
1177             }
1178         }
1179     }
1180 
1181 
AddKnownTx(const uint256 & hash)1182     void AddKnownTx(const uint256& hash)
1183     {
1184         if (m_tx_relay != nullptr) {
1185             LOCK(m_tx_relay->cs_tx_inventory);
1186             m_tx_relay->filterInventoryKnown.insert(hash);
1187         }
1188     }
1189 
PushTxInventory(const uint256 & hash)1190     void PushTxInventory(const uint256& hash)
1191     {
1192         if (m_tx_relay == nullptr) return;
1193         LOCK(m_tx_relay->cs_tx_inventory);
1194         if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
1195             m_tx_relay->setInventoryTxToSend.insert(hash);
1196         }
1197     }
1198 
1199     void CloseSocketDisconnect();
1200 
1201     void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
1202 
GetLocalServices()1203     ServiceFlags GetLocalServices() const
1204     {
1205         return nLocalServices;
1206     }
1207 
1208     std::string GetAddrName() const;
1209     //! Sets the addrName only if it was not previously set
1210     void MaybeSetAddrName(const std::string& addrNameIn);
1211 
1212     std::string ConnectionTypeAsString() const;
1213 };
1214 
1215 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
1216 int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
1217 
1218 /** Wrapper to return mockable type */
PoissonNextSend(std::chrono::microseconds now,std::chrono::seconds average_interval)1219 inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
1220 {
1221     return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
1222 }
1223 
1224 #endif // BITCOIN_NET_H
1225