LCOV - code coverage report
Current view: top level - src - net.h (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 204 213 95.8 %
Date: 2020-09-26 01:30:44 Functions: 95 108 88.0 %

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

Generated by: LCOV version 1.15