LCOV - code coverage report
Current view: top level - src - net.h (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 194 209 92.8 %
Date: 2020-10-06 11:46:21 Functions: 44 45 97.8 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 0 0 -

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

Generated by: LCOV version 1.14