LCOV - code coverage report
Current view: top level - src - net.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 44 195 22.6 %
Date: 2023-11-10 23:46:46 Functions: 5 77 6.5 %
Branches: 1 63 1.6 %

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

Generated by: LCOV version 1.14