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

Generated by: LCOV version 1.14