LCOV - code coverage report
Current view: top level - src - net.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 44 180 24.4 %
Date: 2023-09-26 12:08:55 Functions: 5 67 7.5 %

          Line data    Source code
       1             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2022 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 <bip324.h>
      10             : #include <chainparams.h>
      11             : #include <common/bloom.h>
      12             : #include <compat/compat.h>
      13             : #include <consensus/amount.h>
      14             : #include <crypto/siphash.h>
      15             : #include <hash.h>
      16             : #include <i2p.h>
      17             : #include <kernel/messagestartchars.h>
      18             : #include <net_permissions.h>
      19             : #include <netaddress.h>
      20             : #include <netbase.h>
      21             : #include <netgroup.h>
      22             : #include <node/connection_types.h>
      23             : #include <policy/feerate.h>
      24             : #include <protocol.h>
      25             : #include <random.h>
      26             : #include <span.h>
      27             : #include <streams.h>
      28             : #include <sync.h>
      29             : #include <uint256.h>
      30             : #include <util/check.h>
      31             : #include <util/sock.h>
      32             : #include <util/threadinterrupt.h>
      33             : 
      34             : #include <atomic>
      35             : #include <condition_variable>
      36             : #include <cstdint>
      37             : #include <deque>
      38             : #include <functional>
      39             : #include <list>
      40             : #include <map>
      41             : #include <memory>
      42             : #include <optional>
      43             : #include <queue>
      44             : #include <thread>
      45             : #include <unordered_set>
      46             : #include <vector>
      47             : 
      48             : class AddrMan;
      49             : class BanMan;
      50             : class CChainParams;
      51             : class CNode;
      52             : class CScheduler;
      53             : struct bilingual_str;
      54             : 
      55             : /** Default for -whitelistrelay. */
      56             : static const bool DEFAULT_WHITELISTRELAY = true;
      57             : /** Default for -whitelistforcerelay. */
      58             : static const bool DEFAULT_WHITELISTFORCERELAY = false;
      59             : 
      60             : /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
      61             : static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
      62             : /** Run the feeler connection loop once every 2 minutes. **/
      63             : static constexpr auto FEELER_INTERVAL = 2min;
      64             : /** Run the extra block-relay-only connection loop once every 5 minutes. **/
      65             : static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
      66             : /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
      67             : static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
      68             : /** Maximum length of the user agent string in `version` message */
      69             : static const unsigned int MAX_SUBVERSION_LENGTH = 256;
      70             : /** Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc) */
      71             : static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
      72             : /** Maximum number of addnode outgoing nodes */
      73             : static const int MAX_ADDNODE_CONNECTIONS = 8;
      74             : /** Maximum number of block-relay-only outgoing connections */
      75             : static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
      76             : /** Maximum number of feeler connections */
      77             : static const int MAX_FEELER_CONNECTIONS = 1;
      78             : /** -listen default */
      79             : static const bool DEFAULT_LISTEN = true;
      80             : /** The maximum number of peer connections to maintain. */
      81             : static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
      82             : /** The default for -maxuploadtarget. 0 = Unlimited */
      83             : static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
      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             : /** Number of file descriptors required for message capture **/
      89             : static const int NUM_FDS_MESSAGE_CAPTURE = 1;
      90             : 
      91             : static constexpr bool DEFAULT_FORCEDNSSEED{false};
      92             : static constexpr bool DEFAULT_DNSSEED{true};
      93             : static constexpr bool DEFAULT_FIXEDSEEDS{true};
      94             : static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
      95             : static const size_t DEFAULT_MAXSENDBUFFER    = 1 * 1000;
      96             : 
      97             : typedef int64_t NodeId;
      98             : 
      99           0 : struct AddedNodeInfo
     100             : {
     101             :     std::string strAddedNode;
     102             :     CService resolvedAddress;
     103             :     bool fConnected;
     104             :     bool fInbound;
     105             : };
     106             : 
     107             : class CNodeStats;
     108             : class CClientUIInterface;
     109             : 
     110             : struct CSerializedNetMsg {
     111           0 :     CSerializedNetMsg() = default;
     112           0 :     CSerializedNetMsg(CSerializedNetMsg&&) = default;
     113           0 :     CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
     114             :     // No implicit copying, only moves.
     115             :     CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
     116             :     CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
     117             : 
     118           0 :     CSerializedNetMsg Copy() const
     119             :     {
     120           0 :         CSerializedNetMsg copy;
     121           0 :         copy.data = data;
     122           0 :         copy.m_type = m_type;
     123           0 :         return copy;
     124           0 :     }
     125             : 
     126             :     std::vector<unsigned char> data;
     127             :     std::string m_type;
     128             : 
     129             :     /** Compute total memory usage of this object (own memory + any dynamic memory). */
     130             :     size_t GetMemoryUsage() const noexcept;
     131             : };
     132             : 
     133             : /**
     134             :  * Look up IP addresses from all interfaces on the machine and add them to the
     135             :  * list of local addresses to self-advertise.
     136             :  * The loopback interface is skipped and only the first address from each
     137             :  * interface is used.
     138             :  */
     139             : void Discover();
     140             : 
     141             : uint16_t GetListenPort();
     142             : 
     143             : enum
     144             : {
     145             :     LOCAL_NONE,   // unknown
     146             :     LOCAL_IF,     // address a local interface listens on
     147             :     LOCAL_BIND,   // address explicit bound to
     148             :     LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
     149             :     LOCAL_MANUAL, // address explicitly specified (-externalip=)
     150             : 
     151             :     LOCAL_MAX
     152             : };
     153             : 
     154             : /** Returns a local address that we should advertise to this peer. */
     155             : std::optional<CService> GetLocalAddrForPeer(CNode& node);
     156             : 
     157             : /**
     158             :  * Mark a network as reachable or unreachable (no automatic connects to it)
     159             :  * @note Networks are reachable by default
     160             :  */
     161             : void SetReachable(enum Network net, bool reachable);
     162             : /** @returns true if the network is reachable, false otherwise */
     163             : bool IsReachable(enum Network net);
     164             : /** @returns true if the address is in a reachable network, false otherwise */
     165             : bool IsReachable(const CNetAddr& addr);
     166             : 
     167             : bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
     168             : bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
     169             : void RemoveLocal(const CService& addr);
     170             : bool SeenLocal(const CService& addr);
     171             : bool IsLocal(const CService& addr);
     172             : CService GetLocalAddress(const CNode& peer);
     173             : CService MaybeFlipIPv6toCJDNS(const CService& service);
     174             : 
     175             : 
     176             : extern bool fDiscover;
     177             : extern bool fListen;
     178             : 
     179             : /** Subversion as sent to the P2P network in `version` messages */
     180             : extern std::string strSubVersion;
     181             : 
     182             : struct LocalServiceInfo {
     183             :     int nScore;
     184             :     uint16_t nPort;
     185             : };
     186             : 
     187             : extern GlobalMutex g_maplocalhost_mutex;
     188             : extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
     189             : 
     190             : extern const std::string NET_MESSAGE_TYPE_OTHER;
     191             : using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
     192             : 
     193           0 : class CNodeStats
     194             : {
     195             : public:
     196             :     NodeId nodeid;
     197             :     std::chrono::seconds m_last_send;
     198             :     std::chrono::seconds m_last_recv;
     199             :     std::chrono::seconds m_last_tx_time;
     200             :     std::chrono::seconds m_last_block_time;
     201             :     std::chrono::seconds m_connected;
     202             :     int64_t nTimeOffset;
     203             :     std::string m_addr_name;
     204             :     int nVersion;
     205             :     std::string cleanSubVer;
     206             :     bool fInbound;
     207             :     // We requested high bandwidth connection to peer
     208             :     bool m_bip152_highbandwidth_to;
     209             :     // Peer requested high bandwidth connection
     210             :     bool m_bip152_highbandwidth_from;
     211             :     int m_starting_height;
     212             :     uint64_t nSendBytes;
     213             :     mapMsgTypeSize mapSendBytesPerMsgType;
     214             :     uint64_t nRecvBytes;
     215             :     mapMsgTypeSize mapRecvBytesPerMsgType;
     216             :     NetPermissionFlags m_permission_flags;
     217             :     std::chrono::microseconds m_last_ping_time;
     218             :     std::chrono::microseconds m_min_ping_time;
     219             :     // Our address, as reported by the peer
     220             :     std::string addrLocal;
     221             :     // Address of this peer
     222             :     CAddress addr;
     223             :     // Bind address of our side of the connection
     224             :     CAddress addrBind;
     225             :     // Network the peer connected through
     226             :     Network m_network;
     227             :     uint32_t m_mapped_as;
     228             :     ConnectionType m_conn_type;
     229             : };
     230             : 
     231             : 
     232             : /** Transport protocol agnostic message container.
     233             :  * Ideally it should only contain receive time, payload,
     234             :  * type and size.
     235             :  */
     236             : class CNetMessage {
     237             : public:
     238             :     CDataStream m_recv;                  //!< received message data
     239           0 :     std::chrono::microseconds m_time{0}; //!< time of message receipt
     240           0 :     uint32_t m_message_size{0};          //!< size of the payload
     241           0 :     uint32_t m_raw_message_size{0};      //!< used wire size of the message (including header/checksum)
     242             :     std::string m_type;
     243             : 
     244           0 :     CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
     245             :     // Only one CNetMessage object will exist for the same message on either
     246             :     // the receive or processing queue. For performance reasons we therefore
     247             :     // delete the copy constructor and assignment operator to avoid the
     248             :     // possibility of copying CNetMessage objects.
     249           0 :     CNetMessage(CNetMessage&&) = default;
     250             :     CNetMessage(const CNetMessage&) = delete;
     251             :     CNetMessage& operator=(CNetMessage&&) = default;
     252             :     CNetMessage& operator=(const CNetMessage&) = delete;
     253             : 
     254           0 :     void SetVersion(int nVersionIn)
     255             :     {
     256           0 :         m_recv.SetVersion(nVersionIn);
     257           0 :     }
     258             : };
     259             : 
     260             : /** The Transport converts one connection's sent messages to wire bytes, and received bytes back. */
     261             : class Transport {
     262             : public:
     263           0 :     virtual ~Transport() {}
     264             : 
     265             :     // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
     266             :     // agnostic CNetMessage (message type & payload) objects.
     267             : 
     268             :     /** Returns true if the current message is complete (so GetReceivedMessage can be called). */
     269             :     virtual bool ReceivedMessageComplete() const = 0;
     270             : 
     271             :     /** Feed wire bytes to the transport.
     272             :      *
     273             :      * @return false if some bytes were invalid, in which case the transport can't be used anymore.
     274             :      *
     275             :      * Consumed bytes are chopped off the front of msg_bytes.
     276             :      */
     277             :     virtual bool ReceivedBytes(Span<const uint8_t>& msg_bytes) = 0;
     278             : 
     279             :     /** Retrieve a completed message from transport.
     280             :      *
     281             :      * This can only be called when ReceivedMessageComplete() is true.
     282             :      *
     283             :      * If reject_message=true is returned the message itself is invalid, but (other than false
     284             :      * returned by ReceivedBytes) the transport is not in an inconsistent state.
     285             :      */
     286             :     virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
     287             : 
     288             :     // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
     289             : 
     290             :     /** Set the next message to send.
     291             :      *
     292             :      * If no message can currently be set (perhaps because the previous one is not yet done being
     293             :      * sent), returns false, and msg will be unmodified. Otherwise msg is enqueued (and
     294             :      * possibly moved-from) and true is returned.
     295             :      */
     296             :     virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
     297             : 
     298             :     /** Return type for GetBytesToSend, consisting of:
     299             :      *  - Span<const uint8_t> to_send: span of bytes to be sent over the wire (possibly empty).
     300             :      *  - bool more: whether there will be more bytes to be sent after the ones in to_send are
     301             :      *    all sent (as signaled by MarkBytesSent()).
     302             :      *  - const std::string& m_type: message type on behalf of which this is being sent
     303             :      *    ("" for bytes that are not on behalf of any message).
     304             :      */
     305             :     using BytesToSend = std::tuple<
     306             :         Span<const uint8_t> /*to_send*/,
     307             :         bool /*more*/,
     308             :         const std::string& /*m_type*/
     309             :     >;
     310             : 
     311             :     /** Get bytes to send on the wire, if any, along with other information about it.
     312             :      *
     313             :      * As a const function, it does not modify the transport's observable state, and is thus safe
     314             :      * to be called multiple times.
     315             :      *
     316             :      * @param[in] have_next_message If true, the "more" return value reports whether more will
     317             :      *            be sendable after a SetMessageToSend call. It is set by the caller when they know
     318             :      *            they have another message ready to send, and only care about what happens
     319             :      *            after that. The have_next_message argument only affects this "more" return value
     320             :      *            and nothing else.
     321             :      *
     322             :      *            Effectively, there are three possible outcomes about whether there are more bytes
     323             :      *            to send:
     324             :      *            - Yes:     the transport itself has more bytes to send later. For example, for
     325             :      *                       V1Transport this happens during the sending of the header of a
     326             :      *                       message, when there is a non-empty payload that follows.
     327             :      *            - No:      the transport itself has no more bytes to send, but will have bytes to
     328             :      *                       send if handed a message through SetMessageToSend. In V1Transport this
     329             :      *                       happens when sending the payload of a message.
     330             :      *            - Blocked: the transport itself has no more bytes to send, and is also incapable
     331             :      *                       of sending anything more at all now, if it were handed another
     332             :      *                       message to send. This occurs in V2Transport before the handshake is
     333             :      *                       complete, as the encryption ciphers are not set up for sending
     334             :      *                       messages before that point.
     335             :      *
     336             :      *            The boolean 'more' is true for Yes, false for Blocked, and have_next_message
     337             :      *            controls what is returned for No.
     338             :      *
     339             :      * @return a BytesToSend object. The to_send member returned acts as a stream which is only
     340             :      *         ever appended to. This means that with the exception of MarkBytesSent (which pops
     341             :      *         bytes off the front of later to_sends), operations on the transport can only append
     342             :      *         to what is being returned. Also note that m_type and to_send refer to data that is
     343             :      *         internal to the transport, and calling any non-const function on this object may
     344             :      *         invalidate them.
     345             :      */
     346             :     virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
     347             : 
     348             :     /** Report how many bytes returned by the last GetBytesToSend() have been sent.
     349             :      *
     350             :      * bytes_sent cannot exceed to_send.size() of the last GetBytesToSend() result.
     351             :      *
     352             :      * If bytes_sent=0, this call has no effect.
     353             :      */
     354             :     virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
     355             : 
     356             :     /** Return the memory usage of this transport attributable to buffered data to send. */
     357             :     virtual size_t GetSendMemoryUsage() const noexcept = 0;
     358             : };
     359             : 
     360             : class V1Transport final : public Transport
     361             : {
     362             : private:
     363             :     MessageStartChars m_magic_bytes;
     364             :     const NodeId m_node_id; // Only for logging
     365             :     mutable Mutex m_recv_mutex; //!< Lock for receive state
     366             :     mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
     367             :     mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
     368             :     bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
     369             :     CDataStream hdrbuf GUARDED_BY(m_recv_mutex); // partially received header
     370             :     CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
     371             :     CDataStream vRecv GUARDED_BY(m_recv_mutex); // received message data
     372             :     unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
     373             :     unsigned int nDataPos GUARDED_BY(m_recv_mutex);
     374             : 
     375             :     const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
     376             :     int readHeader(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
     377             :     int readData(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
     378             : 
     379           0 :     void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
     380           0 :         AssertLockHeld(m_recv_mutex);
     381           0 :         vRecv.clear();
     382           0 :         hdrbuf.clear();
     383           0 :         hdrbuf.resize(24);
     384           0 :         in_data = false;
     385           0 :         nHdrPos = 0;
     386           0 :         nDataPos = 0;
     387           0 :         data_hash.SetNull();
     388           0 :         hasher.Reset();
     389           0 :     }
     390             : 
     391           0 :     bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
     392             :     {
     393           0 :         AssertLockHeld(m_recv_mutex);
     394           0 :         if (!in_data) return false;
     395           0 :         return hdr.nMessageSize == nDataPos;
     396           0 :     }
     397             : 
     398             :     /** Lock for sending state. */
     399             :     mutable Mutex m_send_mutex;
     400             :     /** The header of the message currently being sent. */
     401             :     std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
     402             :     /** The data of the message currently being sent. */
     403             :     CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
     404             :     /** Whether we're currently sending header bytes or message bytes. */
     405             :     bool m_sending_header GUARDED_BY(m_send_mutex) {false};
     406             :     /** How many bytes have been sent so far (from m_header_to_send, or from m_message_to_send.data). */
     407             :     size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
     408             : 
     409             : public:
     410             :     V1Transport(const NodeId node_id, int nTypeIn, int nVersionIn) noexcept;
     411             : 
     412           0 :     bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
     413             :     {
     414           0 :         AssertLockNotHeld(m_recv_mutex);
     415           0 :         return WITH_LOCK(m_recv_mutex, return CompleteInternal());
     416             :     }
     417             : 
     418           0 :     bool ReceivedBytes(Span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
     419             :     {
     420           0 :         AssertLockNotHeld(m_recv_mutex);
     421           0 :         LOCK(m_recv_mutex);
     422           0 :         int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
     423           0 :         if (ret < 0) {
     424           0 :             Reset();
     425           0 :         } else {
     426           0 :             msg_bytes = msg_bytes.subspan(ret);
     427             :         }
     428           0 :         return ret >= 0;
     429           0 :     }
     430             : 
     431             :     CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
     432             : 
     433             :     bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     434             :     BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     435             :     void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     436             :     size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     437             : };
     438             : 
     439             : class V2Transport final : public Transport
     440             : {
     441             : private:
     442             :     /** Contents of the version packet to send. BIP324 stipulates that senders should leave this
     443             :      *  empty, and receivers should ignore it. Future extensions can change what is sent as long as
     444             :      *  an empty version packet contents is interpreted as no extensions supported. */
     445             :     static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
     446             : 
     447             :     /** The length of the V1 prefix to match bytes initially received by responders with to
     448             :      *  determine if their peer is speaking V1 or V2. */
     449             :     static constexpr size_t V1_PREFIX_LEN = 12;
     450             : 
     451             :     // The sender side and receiver side of V2Transport are state machines that are transitioned
     452             :     // through, based on what has been received. The receive state corresponds to the contents of,
     453             :     // and bytes received to, the receive buffer. The send state controls what can be appended to
     454             :     // the send buffer and what can be sent from it.
     455             : 
     456             :     /** State type that defines the current contents of the receive buffer and/or how the next
     457             :      *  received bytes added to it will be interpreted.
     458             :      *
     459             :      * Diagram:
     460             :      *
     461             :      *   start(responder)
     462             :      *        |
     463             :      *        |  start(initiator)                                       /---------\
     464             :      *        |          |                                              |         |
     465             :      *        v          v                                              v         |
     466             :      *  KEY_MAYBE_V1 -> KEY -> GARB_GARBTERM -> GARBAUTH -> VERSION -> APP -> APP_READY
     467             :      *        |
     468             :      *        \-------> V1
     469             :      */
     470             :     enum class RecvState : uint8_t {
     471             :         /** (Responder only) either v2 public key or v1 header.
     472             :          *
     473             :          * This is the initial state for responders, before data has been received to distinguish
     474             :          * v1 from v2 connections. When that happens, the state becomes either KEY (for v2) or V1
     475             :          * (for v1). */
     476             :         KEY_MAYBE_V1,
     477             : 
     478             :         /** Public key.
     479             :          *
     480             :          * This is the initial state for initiators, during which the other side's public key is
     481             :          * received. When that information arrives, the ciphers get initialized and the state
     482             :          * becomes GARB_GARBTERM. */
     483             :         KEY,
     484             : 
     485             :         /** Garbage and garbage terminator.
     486             :          *
     487             :          * Whenever a byte is received, the last 16 bytes are compared with the expected garbage
     488             :          * terminator. When that happens, the state becomes GARBAUTH. If no matching terminator is
     489             :          * received in 4111 bytes (4095 for the maximum garbage length, and 16 bytes for the
     490             :          * terminator), the connection aborts. */
     491             :         GARB_GARBTERM,
     492             : 
     493             :         /** Garbage authentication packet.
     494             :          *
     495             :          * A packet is received, and decrypted/verified with AAD set to the garbage received during
     496             :          * the GARB_GARBTERM state. If that succeeds, the state becomes VERSION. If it fails the
     497             :          * connection aborts. */
     498             :         GARBAUTH,
     499             : 
     500             :         /** Version packet.
     501             :          *
     502             :          * A packet is received, and decrypted/verified. If that succeeds, the state becomes APP,
     503             :          * and the decrypted contents is interpreted as version negotiation (currently, that means
     504             :          * ignoring it, but it can be used for negotiating future extensions). If it fails, the
     505             :          * connection aborts. */
     506             :         VERSION,
     507             : 
     508             :         /** Application packet.
     509             :          *
     510             :          * A packet is received, and decrypted/verified. If that succeeds, the state becomes
     511             :          * APP_READY and the decrypted contents is kept in m_recv_decode_buffer until it is
     512             :          * retrieved as a message by GetMessage(). */
     513             :         APP,
     514             : 
     515             :         /** Nothing (an application packet is available for GetMessage()).
     516             :          *
     517             :          * Nothing can be received in this state. When the message is retrieved by GetMessage,
     518             :          * the state becomes APP again. */
     519             :         APP_READY,
     520             : 
     521             :         /** Nothing (this transport is using v1 fallback).
     522             :          *
     523             :          * All receive operations are redirected to m_v1_fallback. */
     524             :         V1,
     525             :     };
     526             : 
     527             :     /** State type that controls the sender side.
     528             :      *
     529             :      * Diagram:
     530             :      *
     531             :      *  start(responder)
     532             :      *      |
     533             :      *      |      start(initiator)
     534             :      *      |            |
     535             :      *      v            v
     536             :      *  MAYBE_V1 -> AWAITING_KEY -> READY
     537             :      *      |
     538             :      *      \-----> V1
     539             :      */
     540             :     enum class SendState : uint8_t {
     541             :         /** (Responder only) Not sending until v1 or v2 is detected.
     542             :          *
     543             :          * This is the initial state for responders. The send buffer is empty.
     544             :          * When the receiver determines whether this
     545             :          * is a V1 or V2 connection, the sender state becomes AWAITING_KEY (for v2) or V1 (for v1).
     546             :          */
     547             :         MAYBE_V1,
     548             : 
     549             :         /** Waiting for the other side's public key.
     550             :          *
     551             :          * This is the initial state for initiators. The public key and garbage is sent out. When
     552             :          * the receiver receives the other side's public key and transitions to GARB_GARBTERM, the
     553             :          * sender state becomes READY. */
     554             :         AWAITING_KEY,
     555             : 
     556             :         /** Normal sending state.
     557             :          *
     558             :          * In this state, the ciphers are initialized, so packets can be sent. When this state is
     559             :          * entered, the garbage terminator, garbage authentication packet, and version
     560             :          * packet are appended to the send buffer (in addition to the key and garbage which may
     561             :          * still be there). In this state a message can be provided if the send buffer is empty. */
     562             :         READY,
     563             : 
     564             :         /** This transport is using v1 fallback.
     565             :          *
     566             :          * All send operations are redirected to m_v1_fallback. */
     567             :         V1,
     568             :     };
     569             : 
     570             :     /** Cipher state. */
     571             :     BIP324Cipher m_cipher;
     572             :     /** Whether we are the initiator side. */
     573             :     const bool m_initiating;
     574             :     /** NodeId (for debug logging). */
     575             :     const NodeId m_nodeid;
     576             :     /** Encapsulate a V1Transport to fall back to. */
     577             :     V1Transport m_v1_fallback;
     578             : 
     579             :     /** Lock for receiver-side fields. */
     580             :     mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
     581             :     /** In {GARBAUTH, VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >=
     582             :      *  BIP324Cipher::LENGTH_LEN. Unspecified otherwise. */
     583             :     uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
     584             :     /** Receive buffer; meaning is determined by m_recv_state. */
     585             :     std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
     586             :     /** During GARBAUTH, the garbage received during GARB_GARBTERM. */
     587             :     std::vector<uint8_t> m_recv_garbage GUARDED_BY(m_recv_mutex);
     588             :     /** Buffer to put decrypted contents in, for converting to CNetMessage. */
     589             :     std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
     590             :     /** Deserialization type. */
     591             :     const int m_recv_type;
     592             :     /** Deserialization version number. */
     593             :     const int m_recv_version;
     594             :     /** Current receiver state. */
     595             :     RecvState m_recv_state GUARDED_BY(m_recv_mutex);
     596             : 
     597             :     /** Lock for sending-side fields. If both sending and receiving fields are accessed,
     598             :      *  m_recv_mutex must be acquired before m_send_mutex. */
     599             :     mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
     600             :     /** The send buffer; meaning is determined by m_send_state. */
     601             :     std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
     602             :     /** How many bytes from the send buffer have been sent so far. */
     603             :     uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
     604             :     /** The garbage sent, or to be sent (MAYBE_V1 and AWAITING_KEY state only). */
     605             :     std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
     606             :     /** Type of the message being sent. */
     607             :     std::string m_send_type GUARDED_BY(m_send_mutex);
     608             :     /** Current sender state. */
     609             :     SendState m_send_state GUARDED_BY(m_send_mutex);
     610             : 
     611             :     /** Change the receive state. */
     612             :     void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
     613             :     /** Change the send state. */
     614             :     void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
     615             :     /** Given a packet's contents, find the message type (if valid), and strip it from contents. */
     616             :     static std::optional<std::string> GetMessageType(Span<const uint8_t>& contents) noexcept;
     617             :     /** Determine how many received bytes can be processed in one go (not allowed in V1 state). */
     618             :     size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
     619             :     /** Put our public key + garbage in the send buffer. */
     620             :     void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
     621             :     /** Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state. */
     622             :     void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
     623             :     /** Process bytes in m_recv_buffer, while in KEY state. */
     624             :     bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
     625             :     /** Process bytes in m_recv_buffer, while in GARB_GARBTERM state. */
     626             :     bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
     627             :     /** Process bytes in m_recv_buffer, while in GARBAUTH/VERSION/APP state. */
     628             :     bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
     629             : 
     630             : public:
     631             :     static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
     632             : 
     633             :     /** Construct a V2 transport with securely generated random keys.
     634             :      *
     635             :      * @param[in] nodeid      the node's NodeId (only for debug log output).
     636             :      * @param[in] initiating  whether we are the initiator side.
     637             :      * @param[in] type_in     the serialization type of returned CNetMessages.
     638             :      * @param[in] version_in  the serialization version of returned CNetMessages.
     639             :      */
     640             :     V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in) noexcept;
     641             : 
     642             :     /** Construct a V2 transport with specified keys and garbage (test use only). */
     643             :     V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in, const CKey& key, Span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
     644             : 
     645             :     // Receive side functions.
     646             :     bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
     647             :     bool ReceivedBytes(Span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
     648             :     CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
     649             : 
     650             :     // Send side functions.
     651             :     bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     652             :     BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     653             :     void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     654             :     size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
     655             : };
     656             : 
     657             : struct CNodeOptions
     658             : {
     659             :     NetPermissionFlags permission_flags = NetPermissionFlags::None;
     660             :     std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
     661             :     bool prefer_evict = false;
     662             :     size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
     663             : };
     664             : 
     665             : /** Information about a peer */
     666             : class CNode
     667             : {
     668             : public:
     669             :     /** Transport serializer/deserializer. The receive side functions are only called under cs_vRecv, while
     670             :      * the sending side functions are only called under cs_vSend. */
     671             :     const std::unique_ptr<Transport> m_transport;
     672             : 
     673             :     const NetPermissionFlags m_permission_flags;
     674             : 
     675             :     /**
     676             :      * Socket used for communication with the node.
     677             :      * May not own a Sock object (after `CloseSocketDisconnect()` or during tests).
     678             :      * `shared_ptr` (instead of `unique_ptr`) is used to avoid premature close of
     679             :      * the underlying file descriptor by one thread while another thread is
     680             :      * poll(2)-ing it for activity.
     681             :      * @see https://github.com/bitcoin/bitcoin/issues/21744 for details.
     682             :      */
     683             :     std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
     684             : 
     685             :     /** Sum of GetMemoryUsage of all vSendMsg entries. */
     686             :     size_t m_send_memusage GUARDED_BY(cs_vSend){0};
     687             :     /** Total number of bytes sent on the wire to this peer. */
     688             :     uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
     689             :     /** Messages still to be fed to m_transport->SetMessageToSend. */
     690             :     std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
     691             :     Mutex cs_vSend;
     692             :     Mutex m_sock_mutex;
     693             :     Mutex cs_vRecv;
     694             : 
     695             :     uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
     696             : 
     697             :     std::atomic<std::chrono::seconds> m_last_send{0s};
     698             :     std::atomic<std::chrono::seconds> m_last_recv{0s};
     699             :     //! Unix epoch time at peer connection
     700             :     const std::chrono::seconds m_connected;
     701             :     std::atomic<int64_t> nTimeOffset{0};
     702             :     // Address of this peer
     703             :     const CAddress addr;
     704             :     // Bind address of our side of the connection
     705             :     const CAddress addrBind;
     706             :     const std::string m_addr_name;
     707             :     //! Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
     708             :     const bool m_inbound_onion;
     709             :     std::atomic<int> nVersion{0};
     710             :     Mutex m_subver_mutex;
     711             :     /**
     712             :      * cleanSubVer is a sanitized string of the user agent byte array we read
     713             :      * from the wire. This cleaned string can safely be logged or displayed.
     714             :      */
     715             :     std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
     716             :     const bool m_prefer_evict{false}; // This peer is preferred for eviction.
     717           0 :     bool HasPermission(NetPermissionFlags permission) const {
     718           0 :         return NetPermissions::HasFlag(m_permission_flags, permission);
     719             :     }
     720             :     /** fSuccessfullyConnected is set to true on receiving VERACK from the peer. */
     721             :     std::atomic_bool fSuccessfullyConnected{false};
     722             :     // Setting fDisconnect to true will cause the node to be disconnected the
     723             :     // next time DisconnectNodes() runs
     724             :     std::atomic_bool fDisconnect{false};
     725             :     CSemaphoreGrant grantOutbound;
     726             :     std::atomic<int> nRefCount{0};
     727             : 
     728             :     const uint64_t nKeyedNetGroup;
     729             :     std::atomic_bool fPauseRecv{false};
     730             :     std::atomic_bool fPauseSend{false};
     731             : 
     732             :     const ConnectionType m_conn_type;
     733             : 
     734             :     /** Move all messages from the received queue to the processing queue. */
     735             :     void MarkReceivedMsgsForProcessing()
     736             :         EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
     737             : 
     738             :     /** Poll the next message from the processing queue of this connection.
     739             :      *
     740             :      * Returns std::nullopt if the processing queue is empty, or a pair
     741             :      * consisting of the message and a bool that indicates if the processing
     742             :      * queue has more entries. */
     743             :     std::optional<std::pair<CNetMessage, bool>> PollMessage()
     744             :         EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
     745             : 
     746             :     /** Account for the total size of a sent message in the per msg type connection stats. */
     747           0 :     void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
     748             :         EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
     749             :     {
     750           0 :         mapSendBytesPerMsgType[msg_type] += sent_bytes;
     751           0 :     }
     752             : 
     753           0 :     bool IsOutboundOrBlockRelayConn() const {
     754           0 :         switch (m_conn_type) {
     755             :             case ConnectionType::OUTBOUND_FULL_RELAY:
     756             :             case ConnectionType::BLOCK_RELAY:
     757           0 :                 return true;
     758             :             case ConnectionType::INBOUND:
     759             :             case ConnectionType::MANUAL:
     760             :             case ConnectionType::ADDR_FETCH:
     761             :             case ConnectionType::FEELER:
     762           0 :                 return false;
     763             :         } // no default case, so the compiler can warn about missing cases
     764             : 
     765           0 :         assert(false);
     766           0 :     }
     767             : 
     768           0 :     bool IsFullOutboundConn() const {
     769           0 :         return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
     770             :     }
     771             : 
     772           0 :     bool IsManualConn() const {
     773           0 :         return m_conn_type == ConnectionType::MANUAL;
     774             :     }
     775             : 
     776           0 :     bool IsManualOrFullOutboundConn() const
     777             :     {
     778           0 :         switch (m_conn_type) {
     779             :         case ConnectionType::INBOUND:
     780             :         case ConnectionType::FEELER:
     781             :         case ConnectionType::BLOCK_RELAY:
     782             :         case ConnectionType::ADDR_FETCH:
     783           0 :                 return false;
     784             :         case ConnectionType::OUTBOUND_FULL_RELAY:
     785             :         case ConnectionType::MANUAL:
     786           0 :                 return true;
     787             :         } // no default case, so the compiler can warn about missing cases
     788             : 
     789           0 :         assert(false);
     790           0 :     }
     791             : 
     792           0 :     bool IsBlockOnlyConn() const {
     793           0 :         return m_conn_type == ConnectionType::BLOCK_RELAY;
     794             :     }
     795             : 
     796           0 :     bool IsFeelerConn() const {
     797           0 :         return m_conn_type == ConnectionType::FEELER;
     798             :     }
     799             : 
     800           0 :     bool IsAddrFetchConn() const {
     801           0 :         return m_conn_type == ConnectionType::ADDR_FETCH;
     802             :     }
     803             : 
     804           0 :     bool IsInboundConn() const {
     805           0 :         return m_conn_type == ConnectionType::INBOUND;
     806             :     }
     807             : 
     808           0 :     bool ExpectServicesFromConn() const {
     809           0 :         switch (m_conn_type) {
     810             :             case ConnectionType::INBOUND:
     811             :             case ConnectionType::MANUAL:
     812             :             case ConnectionType::FEELER:
     813           0 :                 return false;
     814             :             case ConnectionType::OUTBOUND_FULL_RELAY:
     815             :             case ConnectionType::BLOCK_RELAY:
     816             :             case ConnectionType::ADDR_FETCH:
     817           0 :                 return true;
     818             :         } // no default case, so the compiler can warn about missing cases
     819             : 
     820           0 :         assert(false);
     821           0 :     }
     822             : 
     823             :     /**
     824             :      * Get network the peer connected through.
     825             :      *
     826             :      * Returns Network::NET_ONION for *inbound* onion connections,
     827             :      * and CNetAddr::GetNetClass() otherwise. The latter cannot be used directly
     828             :      * because it doesn't detect the former, and it's not the responsibility of
     829             :      * the CNetAddr class to know the actual network a peer is connected through.
     830             :      *
     831             :      * @return network the peer connected through.
     832             :      */
     833             :     Network ConnectedThroughNetwork() const;
     834             : 
     835             :     /** Whether this peer connected through a privacy network. */
     836             :     [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
     837             : 
     838             :     // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
     839             :     std::atomic<bool> m_bip152_highbandwidth_to{false};
     840             :     // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
     841             :     std::atomic<bool> m_bip152_highbandwidth_from{false};
     842             : 
     843             :     /** Whether this peer provides all services that we want. Used for eviction decisions */
     844             :     std::atomic_bool m_has_all_wanted_services{false};
     845             : 
     846             :     /** Whether we should relay transactions to this peer. This only changes
     847             :      * from false to true. It will never change back to false. */
     848             :     std::atomic_bool m_relays_txs{false};
     849             : 
     850             :     /** Whether this peer has loaded a bloom filter. Used only in inbound
     851             :      *  eviction logic. */
     852             :     std::atomic_bool m_bloom_filter_loaded{false};
     853             : 
     854             :     /** UNIX epoch time of the last block received from this peer that we had
     855             :      * not yet seen (e.g. not already received from another peer), that passed
     856             :      * preliminary validity checks and was saved to disk, even if we don't
     857             :      * connect the block or it eventually fails connection. Used as an inbound
     858             :      * peer eviction criterium in CConnman::AttemptToEvictConnection. */
     859             :     std::atomic<std::chrono::seconds> m_last_block_time{0s};
     860             : 
     861             :     /** UNIX epoch time of the last transaction received from this peer that we
     862             :      * had not yet seen (e.g. not already received from another peer) and that
     863             :      * was accepted into our mempool. Used as an inbound peer eviction criterium
     864             :      * in CConnman::AttemptToEvictConnection. */
     865             :     std::atomic<std::chrono::seconds> m_last_tx_time{0s};
     866             : 
     867             :     /** Last measured round-trip time. Used only for RPC/GUI stats/debugging.*/
     868             :     std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
     869             : 
     870             :     /** Lowest measured round-trip time. Used as an inbound peer eviction
     871             :      * criterium in CConnman::AttemptToEvictConnection. */
     872             :     std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
     873             : 
     874             :     CNode(NodeId id,
     875             :           std::shared_ptr<Sock> sock,
     876             :           const CAddress& addrIn,
     877             :           uint64_t nKeyedNetGroupIn,
     878             :           uint64_t nLocalHostNonceIn,
     879             :           const CAddress& addrBindIn,
     880             :           const std::string& addrNameIn,
     881             :           ConnectionType conn_type_in,
     882             :           bool inbound_onion,
     883             :           CNodeOptions&& node_opts = {});
     884             :     CNode(const CNode&) = delete;
     885             :     CNode& operator=(const CNode&) = delete;
     886             : 
     887           0 :     NodeId GetId() const {
     888           0 :         return id;
     889             :     }
     890             : 
     891           0 :     uint64_t GetLocalNonce() const {
     892           0 :         return nLocalHostNonce;
     893             :     }
     894             : 
     895           0 :     int GetRefCount() const
     896             :     {
     897           0 :         assert(nRefCount >= 0);
     898           0 :         return nRefCount;
     899             :     }
     900             : 
     901             :     /**
     902             :      * Receive bytes from the buffer and deserialize them into messages.
     903             :      *
     904             :      * @param[in]   msg_bytes   The raw data
     905             :      * @param[out]  complete    Set True if at least one message has been
     906             :      *                          deserialized and is ready to be processed
     907             :      * @return  True if the peer should stay connected,
     908             :      *          False if the peer should be disconnected from.
     909             :      */
     910             :     bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
     911             : 
     912           0 :     void SetCommonVersion(int greatest_common_version)
     913             :     {
     914           0 :         Assume(m_greatest_common_version == INIT_PROTO_VERSION);
     915           0 :         m_greatest_common_version = greatest_common_version;
     916           0 :     }
     917           0 :     int GetCommonVersion() const
     918             :     {
     919           0 :         return m_greatest_common_version;
     920             :     }
     921             : 
     922             :     CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
     923             :     //! May not be called more than once
     924             :     void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
     925             : 
     926           0 :     CNode* AddRef()
     927             :     {
     928           0 :         nRefCount++;
     929           0 :         return this;
     930             :     }
     931             : 
     932           0 :     void Release()
     933             :     {
     934           0 :         nRefCount--;
     935           0 :     }
     936             : 
     937             :     void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
     938             : 
     939             :     void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
     940             : 
     941           0 :     std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
     942             : 
     943             :     /** A ping-pong round trip has completed successfully. Update latest and minimum ping times. */
     944           0 :     void PongReceived(std::chrono::microseconds ping_time) {
     945           0 :         m_last_ping_time = ping_time;
     946           0 :         m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
     947           0 :     }
     948             : 
     949             : private:
     950             :     const NodeId id;
     951             :     const uint64_t nLocalHostNonce;
     952             :     std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
     953             : 
     954             :     const size_t m_recv_flood_size;
     955             :     std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
     956             : 
     957             :     Mutex m_msg_process_queue_mutex;
     958             :     std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
     959             :     size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
     960             : 
     961             :     // Our address, as reported by the peer
     962             :     CService addrLocal GUARDED_BY(m_addr_local_mutex);
     963             :     mutable Mutex m_addr_local_mutex;
     964             : 
     965             :     mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
     966             :     mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
     967             : 
     968             :     /**
     969             :      * If an I2P session is created per connection (for outbound transient I2P
     970             :      * connections) then it is stored here so that it can be destroyed when the
     971             :      * socket is closed. I2P sessions involve a data/transport socket (in `m_sock`)
     972             :      * and a control socket (in `m_i2p_sam_session`). For transient sessions, once
     973             :      * the data socket is closed, the control socket is not going to be used anymore
     974             :      * and is just taking up resources. So better close it as soon as `m_sock` is
     975             :      * closed.
     976             :      * Otherwise this unique_ptr is empty.
     977             :      */
     978             :     std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
     979             : };
     980             : 
     981             : /**
     982             :  * Interface for message handling
     983             :  */
     984             : class NetEventsInterface
     985             : {
     986             : public:
     987             :     /** Mutex for anything that is only accessed via the msg processing thread */
     988             :     static Mutex g_msgproc_mutex;
     989             : 
     990             :     /** Initialize a peer (setup state, queue any initial messages) */
     991             :     virtual void InitializeNode(CNode& node, ServiceFlags our_services) = 0;
     992             : 
     993             :     /** Handle removal of a peer (clear state) */
     994             :     virtual void FinalizeNode(const CNode& node) = 0;
     995             : 
     996             :     /**
     997             :     * Process protocol messages received from a given node
     998             :     *
     999             :     * @param[in]   pnode           The node which we have received messages from.
    1000             :     * @param[in]   interrupt       Interrupt condition for processing threads
    1001             :     * @return                      True if there is more work to be done
    1002             :     */
    1003             :     virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
    1004             : 
    1005             :     /**
    1006             :     * Send queued protocol messages to a given node.
    1007             :     *
    1008             :     * @param[in]   pnode           The node which we are sending messages to.
    1009             :     * @return                      True if there is more work to be done
    1010             :     */
    1011             :     virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
    1012             : 
    1013             : 
    1014             : protected:
    1015             :     /**
    1016             :      * Protected destructor so that instances can only be deleted by derived classes.
    1017             :      * If that restriction is no longer desired, this should be made public and virtual.
    1018             :      */
    1019             :     ~NetEventsInterface() = default;
    1020             : };
    1021             : 
    1022             : class CConnman
    1023             : {
    1024             : public:
    1025             : 
    1026           4 :     struct Options
    1027             :     {
    1028           2 :         ServiceFlags nLocalServices = NODE_NONE;
    1029           2 :         int nMaxConnections = 0;
    1030           2 :         int m_max_outbound_full_relay = 0;
    1031           2 :         int m_max_outbound_block_relay = 0;
    1032           2 :         int nMaxAddnode = 0;
    1033           2 :         int nMaxFeeler = 0;
    1034           2 :         CClientUIInterface* uiInterface = nullptr;
    1035           2 :         NetEventsInterface* m_msgproc = nullptr;
    1036           2 :         BanMan* m_banman = nullptr;
    1037           2 :         unsigned int nSendBufferMaxSize = 0;
    1038           2 :         unsigned int nReceiveFloodSize = 0;
    1039           2 :         uint64_t nMaxOutboundLimit = 0;
    1040           2 :         int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
    1041             :         std::vector<std::string> vSeedNodes;
    1042             :         std::vector<NetWhitelistPermissions> vWhitelistedRange;
    1043             :         std::vector<NetWhitebindPermissions> vWhiteBinds;
    1044             :         std::vector<CService> vBinds;
    1045             :         std::vector<CService> onion_binds;
    1046             :         /// True if the user did not specify -bind= or -whitebind= and thus
    1047             :         /// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
    1048             :         bool bind_on_any;
    1049           2 :         bool m_use_addrman_outgoing = true;
    1050             :         std::vector<std::string> m_specified_outgoing;
    1051             :         std::vector<std::string> m_added_nodes;
    1052             :         bool m_i2p_accept_incoming;
    1053             :     };
    1054             : 
    1055           2 :     void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
    1056             :     {
    1057           2 :         AssertLockNotHeld(m_total_bytes_sent_mutex);
    1058             : 
    1059           2 :         nLocalServices = connOptions.nLocalServices;
    1060           2 :         nMaxConnections = connOptions.nMaxConnections;
    1061           2 :         m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
    1062           2 :         m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
    1063           2 :         m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
    1064           2 :         nMaxAddnode = connOptions.nMaxAddnode;
    1065           2 :         nMaxFeeler = connOptions.nMaxFeeler;
    1066           2 :         m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
    1067           2 :         m_client_interface = connOptions.uiInterface;
    1068           2 :         m_banman = connOptions.m_banman;
    1069           2 :         m_msgproc = connOptions.m_msgproc;
    1070           2 :         nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
    1071           2 :         nReceiveFloodSize = connOptions.nReceiveFloodSize;
    1072           2 :         m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
    1073             :         {
    1074           2 :             LOCK(m_total_bytes_sent_mutex);
    1075           2 :             nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
    1076           2 :         }
    1077           2 :         vWhitelistedRange = connOptions.vWhitelistedRange;
    1078             :         {
    1079           2 :             LOCK(m_added_nodes_mutex);
    1080           2 :             m_added_nodes = connOptions.m_added_nodes;
    1081           2 :         }
    1082           2 :         m_onion_binds = connOptions.onion_binds;
    1083           2 :     }
    1084             : 
    1085             :     CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
    1086             :              const CChainParams& params, bool network_active = true);
    1087             : 
    1088             :     ~CConnman();
    1089             : 
    1090             :     bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
    1091             : 
    1092             :     void StopThreads();
    1093             :     void StopNodes();
    1094           1 :     void Stop()
    1095             :     {
    1096           1 :         StopThreads();
    1097           1 :         StopNodes();
    1098           1 :     };
    1099             : 
    1100             :     void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
    1101           0 :     bool GetNetworkActive() const { return fNetworkActive; };
    1102           0 :     bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
    1103             :     void SetNetworkActive(bool active);
    1104             :     void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
    1105             :     bool CheckIncomingNonce(uint64_t nonce);
    1106             : 
    1107             :     // alias for thread safety annotations only, not defined
    1108             :     RecursiveMutex& GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex);
    1109             : 
    1110             :     bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
    1111             : 
    1112             :     void PushMessage(CNode* pnode, CSerializedNetMsg&& msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
    1113             : 
    1114             :     using NodeFn = std::function<void(CNode*)>;
    1115           0 :     void ForEachNode(const NodeFn& func)
    1116             :     {
    1117           0 :         LOCK(m_nodes_mutex);
    1118           0 :         for (auto&& node : m_nodes) {
    1119           0 :             if (NodeFullyConnected(node))
    1120           0 :                 func(node);
    1121             :         }
    1122           0 :     };
    1123             : 
    1124             :     void ForEachNode(const NodeFn& func) const
    1125             :     {
    1126             :         LOCK(m_nodes_mutex);
    1127             :         for (auto&& node : m_nodes) {
    1128             :             if (NodeFullyConnected(node))
    1129             :                 func(node);
    1130             :         }
    1131             :     };
    1132             : 
    1133             :     // Addrman functions
    1134             :     /**
    1135             :      * Return all or many randomly selected addresses, optionally by network.
    1136             :      *
    1137             :      * @param[in] max_addresses  Maximum number of addresses to return (0 = all).
    1138             :      * @param[in] max_pct        Maximum percentage of addresses to return (0 = all).
    1139             :      * @param[in] network        Select only addresses of this network (nullopt = all).
    1140             :      */
    1141             :     std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
    1142             :     /**
    1143             :      * Cache is used to minimize topology leaks, so it should
    1144             :      * be used for all non-trusted calls, for example, p2p.
    1145             :      * A non-malicious call (from RPC or a peer with addr permission) should
    1146             :      * call the function without a parameter to avoid using the cache.
    1147             :      */
    1148             :     std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
    1149             : 
    1150             :     // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
    1151             :     // a peer that is better than all our current peers.
    1152             :     void SetTryNewOutboundPeer(bool flag);
    1153             :     bool GetTryNewOutboundPeer() const;
    1154             : 
    1155             :     void StartExtraBlockRelayPeers();
    1156             : 
    1157             :     // Return the number of outbound peers we have in excess of our target (eg,
    1158             :     // if we previously called SetTryNewOutboundPeer(true), and have since set
    1159             :     // to false, we may have extra peers that we wish to disconnect). This may
    1160             :     // return a value less than (num_outbound_connections - num_outbound_slots)
    1161             :     // in cases where some outbound connections are not yet fully connected, or
    1162             :     // not yet fully disconnected.
    1163             :     int GetExtraFullOutboundCount() const;
    1164             :     // Count the number of block-relay-only peers we have over our limit.
    1165             :     int GetExtraBlockRelayCount() const;
    1166             : 
    1167             :     bool AddNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
    1168             :     bool RemoveAddedNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
    1169             :     std::vector<AddedNodeInfo> GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
    1170             : 
    1171             :     /**
    1172             :      * Attempts to open a connection. Currently only used from tests.
    1173             :      *
    1174             :      * @param[in]   address     Address of node to try connecting to
    1175             :      * @param[in]   conn_type   ConnectionType::OUTBOUND, ConnectionType::BLOCK_RELAY,
    1176             :      *                          ConnectionType::ADDR_FETCH or ConnectionType::FEELER
    1177             :      * @return      bool        Returns false if there are no available
    1178             :      *                          slots for this connection:
    1179             :      *                          - conn_type not a supported ConnectionType
    1180             :      *                          - Max total outbound connection capacity filled
    1181             :      *                          - Max connection capacity for type is filled
    1182             :      */
    1183             :     bool AddConnection(const std::string& address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
    1184             : 
    1185             :     size_t GetNodeCount(ConnectionDirection) const;
    1186             :     uint32_t GetMappedAS(const CNetAddr& addr) const;
    1187             :     void GetNodeStats(std::vector<CNodeStats>& vstats) const;
    1188             :     bool DisconnectNode(const std::string& node);
    1189             :     bool DisconnectNode(const CSubNet& subnet);
    1190             :     bool DisconnectNode(const CNetAddr& addr);
    1191             :     bool DisconnectNode(NodeId id);
    1192             : 
    1193             :     //! Used to convey which local services we are offering peers during node
    1194             :     //! connection.
    1195             :     //!
    1196             :     //! The data returned by this is used in CNode construction,
    1197             :     //! which is used to advertise which services we are offering
    1198             :     //! that peer during `net_processing.cpp:PushNodeVersion()`.
    1199             :     ServiceFlags GetLocalServices() const;
    1200             : 
    1201             :     uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
    1202             :     std::chrono::seconds GetMaxOutboundTimeframe() const;
    1203             : 
    1204             :     //! check if the outbound target is reached
    1205             :     //! if param historicalBlockServingLimit is set true, the function will
    1206             :     //! response true if the limit for serving historical blocks has been reached
    1207             :     bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
    1208             : 
    1209             :     //! response the bytes left in the current max outbound cycle
    1210             :     //! in case of no limit, it will always response 0
    1211             :     uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
    1212             : 
    1213             :     std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
    1214             : 
    1215             :     uint64_t GetTotalBytesRecv() const;
    1216             :     uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
    1217             : 
    1218             :     /** Get a unique deterministic randomizer. */
    1219             :     CSipHasher GetDeterministicRandomizer(uint64_t id) const;
    1220             : 
    1221             :     void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
    1222             : 
    1223             :     /** Return true if we should disconnect the peer for failing an inactivity check. */
    1224             :     bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
    1225             : 
    1226             :     bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
    1227             : 
    1228             : private:
    1229             :     struct ListenSocket {
    1230             :     public:
    1231             :         std::shared_ptr<Sock> sock;
    1232           0 :         inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
    1233           0 :         ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
    1234           0 :             : sock{sock_}, m_permissions{permissions_}
    1235             :         {
    1236           0 :         }
    1237             : 
    1238             :     private:
    1239             :         NetPermissionFlags m_permissions;
    1240             :     };
    1241             : 
    1242             :     //! returns the time left in the current max outbound cycle
    1243             :     //! in case of no limit, it will always return 0
    1244             :     std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);
    1245             : 
    1246             :     bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
    1247             :     bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
    1248             :     bool InitBinds(const Options& options);
    1249             : 
    1250             :     void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_unused_i2p_sessions_mutex);
    1251             :     void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
    1252             :     void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_unused_i2p_sessions_mutex);
    1253             :     void ThreadOpenConnections(std::vector<std::string> connect) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_added_nodes_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex);
    1254             :     void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
    1255             :     void ThreadI2PAcceptIncoming();
    1256             :     void AcceptConnection(const ListenSocket& hListenSocket);
    1257             : 
    1258             :     /**
    1259             :      * Create a `CNode` object from a socket that has just been accepted and add the node to
    1260             :      * the `m_nodes` member.
    1261             :      * @param[in] sock Connected socket to communicate with the peer.
    1262             :      * @param[in] permission_flags The peer's permissions.
    1263             :      * @param[in] addr_bind The address and port at our side of the connection.
    1264             :      * @param[in] addr The address and port at the peer's side of the connection.
    1265             :      */
    1266             :     void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
    1267             :                                       NetPermissionFlags permission_flags,
    1268             :                                       const CAddress& addr_bind,
    1269             :                                       const CAddress& addr);
    1270             : 
    1271             :     void DisconnectNodes();
    1272             :     void NotifyNumConnectionsChanged();
    1273             :     /** Return true if the peer is inactive and should be disconnected. */
    1274             :     bool InactivityCheck(const CNode& node) const;
    1275             : 
    1276             :     /**
    1277             :      * Generate a collection of sockets to check for IO readiness.
    1278             :      * @param[in] nodes Select from these nodes' sockets.
    1279             :      * @return sockets to check for readiness
    1280             :      */
    1281             :     Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
    1282             : 
    1283             :     /**
    1284             :      * Check connected and listening sockets for IO readiness and process them accordingly.
    1285             :      */
    1286             :     void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
    1287             : 
    1288             :     /**
    1289             :      * Do the read/write for connected sockets that are ready for IO.
    1290             :      * @param[in] nodes Nodes to process. The socket of each node is checked against `what`.
    1291             :      * @param[in] events_per_sock Sockets that are ready for IO.
    1292             :      */
    1293             :     void SocketHandlerConnected(const std::vector<CNode*>& nodes,
    1294             :                                 const Sock::EventsPerSock& events_per_sock)
    1295             :         EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
    1296             : 
    1297             :     /**
    1298             :      * Accept incoming connections, one from each read-ready listening socket.
    1299             :      * @param[in] events_per_sock Sockets that are ready for IO.
    1300             :      */
    1301             :     void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
    1302             : 
    1303             :     void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
    1304             :     void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);
    1305             : 
    1306             :     uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
    1307             : 
    1308             :     CNode* FindNode(const CNetAddr& ip);
    1309             :     CNode* FindNode(const CSubNet& subNet);
    1310             :     CNode* FindNode(const std::string& addrName);
    1311             :     CNode* FindNode(const CService& addr);
    1312             : 
    1313             :     /**
    1314             :      * Determine whether we're already connected to a given address, in order to
    1315             :      * avoid initiating duplicate connections.
    1316             :      */
    1317             :     bool AlreadyConnectedToAddress(const CAddress& addr);
    1318             : 
    1319             :     bool AttemptToEvictConnection();
    1320             :     CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
    1321             :     void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
    1322             : 
    1323             :     void DeleteNode(CNode* pnode);
    1324             : 
    1325             :     NodeId GetNewNodeId();
    1326             : 
    1327             :     /** (Try to) send data from node's vSendMsg. Returns (bytes_sent, data_left). */
    1328             :     std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
    1329             : 
    1330             :     void DumpAddresses();
    1331             : 
    1332             :     // Network stats
    1333             :     void RecordBytesRecv(uint64_t bytes);
    1334             :     void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
    1335             : 
    1336             :     /**
    1337             :      Return reachable networks for which we have no addresses in addrman and therefore
    1338             :      may require loading fixed seeds.
    1339             :      */
    1340             :     std::unordered_set<Network> GetReachableEmptyNetworks() const;
    1341             : 
    1342             :     /**
    1343             :      * Return vector of current BLOCK_RELAY peers.
    1344             :      */
    1345             :     std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
    1346             : 
    1347             :     /**
    1348             :      * Search for a "preferred" network, a reachable network to which we
    1349             :      * currently don't have any OUTBOUND_FULL_RELAY or MANUAL connections.
    1350             :      * There needs to be at least one address in AddrMan for a preferred
    1351             :      * network to be picked.
    1352             :      *
    1353             :      * @param[out]    network        Preferred network, if found.
    1354             :      *
    1355             :      * @return           bool        Whether a preferred network was found.
    1356             :      */
    1357             :     bool MaybePickPreferredNetwork(std::optional<Network>& network);
    1358             : 
    1359             :     // Whether the node should be passed out in ForEach* callbacks
    1360             :     static bool NodeFullyConnected(const CNode* pnode);
    1361             : 
    1362             :     uint16_t GetDefaultPort(Network net) const;
    1363             :     uint16_t GetDefaultPort(const std::string& addr) const;
    1364             : 
    1365             :     // Network usage totals
    1366             :     mutable Mutex m_total_bytes_sent_mutex;
    1367             :     std::atomic<uint64_t> nTotalBytesRecv{0};
    1368             :     uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
    1369             : 
    1370             :     // outbound limit & stats
    1371             :     uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
    1372             :     std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
    1373             :     uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);
    1374             : 
    1375             :     // P2P timeout in seconds
    1376             :     std::chrono::seconds m_peer_connect_timeout;
    1377             : 
    1378             :     // Whitelisted ranges. Any node connecting from these is automatically
    1379             :     // whitelisted (as well as those connecting to whitelisted binds).
    1380             :     std::vector<NetWhitelistPermissions> vWhitelistedRange;
    1381             : 
    1382             :     unsigned int nSendBufferMaxSize{0};
    1383             :     unsigned int nReceiveFloodSize{0};
    1384             : 
    1385             :     std::vector<ListenSocket> vhListenSocket;
    1386             :     std::atomic<bool> fNetworkActive{true};
    1387             :     bool fAddressesInitialized{false};
    1388             :     AddrMan& addrman;
    1389             :     const NetGroupManager& m_netgroupman;
    1390             :     std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
    1391             :     Mutex m_addr_fetches_mutex;
    1392             :     std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
    1393             :     mutable Mutex m_added_nodes_mutex;
    1394             :     std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
    1395             :     std::list<CNode*> m_nodes_disconnected;
    1396             :     mutable RecursiveMutex m_nodes_mutex;
    1397             :     std::atomic<NodeId> nLastNodeId{0};
    1398             :     unsigned int nPrevNodeCount{0};
    1399             : 
    1400             :     // Stores number of full-tx connections (outbound and manual) per network
    1401             :     std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
    1402             : 
    1403             :     /**
    1404             :      * Cache responses to addr requests to minimize privacy leak.
    1405             :      * Attack example: scraping addrs in real-time may allow an attacker
    1406             :      * to infer new connections of the victim by detecting new records
    1407             :      * with fresh timestamps (per self-announcement).
    1408             :      */
    1409             :     struct CachedAddrResponse {
    1410             :         std::vector<CAddress> m_addrs_response_cache;
    1411             :         std::chrono::microseconds m_cache_entry_expiration{0};
    1412             :     };
    1413             : 
    1414             :     /**
    1415             :      * Addr responses stored in different caches
    1416             :      * per (network, local socket) prevent cross-network node identification.
    1417             :      * If a node for example is multi-homed under Tor and IPv6,
    1418             :      * a single cache (or no cache at all) would let an attacker
    1419             :      * to easily detect that it is the same node by comparing responses.
    1420             :      * Indexing by local socket prevents leakage when a node has multiple
    1421             :      * listening addresses on the same network.
    1422             :      *
    1423             :      * The used memory equals to 1000 CAddress records (or around 40 bytes) per
    1424             :      * distinct Network (up to 5) we have/had an inbound peer from,
    1425             :      * resulting in at most ~196 KB. Every separate local socket may
    1426             :      * add up to ~196 KB extra.
    1427             :      */
    1428             :     std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
    1429             : 
    1430             :     /**
    1431             :      * Services this node offers.
    1432             :      *
    1433             :      * This data is replicated in each Peer instance we create.
    1434             :      *
    1435             :      * This data is not marked const, but after being set it should not
    1436             :      * change.
    1437             :      *
    1438             :      * \sa Peer::our_services
    1439             :      */
    1440             :     ServiceFlags nLocalServices;
    1441             : 
    1442             :     std::unique_ptr<CSemaphore> semOutbound;
    1443             :     std::unique_ptr<CSemaphore> semAddnode;
    1444             :     int nMaxConnections;
    1445             : 
    1446             :     // How many full-relay (tx, block, addr) outbound peers we want
    1447             :     int m_max_outbound_full_relay;
    1448             : 
    1449             :     // How many block-relay only outbound peers we want
    1450             :     // We do not relay tx or addr messages with these peers
    1451             :     int m_max_outbound_block_relay;
    1452             : 
    1453             :     int nMaxAddnode;
    1454             :     int nMaxFeeler;
    1455             :     int m_max_outbound;
    1456             :     bool m_use_addrman_outgoing;
    1457             :     CClientUIInterface* m_client_interface;
    1458             :     NetEventsInterface* m_msgproc;
    1459             :     /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
    1460             :     BanMan* m_banman;
    1461             : 
    1462             :     /**
    1463             :      * Addresses that were saved during the previous clean shutdown. We'll
    1464             :      * attempt to make block-relay-only connections to them.
    1465             :      */
    1466             :     std::vector<CAddress> m_anchors;
    1467             : 
    1468             :     /** SipHasher seeds for deterministic randomness */
    1469             :     const uint64_t nSeed0, nSeed1;
    1470             : 
    1471             :     /** flag for waking the message processor. */
    1472             :     bool fMsgProcWake GUARDED_BY(mutexMsgProc);
    1473             : 
    1474             :     std::condition_variable condMsgProc;
    1475             :     Mutex mutexMsgProc;
    1476             :     std::atomic<bool> flagInterruptMsgProc{false};
    1477             : 
    1478             :     /**
    1479             :      * This is signaled when network activity should cease.
    1480             :      * A pointer to it is saved in `m_i2p_sam_session`, so make sure that
    1481             :      * the lifetime of `interruptNet` is not shorter than
    1482             :      * the lifetime of `m_i2p_sam_session`.
    1483             :      */
    1484             :     CThreadInterrupt interruptNet;
    1485             : 
    1486             :     /**
    1487             :      * I2P SAM session.
    1488             :      * Used to accept incoming and make outgoing I2P connections from a persistent
    1489             :      * address.
    1490             :      */
    1491             :     std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
    1492             : 
    1493             :     std::thread threadDNSAddressSeed;
    1494             :     std::thread threadSocketHandler;
    1495             :     std::thread threadOpenAddedConnections;
    1496             :     std::thread threadOpenConnections;
    1497             :     std::thread threadMessageHandler;
    1498             :     std::thread threadI2PAcceptIncoming;
    1499             : 
    1500             :     /** flag for deciding to connect to an extra outbound peer,
    1501             :      *  in excess of m_max_outbound_full_relay
    1502             :      *  This takes the place of a feeler connection */
    1503             :     std::atomic_bool m_try_another_outbound_peer;
    1504             : 
    1505             :     /** flag for initiating extra block-relay-only peer connections.
    1506             :      *  this should only be enabled after initial chain sync has occurred,
    1507             :      *  as these connections are intended to be short-lived and low-bandwidth.
    1508             :      */
    1509             :     std::atomic_bool m_start_extra_block_relay_peers{false};
    1510             : 
    1511             :     /**
    1512             :      * A vector of -bind=<address>:<port>=onion arguments each of which is
    1513             :      * an address and port that are designated for incoming Tor connections.
    1514             :      */
    1515             :     std::vector<CService> m_onion_binds;
    1516             : 
    1517             :     /**
    1518             :      * Mutex protecting m_i2p_sam_sessions.
    1519             :      */
    1520             :     Mutex m_unused_i2p_sessions_mutex;
    1521             : 
    1522             :     /**
    1523             :      * A pool of created I2P SAM transient sessions that should be used instead
    1524             :      * of creating new ones in order to reduce the load on the I2P network.
    1525             :      * Creating a session in I2P is not cheap, thus if this is not empty, then
    1526             :      * pick an entry from it instead of creating a new session. If connecting to
    1527             :      * a host fails, then the created session is put to this pool for reuse.
    1528             :      */
    1529             :     std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
    1530             : 
    1531             :     /**
    1532             :      * Cap on the size of `m_unused_i2p_sessions`, to ensure it does not
    1533             :      * unexpectedly use too much memory.
    1534             :      */
    1535             :     static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
    1536             : 
    1537             :     /**
    1538             :      * RAII helper to atomically create a copy of `m_nodes` and add a reference
    1539             :      * to each of the nodes. The nodes are released when this object is destroyed.
    1540             :      */
    1541             :     class NodesSnapshot
    1542             :     {
    1543             :     public:
    1544           0 :         explicit NodesSnapshot(const CConnman& connman, bool shuffle)
    1545             :         {
    1546             :             {
    1547           0 :                 LOCK(connman.m_nodes_mutex);
    1548           0 :                 m_nodes_copy = connman.m_nodes;
    1549           0 :                 for (auto& node : m_nodes_copy) {
    1550           0 :                     node->AddRef();
    1551             :                 }
    1552           0 :             }
    1553           0 :             if (shuffle) {
    1554           0 :                 Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
    1555           0 :             }
    1556           0 :         }
    1557             : 
    1558           0 :         ~NodesSnapshot()
    1559             :         {
    1560           0 :             for (auto& node : m_nodes_copy) {
    1561           0 :                 node->Release();
    1562             :             }
    1563           0 :         }
    1564             : 
    1565           0 :         const std::vector<CNode*>& Nodes() const
    1566             :         {
    1567           0 :             return m_nodes_copy;
    1568             :         }
    1569             : 
    1570             :     private:
    1571             :         std::vector<CNode*> m_nodes_copy;
    1572             :     };
    1573             : 
    1574             :     const CChainParams& m_params;
    1575             : 
    1576             :     friend struct ConnmanTestMsg;
    1577             : };
    1578             : 
    1579             : /** Defaults to `CaptureMessageToFile()`, but can be overridden by unit tests. */
    1580             : extern std::function<void(const CAddress& addr,
    1581             :                           const std::string& msg_type,
    1582             :                           Span<const unsigned char> data,
    1583             :                           bool is_incoming)>
    1584             :     CaptureMessage;
    1585             : 
    1586             : #endif // BITCOIN_NET_H

Generated by: LCOV version 1.14