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