Branch data Line data Source code
# 1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
# 2 : : // Copyright (c) 2009-2021 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 <chainparams.h>
# 10 : : #include <common/bloom.h>
# 11 : : #include <compat.h>
# 12 : : #include <consensus/amount.h>
# 13 : : #include <crypto/siphash.h>
# 14 : : #include <hash.h>
# 15 : : #include <i2p.h>
# 16 : : #include <logging.h>
# 17 : : #include <net_permissions.h>
# 18 : : #include <netaddress.h>
# 19 : : #include <netbase.h>
# 20 : : #include <policy/feerate.h>
# 21 : : #include <protocol.h>
# 22 : : #include <random.h>
# 23 : : #include <span.h>
# 24 : : #include <streams.h>
# 25 : : #include <sync.h>
# 26 : : #include <threadinterrupt.h>
# 27 : : #include <uint256.h>
# 28 : : #include <util/check.h>
# 29 : : #include <util/sock.h>
# 30 : :
# 31 : : #include <atomic>
# 32 : : #include <condition_variable>
# 33 : : #include <cstdint>
# 34 : : #include <deque>
# 35 : : #include <functional>
# 36 : : #include <list>
# 37 : : #include <map>
# 38 : : #include <memory>
# 39 : : #include <optional>
# 40 : : #include <thread>
# 41 : : #include <vector>
# 42 : :
# 43 : : class AddrMan;
# 44 : : class BanMan;
# 45 : : class CNode;
# 46 : : class CScheduler;
# 47 : : struct bilingual_str;
# 48 : :
# 49 : : /** Default for -whitelistrelay. */
# 50 : : static const bool DEFAULT_WHITELISTRELAY = true;
# 51 : : /** Default for -whitelistforcerelay. */
# 52 : : static const bool DEFAULT_WHITELISTFORCERELAY = false;
# 53 : :
# 54 : : /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
# 55 : : static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
# 56 : : /** Run the feeler connection loop once every 2 minutes. **/
# 57 : : static constexpr auto FEELER_INTERVAL = 2min;
# 58 : : /** Run the extra block-relay-only connection loop once every 5 minutes. **/
# 59 : : static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
# 60 : : /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
# 61 : : static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
# 62 : : /** Maximum length of the user agent string in `version` message */
# 63 : : static const unsigned int MAX_SUBVERSION_LENGTH = 256;
# 64 : : /** Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc) */
# 65 : : static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
# 66 : : /** Maximum number of addnode outgoing nodes */
# 67 : : static const int MAX_ADDNODE_CONNECTIONS = 8;
# 68 : : /** Maximum number of block-relay-only outgoing connections */
# 69 : : static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
# 70 : : /** Maximum number of feeler connections */
# 71 : : static const int MAX_FEELER_CONNECTIONS = 1;
# 72 : : /** -listen default */
# 73 : : static const bool DEFAULT_LISTEN = true;
# 74 : : /** The maximum number of peer connections to maintain. */
# 75 : : static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
# 76 : : /** The default for -maxuploadtarget. 0 = Unlimited */
# 77 : : static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
# 78 : : /** Default for blocks only*/
# 79 : : static const bool DEFAULT_BLOCKSONLY = false;
# 80 : : /** -peertimeout default */
# 81 : : static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
# 82 : : /** Number of file descriptors required for message capture **/
# 83 : : static const int NUM_FDS_MESSAGE_CAPTURE = 1;
# 84 : :
# 85 : : static constexpr bool DEFAULT_FORCEDNSSEED{false};
# 86 : : static constexpr bool DEFAULT_DNSSEED{true};
# 87 : : static constexpr bool DEFAULT_FIXEDSEEDS{true};
# 88 : : static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
# 89 : : static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
# 90 : :
# 91 : : typedef int64_t NodeId;
# 92 : :
# 93 : : struct AddedNodeInfo
# 94 : : {
# 95 : : std::string strAddedNode;
# 96 : : CService resolvedAddress;
# 97 : : bool fConnected;
# 98 : : bool fInbound;
# 99 : : };
# 100 : :
# 101 : : class CNodeStats;
# 102 : : class CClientUIInterface;
# 103 : :
# 104 : : struct CSerializedNetMsg {
# 105 : 123718 : CSerializedNetMsg() = default;
# 106 : 10337 : CSerializedNetMsg(CSerializedNetMsg&&) = default;
# 107 : : CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
# 108 : : // No implicit copying, only moves.
# 109 : : CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
# 110 : : CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
# 111 : :
# 112 : : CSerializedNetMsg Copy() const
# 113 : 12894 : {
# 114 : 12894 : CSerializedNetMsg copy;
# 115 : 12894 : copy.data = data;
# 116 : 12894 : copy.m_type = m_type;
# 117 : 12894 : return copy;
# 118 : 12894 : }
# 119 : :
# 120 : : std::vector<unsigned char> data;
# 121 : : std::string m_type;
# 122 : : };
# 123 : :
# 124 : : /** Different types of connections to a peer. This enum encapsulates the
# 125 : : * information we have available at the time of opening or accepting the
# 126 : : * connection. Aside from INBOUND, all types are initiated by us.
# 127 : : *
# 128 : : * If adding or removing types, please update CONNECTION_TYPE_DOC in
# 129 : : * src/rpc/net.cpp and src/qt/rpcconsole.cpp, as well as the descriptions in
# 130 : : * src/qt/guiutil.cpp and src/bitcoin-cli.cpp::NetinfoRequestHandler. */
# 131 : : enum class ConnectionType {
# 132 : : /**
# 133 : : * Inbound connections are those initiated by a peer. This is the only
# 134 : : * property we know at the time of connection, until P2P messages are
# 135 : : * exchanged.
# 136 : : */
# 137 : : INBOUND,
# 138 : :
# 139 : : /**
# 140 : : * These are the default connections that we use to connect with the
# 141 : : * network. There is no restriction on what is relayed; by default we relay
# 142 : : * blocks, addresses & transactions. We automatically attempt to open
# 143 : : * MAX_OUTBOUND_FULL_RELAY_CONNECTIONS using addresses from our AddrMan.
# 144 : : */
# 145 : : OUTBOUND_FULL_RELAY,
# 146 : :
# 147 : :
# 148 : : /**
# 149 : : * We open manual connections to addresses that users explicitly requested
# 150 : : * via the addnode RPC or the -addnode/-connect configuration options. Even if a
# 151 : : * manual connection is misbehaving, we do not automatically disconnect or
# 152 : : * add it to our discouragement filter.
# 153 : : */
# 154 : : MANUAL,
# 155 : :
# 156 : : /**
# 157 : : * Feeler connections are short-lived connections made to check that a node
# 158 : : * is alive. They can be useful for:
# 159 : : * - test-before-evict: if one of the peers is considered for eviction from
# 160 : : * our AddrMan because another peer is mapped to the same slot in the tried table,
# 161 : : * evict only if this longer-known peer is offline.
# 162 : : * - move node addresses from New to Tried table, so that we have more
# 163 : : * connectable addresses in our AddrMan.
# 164 : : * Note that in the literature ("Eclipse Attacks on Bitcoin’s Peer-to-Peer Network")
# 165 : : * only the latter feature is referred to as "feeler connections",
# 166 : : * although in our codebase feeler connections encompass test-before-evict as well.
# 167 : : * We make these connections approximately every FEELER_INTERVAL:
# 168 : : * first we resolve previously found collisions if they exist (test-before-evict),
# 169 : : * otherwise we connect to a node from the new table.
# 170 : : */
# 171 : : FEELER,
# 172 : :
# 173 : : /**
# 174 : : * We use block-relay-only connections to help prevent against partition
# 175 : : * attacks. By not relaying transactions or addresses, these connections
# 176 : : * are harder to detect by a third party, thus helping obfuscate the
# 177 : : * network topology. We automatically attempt to open
# 178 : : * MAX_BLOCK_RELAY_ONLY_ANCHORS using addresses from our anchors.dat. Then
# 179 : : * addresses from our AddrMan if MAX_BLOCK_RELAY_ONLY_CONNECTIONS
# 180 : : * isn't reached yet.
# 181 : : */
# 182 : : BLOCK_RELAY,
# 183 : :
# 184 : : /**
# 185 : : * AddrFetch connections are short lived connections used to solicit
# 186 : : * addresses from peers. These are initiated to addresses submitted via the
# 187 : : * -seednode command line argument, or under certain conditions when the
# 188 : : * AddrMan is empty.
# 189 : : */
# 190 : : ADDR_FETCH,
# 191 : : };
# 192 : :
# 193 : : /** Convert ConnectionType enum to a string value */
# 194 : : std::string ConnectionTypeAsString(ConnectionType conn_type);
# 195 : :
# 196 : : /**
# 197 : : * Look up IP addresses from all interfaces on the machine and add them to the
# 198 : : * list of local addresses to self-advertise.
# 199 : : * The loopback interface is skipped and only the first address from each
# 200 : : * interface is used.
# 201 : : */
# 202 : : void Discover();
# 203 : :
# 204 : : uint16_t GetListenPort();
# 205 : :
# 206 : : enum
# 207 : : {
# 208 : : LOCAL_NONE, // unknown
# 209 : : LOCAL_IF, // address a local interface listens on
# 210 : : LOCAL_BIND, // address explicit bound to
# 211 : : LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
# 212 : : LOCAL_MANUAL, // address explicitly specified (-externalip=)
# 213 : :
# 214 : : LOCAL_MAX
# 215 : : };
# 216 : :
# 217 : : bool IsPeerAddrLocalGood(CNode *pnode);
# 218 : : /** Returns a local address that we should advertise to this peer */
# 219 : : std::optional<CAddress> GetLocalAddrForPeer(CNode *pnode);
# 220 : :
# 221 : : /**
# 222 : : * Mark a network as reachable or unreachable (no automatic connects to it)
# 223 : : * @note Networks are reachable by default
# 224 : : */
# 225 : : void SetReachable(enum Network net, bool reachable);
# 226 : : /** @returns true if the network is reachable, false otherwise */
# 227 : : bool IsReachable(enum Network net);
# 228 : : /** @returns true if the address is in a reachable network, false otherwise */
# 229 : : bool IsReachable(const CNetAddr& addr);
# 230 : :
# 231 : : bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
# 232 : : bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
# 233 : : void RemoveLocal(const CService& addr);
# 234 : : bool SeenLocal(const CService& addr);
# 235 : : bool IsLocal(const CService& addr);
# 236 : : bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
# 237 : : CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
# 238 : :
# 239 : :
# 240 : : extern bool fDiscover;
# 241 : : extern bool fListen;
# 242 : :
# 243 : : /** Subversion as sent to the P2P network in `version` messages */
# 244 : : extern std::string strSubVersion;
# 245 : :
# 246 : : struct LocalServiceInfo {
# 247 : : int nScore;
# 248 : : uint16_t nPort;
# 249 : : };
# 250 : :
# 251 : : extern Mutex g_maplocalhost_mutex;
# 252 : : extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
# 253 : :
# 254 : : extern const std::string NET_MESSAGE_COMMAND_OTHER;
# 255 : : typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
# 256 : :
# 257 : : class CNodeStats
# 258 : : {
# 259 : : public:
# 260 : : NodeId nodeid;
# 261 : : ServiceFlags nServices;
# 262 : : std::chrono::seconds m_last_send;
# 263 : : std::chrono::seconds m_last_recv;
# 264 : : std::chrono::seconds m_last_tx_time;
# 265 : : std::chrono::seconds m_last_block_time;
# 266 : : std::chrono::seconds m_connected;
# 267 : : int64_t nTimeOffset;
# 268 : : std::string m_addr_name;
# 269 : : int nVersion;
# 270 : : std::string cleanSubVer;
# 271 : : bool fInbound;
# 272 : : bool m_bip152_highbandwidth_to;
# 273 : : bool m_bip152_highbandwidth_from;
# 274 : : int m_starting_height;
# 275 : : uint64_t nSendBytes;
# 276 : : mapMsgCmdSize mapSendBytesPerMsgCmd;
# 277 : : uint64_t nRecvBytes;
# 278 : : mapMsgCmdSize mapRecvBytesPerMsgCmd;
# 279 : : NetPermissionFlags m_permissionFlags;
# 280 : : std::chrono::microseconds m_last_ping_time;
# 281 : : std::chrono::microseconds m_min_ping_time;
# 282 : : // Our address, as reported by the peer
# 283 : : std::string addrLocal;
# 284 : : // Address of this peer
# 285 : : CAddress addr;
# 286 : : // Bind address of our side of the connection
# 287 : : CAddress addrBind;
# 288 : : // Network the peer connected through
# 289 : : Network m_network;
# 290 : : uint32_t m_mapped_as;
# 291 : : ConnectionType m_conn_type;
# 292 : : };
# 293 : :
# 294 : :
# 295 : : /** Transport protocol agnostic message container.
# 296 : : * Ideally it should only contain receive time, payload,
# 297 : : * type and size.
# 298 : : */
# 299 : : class CNetMessage {
# 300 : : public:
# 301 : : CDataStream m_recv; //!< received message data
# 302 : : std::chrono::microseconds m_time{0}; //!< time of message receipt
# 303 : : uint32_t m_message_size{0}; //!< size of the payload
# 304 : : uint32_t m_raw_message_size{0}; //!< used wire size of the message (including header/checksum)
# 305 : : std::string m_type;
# 306 : :
# 307 : 111710 : CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
# 308 : :
# 309 : : void SetVersion(int nVersionIn)
# 310 : 107420 : {
# 311 : 107420 : m_recv.SetVersion(nVersionIn);
# 312 : 107420 : }
# 313 : : };
# 314 : :
# 315 : : /** The TransportDeserializer takes care of holding and deserializing the
# 316 : : * network receive buffer. It can deserialize the network buffer into a
# 317 : : * transport protocol agnostic CNetMessage (command & payload)
# 318 : : */
# 319 : : class TransportDeserializer {
# 320 : : public:
# 321 : : // returns true if the current deserialization is complete
# 322 : : virtual bool Complete() const = 0;
# 323 : : // set the serialization context version
# 324 : : virtual void SetVersion(int version) = 0;
# 325 : : /** read and deserialize data, advances msg_bytes data pointer */
# 326 : : virtual int Read(Span<const uint8_t>& msg_bytes) = 0;
# 327 : : // decomposes a message from the context
# 328 : : virtual CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) = 0;
# 329 : 2314 : virtual ~TransportDeserializer() {}
# 330 : : };
# 331 : :
# 332 : : class V1TransportDeserializer final : public TransportDeserializer
# 333 : : {
# 334 : : private:
# 335 : : const CChainParams& m_chain_params;
# 336 : : const NodeId m_node_id; // Only for logging
# 337 : : mutable CHash256 hasher;
# 338 : : mutable uint256 data_hash;
# 339 : : bool in_data; // parsing header (false) or data (true)
# 340 : : CDataStream hdrbuf; // partially received header
# 341 : : CMessageHeader hdr; // complete header
# 342 : : CDataStream vRecv; // received message data
# 343 : : unsigned int nHdrPos;
# 344 : : unsigned int nDataPos;
# 345 : :
# 346 : : const uint256& GetMessageHash() const;
# 347 : : int readHeader(Span<const uint8_t> msg_bytes);
# 348 : : int readData(Span<const uint8_t> msg_bytes);
# 349 : :
# 350 : 112871 : void Reset() {
# 351 : 112871 : vRecv.clear();
# 352 : 112871 : hdrbuf.clear();
# 353 : 112871 : hdrbuf.resize(24);
# 354 : 112871 : in_data = false;
# 355 : 112871 : nHdrPos = 0;
# 356 : 112871 : nDataPos = 0;
# 357 : 112871 : data_hash.SetNull();
# 358 : 112871 : hasher.Reset();
# 359 : 112871 : }
# 360 : :
# 361 : : public:
# 362 : : V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
# 363 : : : m_chain_params(chain_params),
# 364 : : m_node_id(node_id),
# 365 : : hdrbuf(nTypeIn, nVersionIn),
# 366 : : vRecv(nTypeIn, nVersionIn)
# 367 : 1157 : {
# 368 : 1157 : Reset();
# 369 : 1157 : }
# 370 : :
# 371 : : bool Complete() const override
# 372 : 352747 : {
# 373 [ + + ]: 352747 : if (!in_data)
# 374 : 1 : return false;
# 375 : 352746 : return (hdr.nMessageSize == nDataPos);
# 376 : 352747 : }
# 377 : : void SetVersion(int nVersionIn) override
# 378 : 0 : {
# 379 : 0 : hdrbuf.SetVersion(nVersionIn);
# 380 : 0 : vRecv.SetVersion(nVersionIn);
# 381 : 0 : }
# 382 : : int Read(Span<const uint8_t>& msg_bytes) override
# 383 : 241041 : {
# 384 [ + + ]: 241041 : int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
# 385 [ + + ]: 241041 : if (ret < 0) {
# 386 : 4 : Reset();
# 387 : 241037 : } else {
# 388 : 241037 : msg_bytes = msg_bytes.subspan(ret);
# 389 : 241037 : }
# 390 : 241041 : return ret;
# 391 : 241041 : }
# 392 : : CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) override;
# 393 : : };
# 394 : :
# 395 : : /** The TransportSerializer prepares messages for the network transport
# 396 : : */
# 397 : : class TransportSerializer {
# 398 : : public:
# 399 : : // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
# 400 : : virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
# 401 : 2314 : virtual ~TransportSerializer() {}
# 402 : : };
# 403 : :
# 404 : : class V1TransportSerializer : public TransportSerializer {
# 405 : : public:
# 406 : : void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
# 407 : : };
# 408 : :
# 409 : : /** Information about a peer */
# 410 : : class CNode
# 411 : : {
# 412 : : friend class CConnman;
# 413 : : friend struct ConnmanTestMsg;
# 414 : :
# 415 : : public:
# 416 : : std::unique_ptr<TransportDeserializer> m_deserializer;
# 417 : : std::unique_ptr<TransportSerializer> m_serializer;
# 418 : :
# 419 : : NetPermissionFlags m_permissionFlags{NetPermissionFlags::None};
# 420 : : std::atomic<ServiceFlags> nServices{NODE_NONE};
# 421 : :
# 422 : : /**
# 423 : : * Socket used for communication with the node.
# 424 : : * May not own a Sock object (after `CloseSocketDisconnect()` or during tests).
# 425 : : * `shared_ptr` (instead of `unique_ptr`) is used to avoid premature close of
# 426 : : * the underlying file descriptor by one thread while another thread is
# 427 : : * poll(2)-ing it for activity.
# 428 : : * @see https://github.com/bitcoin/bitcoin/issues/21744 for details.
# 429 : : */
# 430 : : std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
# 431 : :
# 432 : : /** Total size of all vSendMsg entries */
# 433 : : size_t nSendSize GUARDED_BY(cs_vSend){0};
# 434 : : /** Offset inside the first vSendMsg already sent */
# 435 : : size_t nSendOffset GUARDED_BY(cs_vSend){0};
# 436 : : uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
# 437 : : std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
# 438 : : Mutex cs_vSend;
# 439 : : Mutex m_sock_mutex;
# 440 : : Mutex cs_vRecv;
# 441 : :
# 442 : : RecursiveMutex cs_vProcessMsg;
# 443 : : std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
# 444 : : size_t nProcessQueueSize{0};
# 445 : :
# 446 : : RecursiveMutex cs_sendProcessing;
# 447 : :
# 448 : : uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
# 449 : :
# 450 : : std::atomic<std::chrono::seconds> m_last_send{0s};
# 451 : : std::atomic<std::chrono::seconds> m_last_recv{0s};
# 452 : : //! Unix epoch time at peer connection
# 453 : : const std::chrono::seconds m_connected;
# 454 : : std::atomic<int64_t> nTimeOffset{0};
# 455 : : // Address of this peer
# 456 : : const CAddress addr;
# 457 : : // Bind address of our side of the connection
# 458 : : const CAddress addrBind;
# 459 : : const std::string m_addr_name;
# 460 : : //! Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
# 461 : : const bool m_inbound_onion;
# 462 : : std::atomic<int> nVersion{0};
# 463 : : Mutex m_subver_mutex;
# 464 : : /**
# 465 : : * cleanSubVer is a sanitized string of the user agent byte array we read
# 466 : : * from the wire. This cleaned string can safely be logged or displayed.
# 467 : : */
# 468 : : std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
# 469 : : bool m_prefer_evict{false}; // This peer is preferred for eviction.
# 470 : 701632 : bool HasPermission(NetPermissionFlags permission) const {
# 471 : 701632 : return NetPermissions::HasFlag(m_permissionFlags, permission);
# 472 : 701632 : }
# 473 : : bool fClient{false}; // set by version message
# 474 : : bool m_limited_node{false}; //after BIP159, set by version message
# 475 : : /** fSuccessfullyConnected is set to true on receiving VERACK from the peer. */
# 476 : : std::atomic_bool fSuccessfullyConnected{false};
# 477 : : // Setting fDisconnect to true will cause the node to be disconnected the
# 478 : : // next time DisconnectNodes() runs
# 479 : : std::atomic_bool fDisconnect{false};
# 480 : : CSemaphoreGrant grantOutbound;
# 481 : : std::atomic<int> nRefCount{0};
# 482 : :
# 483 : : const uint64_t nKeyedNetGroup;
# 484 : : std::atomic_bool fPauseRecv{false};
# 485 : : std::atomic_bool fPauseSend{false};
# 486 : :
# 487 : 316708 : bool IsOutboundOrBlockRelayConn() const {
# 488 [ - + ]: 316708 : switch (m_conn_type) {
# 489 [ + + ]: 1675 : case ConnectionType::OUTBOUND_FULL_RELAY:
# 490 [ + + ]: 2354 : case ConnectionType::BLOCK_RELAY:
# 491 : 2354 : return true;
# 492 [ + + ]: 176934 : case ConnectionType::INBOUND:
# 493 [ + + ]: 314342 : case ConnectionType::MANUAL:
# 494 [ + + ]: 314354 : case ConnectionType::ADDR_FETCH:
# 495 [ - + ]: 314354 : case ConnectionType::FEELER:
# 496 : 314354 : return false;
# 497 : 316708 : } // no default case, so the compiler can warn about missing cases
# 498 : :
# 499 : 0 : assert(false);
# 500 : 0 : }
# 501 : :
# 502 : 8259 : bool IsFullOutboundConn() const {
# 503 : 8259 : return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
# 504 : 8259 : }
# 505 : :
# 506 : 106 : bool IsManualConn() const {
# 507 : 106 : return m_conn_type == ConnectionType::MANUAL;
# 508 : 106 : }
# 509 : :
# 510 : 3562 : bool IsBlockOnlyConn() const {
# 511 : 3562 : return m_conn_type == ConnectionType::BLOCK_RELAY;
# 512 : 3562 : }
# 513 : :
# 514 : 2186 : bool IsFeelerConn() const {
# 515 : 2186 : return m_conn_type == ConnectionType::FEELER;
# 516 : 2186 : }
# 517 : :
# 518 : 402036 : bool IsAddrFetchConn() const {
# 519 : 402036 : return m_conn_type == ConnectionType::ADDR_FETCH;
# 520 : 402036 : }
# 521 : :
# 522 : 51935 : bool IsInboundConn() const {
# 523 : 51935 : return m_conn_type == ConnectionType::INBOUND;
# 524 : 51935 : }
# 525 : :
# 526 : 1081 : bool ExpectServicesFromConn() const {
# 527 [ - + ]: 1081 : switch (m_conn_type) {
# 528 [ + + ]: 673 : case ConnectionType::INBOUND:
# 529 [ + + ]: 1024 : case ConnectionType::MANUAL:
# 530 [ + + ]: 1025 : case ConnectionType::FEELER:
# 531 : 1025 : return false;
# 532 [ + + ]: 36 : case ConnectionType::OUTBOUND_FULL_RELAY:
# 533 [ + + ]: 54 : case ConnectionType::BLOCK_RELAY:
# 534 [ + + ]: 56 : case ConnectionType::ADDR_FETCH:
# 535 : 56 : return true;
# 536 : 1081 : } // no default case, so the compiler can warn about missing cases
# 537 : :
# 538 : 0 : assert(false);
# 539 : 0 : }
# 540 : :
# 541 : : /**
# 542 : : * Get network the peer connected through.
# 543 : : *
# 544 : : * Returns Network::NET_ONION for *inbound* onion connections,
# 545 : : * and CNetAddr::GetNetClass() otherwise. The latter cannot be used directly
# 546 : : * because it doesn't detect the former, and it's not the responsibility of
# 547 : : * the CNetAddr class to know the actual network a peer is connected through.
# 548 : : *
# 549 : : * @return network the peer connected through.
# 550 : : */
# 551 : : Network ConnectedThroughNetwork() const;
# 552 : :
# 553 : : // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
# 554 : : std::atomic<bool> m_bip152_highbandwidth_to{false};
# 555 : : // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
# 556 : : std::atomic<bool> m_bip152_highbandwidth_from{false};
# 557 : :
# 558 : : /** Whether we should relay transactions to this peer (their version
# 559 : : * message did not include fRelay=false and this is not a block-relay-only
# 560 : : * connection). This only changes from false to true. It will never change
# 561 : : * back to false. Used only in inbound eviction logic. */
# 562 : : std::atomic_bool m_relays_txs{false};
# 563 : :
# 564 : : /** Whether this peer has loaded a bloom filter. Used only in inbound
# 565 : : * eviction logic. */
# 566 : : std::atomic_bool m_bloom_filter_loaded{false};
# 567 : :
# 568 : : /** UNIX epoch time of the last block received from this peer that we had
# 569 : : * not yet seen (e.g. not already received from another peer), that passed
# 570 : : * preliminary validity checks and was saved to disk, even if we don't
# 571 : : * connect the block or it eventually fails connection. Used as an inbound
# 572 : : * peer eviction criterium in CConnman::AttemptToEvictConnection. */
# 573 : : std::atomic<std::chrono::seconds> m_last_block_time{0s};
# 574 : :
# 575 : : /** UNIX epoch time of the last transaction received from this peer that we
# 576 : : * had not yet seen (e.g. not already received from another peer) and that
# 577 : : * was accepted into our mempool. Used as an inbound peer eviction criterium
# 578 : : * in CConnman::AttemptToEvictConnection. */
# 579 : : std::atomic<std::chrono::seconds> m_last_tx_time{0s};
# 580 : :
# 581 : : /** Last measured round-trip time. Used only for RPC/GUI stats/debugging.*/
# 582 : : std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
# 583 : :
# 584 : : /** Lowest measured round-trip time. Used as an inbound peer eviction
# 585 : : * criterium in CConnman::AttemptToEvictConnection. */
# 586 : : std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
# 587 : :
# 588 : : CNode(NodeId id, ServiceFlags nLocalServicesIn, std::shared_ptr<Sock> sock, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress& addrBindIn, const std::string& addrNameIn, ConnectionType conn_type_in, bool inbound_onion);
# 589 : : CNode(const CNode&) = delete;
# 590 : : CNode& operator=(const CNode&) = delete;
# 591 : :
# 592 : 3149380 : NodeId GetId() const {
# 593 : 3149380 : return id;
# 594 : 3149380 : }
# 595 : :
# 596 : 1131 : uint64_t GetLocalNonce() const {
# 597 : 1131 : return nLocalHostNonce;
# 598 : 1131 : }
# 599 : :
# 600 : : int GetRefCount() const
# 601 : 424 : {
# 602 : 424 : assert(nRefCount >= 0);
# 603 : 0 : return nRefCount;
# 604 : 424 : }
# 605 : :
# 606 : : /**
# 607 : : * Receive bytes from the buffer and deserialize them into messages.
# 608 : : *
# 609 : : * @param[in] msg_bytes The raw data
# 610 : : * @param[out] complete Set True if at least one message has been
# 611 : : * deserialized and is ready to be processed
# 612 : : * @return True if the peer should stay connected,
# 613 : : * False if the peer should be disconnected from.
# 614 : : */
# 615 : : bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete);
# 616 : :
# 617 : : void SetCommonVersion(int greatest_common_version)
# 618 : 1114 : {
# 619 : 1114 : Assume(m_greatest_common_version == INIT_PROTO_VERSION);
# 620 : 1114 : m_greatest_common_version = greatest_common_version;
# 621 : 1114 : }
# 622 : : int GetCommonVersion() const
# 623 : 1609736 : {
# 624 : 1609736 : return m_greatest_common_version;
# 625 : 1609736 : }
# 626 : :
# 627 : : CService GetAddrLocal() const LOCKS_EXCLUDED(m_addr_local_mutex);
# 628 : : //! May not be called more than once
# 629 : : void SetAddrLocal(const CService& addrLocalIn) LOCKS_EXCLUDED(m_addr_local_mutex);
# 630 : :
# 631 : : CNode* AddRef()
# 632 : 819339 : {
# 633 : 819339 : nRefCount++;
# 634 : 819339 : return this;
# 635 : 819339 : }
# 636 : :
# 637 : : void Release()
# 638 : 818648 : {
# 639 : 818648 : nRefCount--;
# 640 : 818648 : }
# 641 : :
# 642 : : void CloseSocketDisconnect();
# 643 : :
# 644 : : void CopyStats(CNodeStats& stats);
# 645 : :
# 646 : : ServiceFlags GetLocalServices() const
# 647 : 31852 : {
# 648 : 31852 : return nLocalServices;
# 649 : 31852 : }
# 650 : :
# 651 : 469 : std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
# 652 : :
# 653 : : /** A ping-pong round trip has completed successfully. Update latest and minimum ping times. */
# 654 : 1263 : void PongReceived(std::chrono::microseconds ping_time) {
# 655 : 1263 : m_last_ping_time = ping_time;
# 656 : 1263 : m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
# 657 : 1263 : }
# 658 : :
# 659 : : private:
# 660 : : const NodeId id;
# 661 : : const uint64_t nLocalHostNonce;
# 662 : : const ConnectionType m_conn_type;
# 663 : : std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
# 664 : :
# 665 : : //! Services offered to this peer.
# 666 : : //!
# 667 : : //! This is supplied by the parent CConnman during peer connection
# 668 : : //! (CConnman::ConnectNode()) from its attribute of the same name.
# 669 : : //!
# 670 : : //! This is const because there is no protocol defined for renegotiating
# 671 : : //! services initially offered to a peer. The set of local services we
# 672 : : //! offer should not change after initialization.
# 673 : : //!
# 674 : : //! An interesting example of this is NODE_NETWORK and initial block
# 675 : : //! download: a node which starts up from scratch doesn't have any blocks
# 676 : : //! to serve, but still advertises NODE_NETWORK because it will eventually
# 677 : : //! fulfill this role after IBD completes. P2P code is written in such a
# 678 : : //! way that it can gracefully handle peers who don't make good on their
# 679 : : //! service advertisements.
# 680 : : const ServiceFlags nLocalServices;
# 681 : :
# 682 : : std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
# 683 : :
# 684 : : // Our address, as reported by the peer
# 685 : : CService addrLocal GUARDED_BY(m_addr_local_mutex);
# 686 : : mutable Mutex m_addr_local_mutex;
# 687 : :
# 688 : : mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend);
# 689 : : mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
# 690 : : };
# 691 : :
# 692 : : /**
# 693 : : * Interface for message handling
# 694 : : */
# 695 : : class NetEventsInterface
# 696 : : {
# 697 : : public:
# 698 : : /** Initialize a peer (setup state, queue any initial messages) */
# 699 : : virtual void InitializeNode(CNode* pnode) = 0;
# 700 : :
# 701 : : /** Handle removal of a peer (clear state) */
# 702 : : virtual void FinalizeNode(const CNode& node) = 0;
# 703 : :
# 704 : : /**
# 705 : : * Process protocol messages received from a given node
# 706 : : *
# 707 : : * @param[in] pnode The node which we have received messages from.
# 708 : : * @param[in] interrupt Interrupt condition for processing threads
# 709 : : * @return True if there is more work to be done
# 710 : : */
# 711 : : virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
# 712 : :
# 713 : : /**
# 714 : : * Send queued protocol messages to a given node.
# 715 : : *
# 716 : : * @param[in] pnode The node which we are sending messages to.
# 717 : : * @return True if there is more work to be done
# 718 : : */
# 719 : : virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
# 720 : :
# 721 : :
# 722 : : protected:
# 723 : : /**
# 724 : : * Protected destructor so that instances can only be deleted by derived classes.
# 725 : : * If that restriction is no longer desired, this should be made public and virtual.
# 726 : : */
# 727 : : ~NetEventsInterface() = default;
# 728 : : };
# 729 : :
# 730 : : class CConnman
# 731 : : {
# 732 : : public:
# 733 : :
# 734 : : struct Options
# 735 : : {
# 736 : : ServiceFlags nLocalServices = NODE_NONE;
# 737 : : int nMaxConnections = 0;
# 738 : : int m_max_outbound_full_relay = 0;
# 739 : : int m_max_outbound_block_relay = 0;
# 740 : : int nMaxAddnode = 0;
# 741 : : int nMaxFeeler = 0;
# 742 : : CClientUIInterface* uiInterface = nullptr;
# 743 : : NetEventsInterface* m_msgproc = nullptr;
# 744 : : BanMan* m_banman = nullptr;
# 745 : : unsigned int nSendBufferMaxSize = 0;
# 746 : : unsigned int nReceiveFloodSize = 0;
# 747 : : uint64_t nMaxOutboundLimit = 0;
# 748 : : int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
# 749 : : std::vector<std::string> vSeedNodes;
# 750 : : std::vector<NetWhitelistPermissions> vWhitelistedRange;
# 751 : : std::vector<NetWhitebindPermissions> vWhiteBinds;
# 752 : : std::vector<CService> vBinds;
# 753 : : std::vector<CService> onion_binds;
# 754 : : /// True if the user did not specify -bind= or -whitebind= and thus
# 755 : : /// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
# 756 : : bool bind_on_any;
# 757 : : bool m_use_addrman_outgoing = true;
# 758 : : std::vector<std::string> m_specified_outgoing;
# 759 : : std::vector<std::string> m_added_nodes;
# 760 : : bool m_i2p_accept_incoming;
# 761 : : };
# 762 : :
# 763 : 1892 : void Init(const Options& connOptions) {
# 764 : 1892 : nLocalServices = connOptions.nLocalServices;
# 765 : 1892 : nMaxConnections = connOptions.nMaxConnections;
# 766 : 1892 : m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
# 767 : 1892 : m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
# 768 : 1892 : m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
# 769 : 1892 : nMaxAddnode = connOptions.nMaxAddnode;
# 770 : 1892 : nMaxFeeler = connOptions.nMaxFeeler;
# 771 : 1892 : m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
# 772 : 1892 : m_client_interface = connOptions.uiInterface;
# 773 : 1892 : m_banman = connOptions.m_banman;
# 774 : 1892 : m_msgproc = connOptions.m_msgproc;
# 775 : 1892 : nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
# 776 : 1892 : nReceiveFloodSize = connOptions.nReceiveFloodSize;
# 777 : 1892 : m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
# 778 : 1892 : {
# 779 : 1892 : LOCK(cs_totalBytesSent);
# 780 : 1892 : nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
# 781 : 1892 : }
# 782 : 1892 : vWhitelistedRange = connOptions.vWhitelistedRange;
# 783 : 1892 : {
# 784 : 1892 : LOCK(m_added_nodes_mutex);
# 785 : 1892 : m_added_nodes = connOptions.m_added_nodes;
# 786 : 1892 : }
# 787 : 1892 : m_onion_binds = connOptions.onion_binds;
# 788 : 1892 : }
# 789 : :
# 790 : : CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, bool network_active = true);
# 791 : : ~CConnman();
# 792 : : bool Start(CScheduler& scheduler, const Options& options);
# 793 : :
# 794 : : void StopThreads();
# 795 : : void StopNodes();
# 796 : : void Stop()
# 797 : 1725 : {
# 798 : 1725 : StopThreads();
# 799 : 1725 : StopNodes();
# 800 : 1725 : };
# 801 : :
# 802 : : void Interrupt();
# 803 : 157 : bool GetNetworkActive() const { return fNetworkActive; };
# 804 : 67 : bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
# 805 : : void SetNetworkActive(bool active);
# 806 : : void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
# 807 : : bool CheckIncomingNonce(uint64_t nonce);
# 808 : :
# 809 : : bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
# 810 : :
# 811 : : void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
# 812 : :
# 813 : : using NodeFn = std::function<void(CNode*)>;
# 814 : : void ForEachNode(const NodeFn& func)
# 815 : 46424 : {
# 816 : 46424 : LOCK(m_nodes_mutex);
# 817 [ + + ]: 60311 : for (auto&& node : m_nodes) {
# 818 [ + + ]: 60311 : if (NodeFullyConnected(node))
# 819 : 60304 : func(node);
# 820 : 60311 : }
# 821 : 46424 : };
# 822 : :
# 823 : : void ForEachNode(const NodeFn& func) const
# 824 : 0 : {
# 825 : 0 : LOCK(m_nodes_mutex);
# 826 : 0 : for (auto&& node : m_nodes) {
# 827 : 0 : if (NodeFullyConnected(node))
# 828 : 0 : func(node);
# 829 : 0 : }
# 830 : 0 : };
# 831 : :
# 832 : : // Addrman functions
# 833 : : /**
# 834 : : * Return all or many randomly selected addresses, optionally by network.
# 835 : : *
# 836 : : * @param[in] max_addresses Maximum number of addresses to return (0 = all).
# 837 : : * @param[in] max_pct Maximum percentage of addresses to return (0 = all).
# 838 : : * @param[in] network Select only addresses of this network (nullopt = all).
# 839 : : */
# 840 : : std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
# 841 : : /**
# 842 : : * Cache is used to minimize topology leaks, so it should
# 843 : : * be used for all non-trusted calls, for example, p2p.
# 844 : : * A non-malicious call (from RPC or a peer with addr permission) should
# 845 : : * call the function without a parameter to avoid using the cache.
# 846 : : */
# 847 : : std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
# 848 : :
# 849 : : // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
# 850 : : // a peer that is better than all our current peers.
# 851 : : void SetTryNewOutboundPeer(bool flag);
# 852 : : bool GetTryNewOutboundPeer() const;
# 853 : :
# 854 : 49 : void StartExtraBlockRelayPeers() {
# 855 [ + - ]: 49 : LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
# 856 : 49 : m_start_extra_block_relay_peers = true;
# 857 : 49 : }
# 858 : :
# 859 : : // Return the number of outbound peers we have in excess of our target (eg,
# 860 : : // if we previously called SetTryNewOutboundPeer(true), and have since set
# 861 : : // to false, we may have extra peers that we wish to disconnect). This may
# 862 : : // return a value less than (num_outbound_connections - num_outbound_slots)
# 863 : : // in cases where some outbound connections are not yet fully connected, or
# 864 : : // not yet fully disconnected.
# 865 : : int GetExtraFullOutboundCount() const;
# 866 : : // Count the number of block-relay-only peers we have over our limit.
# 867 : : int GetExtraBlockRelayCount() const;
# 868 : :
# 869 : : bool AddNode(const std::string& node);
# 870 : : bool RemoveAddedNode(const std::string& node);
# 871 : : std::vector<AddedNodeInfo> GetAddedNodeInfo() const;
# 872 : :
# 873 : : /**
# 874 : : * Attempts to open a connection. Currently only used from tests.
# 875 : : *
# 876 : : * @param[in] address Address of node to try connecting to
# 877 : : * @param[in] conn_type ConnectionType::OUTBOUND, ConnectionType::BLOCK_RELAY,
# 878 : : * ConnectionType::ADDR_FETCH or ConnectionType::FEELER
# 879 : : * @return bool Returns false if there are no available
# 880 : : * slots for this connection:
# 881 : : * - conn_type not a supported ConnectionType
# 882 : : * - Max total outbound connection capacity filled
# 883 : : * - Max connection capacity for type is filled
# 884 : : */
# 885 : : bool AddConnection(const std::string& address, ConnectionType conn_type);
# 886 : :
# 887 : : size_t GetNodeCount(ConnectionDirection) const;
# 888 : : void GetNodeStats(std::vector<CNodeStats>& vstats) const;
# 889 : : bool DisconnectNode(const std::string& node);
# 890 : : bool DisconnectNode(const CSubNet& subnet);
# 891 : : bool DisconnectNode(const CNetAddr& addr);
# 892 : : bool DisconnectNode(NodeId id);
# 893 : :
# 894 : : //! Used to convey which local services we are offering peers during node
# 895 : : //! connection.
# 896 : : //!
# 897 : : //! The data returned by this is used in CNode construction,
# 898 : : //! which is used to advertise which services we are offering
# 899 : : //! that peer during `net_processing.cpp:PushNodeVersion()`.
# 900 : : ServiceFlags GetLocalServices() const;
# 901 : :
# 902 : : uint64_t GetMaxOutboundTarget() const;
# 903 : : std::chrono::seconds GetMaxOutboundTimeframe() const;
# 904 : :
# 905 : : //! check if the outbound target is reached
# 906 : : //! if param historicalBlockServingLimit is set true, the function will
# 907 : : //! response true if the limit for serving historical blocks has been reached
# 908 : : bool OutboundTargetReached(bool historicalBlockServingLimit) const;
# 909 : :
# 910 : : //! response the bytes left in the current max outbound cycle
# 911 : : //! in case of no limit, it will always response 0
# 912 : : uint64_t GetOutboundTargetBytesLeft() const;
# 913 : :
# 914 : : //! returns the time left in the current max outbound cycle
# 915 : : //! in case of no limit, it will always return 0
# 916 : : std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
# 917 : :
# 918 : : uint64_t GetTotalBytesRecv() const;
# 919 : : uint64_t GetTotalBytesSent() const;
# 920 : :
# 921 : : /** Get a unique deterministic randomizer. */
# 922 : : CSipHasher GetDeterministicRandomizer(uint64_t id) const;
# 923 : :
# 924 : : unsigned int GetReceiveFloodSize() const;
# 925 : :
# 926 : : void WakeMessageHandler();
# 927 : :
# 928 : : /** Return true if we should disconnect the peer for failing an inactivity check. */
# 929 : : bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
# 930 : :
# 931 : : private:
# 932 : : struct ListenSocket {
# 933 : : public:
# 934 : : std::shared_ptr<Sock> sock;
# 935 : 679 : inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
# 936 : : ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
# 937 : : : sock{sock_}, m_permissions{permissions_}
# 938 : 866 : {
# 939 : 866 : }
# 940 : :
# 941 : : private:
# 942 : : NetPermissionFlags m_permissions;
# 943 : : };
# 944 : :
# 945 : : bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
# 946 : : bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
# 947 : : bool InitBinds(const Options& options);
# 948 : :
# 949 : : void ThreadOpenAddedConnections();
# 950 : : void AddAddrFetch(const std::string& strDest);
# 951 : : void ProcessAddrFetch();
# 952 : : void ThreadOpenConnections(std::vector<std::string> connect);
# 953 : : void ThreadMessageHandler();
# 954 : : void ThreadI2PAcceptIncoming();
# 955 : : void AcceptConnection(const ListenSocket& hListenSocket);
# 956 : :
# 957 : : /**
# 958 : : * Create a `CNode` object from a socket that has just been accepted and add the node to
# 959 : : * the `m_nodes` member.
# 960 : : * @param[in] sock Connected socket to communicate with the peer.
# 961 : : * @param[in] permissionFlags The peer's permissions.
# 962 : : * @param[in] addr_bind The address and port at our side of the connection.
# 963 : : * @param[in] addr The address and port at the peer's side of the connection.
# 964 : : */
# 965 : : void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
# 966 : : NetPermissionFlags permissionFlags,
# 967 : : const CAddress& addr_bind,
# 968 : : const CAddress& addr);
# 969 : :
# 970 : : void DisconnectNodes();
# 971 : : void NotifyNumConnectionsChanged();
# 972 : : /** Return true if the peer is inactive and should be disconnected. */
# 973 : : bool InactivityCheck(const CNode& node) const;
# 974 : :
# 975 : : /**
# 976 : : * Generate a collection of sockets to check for IO readiness.
# 977 : : * @param[in] nodes Select from these nodes' sockets.
# 978 : : * @param[out] recv_set Sockets to check for read readiness.
# 979 : : * @param[out] send_set Sockets to check for write readiness.
# 980 : : * @param[out] error_set Sockets to check for errors.
# 981 : : * @return true if at least one socket is to be checked (the returned set is not empty)
# 982 : : */
# 983 : : bool GenerateSelectSet(const std::vector<CNode*>& nodes,
# 984 : : std::set<SOCKET>& recv_set,
# 985 : : std::set<SOCKET>& send_set,
# 986 : : std::set<SOCKET>& error_set);
# 987 : :
# 988 : : /**
# 989 : : * Check which sockets are ready for IO.
# 990 : : * @param[in] nodes Select from these nodes' sockets.
# 991 : : * @param[out] recv_set Sockets which are ready for read.
# 992 : : * @param[out] send_set Sockets which are ready for write.
# 993 : : * @param[out] error_set Sockets which have errors.
# 994 : : * This calls `GenerateSelectSet()` to gather a list of sockets to check.
# 995 : : */
# 996 : : void SocketEvents(const std::vector<CNode*>& nodes,
# 997 : : std::set<SOCKET>& recv_set,
# 998 : : std::set<SOCKET>& send_set,
# 999 : : std::set<SOCKET>& error_set);
# 1000 : :
# 1001 : : /**
# 1002 : : * Check connected and listening sockets for IO readiness and process them accordingly.
# 1003 : : */
# 1004 : : void SocketHandler();
# 1005 : :
# 1006 : : /**
# 1007 : : * Do the read/write for connected sockets that are ready for IO.
# 1008 : : * @param[in] nodes Nodes to process. The socket of each node is checked against
# 1009 : : * `recv_set`, `send_set` and `error_set`.
# 1010 : : * @param[in] recv_set Sockets that are ready for read.
# 1011 : : * @param[in] send_set Sockets that are ready for send.
# 1012 : : * @param[in] error_set Sockets that have an exceptional condition (error).
# 1013 : : */
# 1014 : : void SocketHandlerConnected(const std::vector<CNode*>& nodes,
# 1015 : : const std::set<SOCKET>& recv_set,
# 1016 : : const std::set<SOCKET>& send_set,
# 1017 : : const std::set<SOCKET>& error_set);
# 1018 : :
# 1019 : : /**
# 1020 : : * Accept incoming connections, one from each read-ready listening socket.
# 1021 : : * @param[in] recv_set Sockets that are ready for read.
# 1022 : : */
# 1023 : : void SocketHandlerListening(const std::set<SOCKET>& recv_set);
# 1024 : :
# 1025 : : void ThreadSocketHandler();
# 1026 : : void ThreadDNSAddressSeed();
# 1027 : :
# 1028 : : uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
# 1029 : :
# 1030 : : CNode* FindNode(const CNetAddr& ip);
# 1031 : : CNode* FindNode(const CSubNet& subNet);
# 1032 : : CNode* FindNode(const std::string& addrName);
# 1033 : : CNode* FindNode(const CService& addr);
# 1034 : :
# 1035 : : /**
# 1036 : : * Determine whether we're already connected to a given address, in order to
# 1037 : : * avoid initiating duplicate connections.
# 1038 : : */
# 1039 : : bool AlreadyConnectedToAddress(const CAddress& addr);
# 1040 : :
# 1041 : : bool AttemptToEvictConnection();
# 1042 : : CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
# 1043 : : void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
# 1044 : :
# 1045 : : void DeleteNode(CNode* pnode);
# 1046 : :
# 1047 : : NodeId GetNewNodeId();
# 1048 : :
# 1049 : : size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
# 1050 : : void DumpAddresses();
# 1051 : :
# 1052 : : // Network stats
# 1053 : : void RecordBytesRecv(uint64_t bytes);
# 1054 : : void RecordBytesSent(uint64_t bytes);
# 1055 : :
# 1056 : : /**
# 1057 : : * Return vector of current BLOCK_RELAY peers.
# 1058 : : */
# 1059 : : std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
# 1060 : :
# 1061 : : // Whether the node should be passed out in ForEach* callbacks
# 1062 : : static bool NodeFullyConnected(const CNode* pnode);
# 1063 : :
# 1064 : : // Network usage totals
# 1065 : : mutable RecursiveMutex cs_totalBytesSent;
# 1066 : : std::atomic<uint64_t> nTotalBytesRecv{0};
# 1067 : : uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
# 1068 : :
# 1069 : : // outbound limit & stats
# 1070 : : uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent) {0};
# 1071 : : std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent) {0};
# 1072 : : uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
# 1073 : :
# 1074 : : // P2P timeout in seconds
# 1075 : : std::chrono::seconds m_peer_connect_timeout;
# 1076 : :
# 1077 : : // Whitelisted ranges. Any node connecting from these is automatically
# 1078 : : // whitelisted (as well as those connecting to whitelisted binds).
# 1079 : : std::vector<NetWhitelistPermissions> vWhitelistedRange;
# 1080 : :
# 1081 : : unsigned int nSendBufferMaxSize{0};
# 1082 : : unsigned int nReceiveFloodSize{0};
# 1083 : :
# 1084 : : std::vector<ListenSocket> vhListenSocket;
# 1085 : : std::atomic<bool> fNetworkActive{true};
# 1086 : : bool fAddressesInitialized{false};
# 1087 : : AddrMan& addrman;
# 1088 : : std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
# 1089 : : Mutex m_addr_fetches_mutex;
# 1090 : : std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
# 1091 : : mutable Mutex m_added_nodes_mutex;
# 1092 : : std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
# 1093 : : std::list<CNode*> m_nodes_disconnected;
# 1094 : : mutable RecursiveMutex m_nodes_mutex;
# 1095 : : std::atomic<NodeId> nLastNodeId{0};
# 1096 : : unsigned int nPrevNodeCount{0};
# 1097 : :
# 1098 : : /**
# 1099 : : * Cache responses to addr requests to minimize privacy leak.
# 1100 : : * Attack example: scraping addrs in real-time may allow an attacker
# 1101 : : * to infer new connections of the victim by detecting new records
# 1102 : : * with fresh timestamps (per self-announcement).
# 1103 : : */
# 1104 : : struct CachedAddrResponse {
# 1105 : : std::vector<CAddress> m_addrs_response_cache;
# 1106 : : std::chrono::microseconds m_cache_entry_expiration{0};
# 1107 : : };
# 1108 : :
# 1109 : : /**
# 1110 : : * Addr responses stored in different caches
# 1111 : : * per (network, local socket) prevent cross-network node identification.
# 1112 : : * If a node for example is multi-homed under Tor and IPv6,
# 1113 : : * a single cache (or no cache at all) would let an attacker
# 1114 : : * to easily detect that it is the same node by comparing responses.
# 1115 : : * Indexing by local socket prevents leakage when a node has multiple
# 1116 : : * listening addresses on the same network.
# 1117 : : *
# 1118 : : * The used memory equals to 1000 CAddress records (or around 40 bytes) per
# 1119 : : * distinct Network (up to 5) we have/had an inbound peer from,
# 1120 : : * resulting in at most ~196 KB. Every separate local socket may
# 1121 : : * add up to ~196 KB extra.
# 1122 : : */
# 1123 : : std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
# 1124 : :
# 1125 : : /**
# 1126 : : * Services this instance offers.
# 1127 : : *
# 1128 : : * This data is replicated in each CNode instance we create during peer
# 1129 : : * connection (in ConnectNode()) under a member also called
# 1130 : : * nLocalServices.
# 1131 : : *
# 1132 : : * This data is not marked const, but after being set it should not
# 1133 : : * change. See the note in CNode::nLocalServices documentation.
# 1134 : : *
# 1135 : : * \sa CNode::nLocalServices
# 1136 : : */
# 1137 : : ServiceFlags nLocalServices;
# 1138 : :
# 1139 : : std::unique_ptr<CSemaphore> semOutbound;
# 1140 : : std::unique_ptr<CSemaphore> semAddnode;
# 1141 : : int nMaxConnections;
# 1142 : :
# 1143 : : // How many full-relay (tx, block, addr) outbound peers we want
# 1144 : : int m_max_outbound_full_relay;
# 1145 : :
# 1146 : : // How many block-relay only outbound peers we want
# 1147 : : // We do not relay tx or addr messages with these peers
# 1148 : : int m_max_outbound_block_relay;
# 1149 : :
# 1150 : : int nMaxAddnode;
# 1151 : : int nMaxFeeler;
# 1152 : : int m_max_outbound;
# 1153 : : bool m_use_addrman_outgoing;
# 1154 : : CClientUIInterface* m_client_interface;
# 1155 : : NetEventsInterface* m_msgproc;
# 1156 : : /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
# 1157 : : BanMan* m_banman;
# 1158 : :
# 1159 : : /**
# 1160 : : * Addresses that were saved during the previous clean shutdown. We'll
# 1161 : : * attempt to make block-relay-only connections to them.
# 1162 : : */
# 1163 : : std::vector<CAddress> m_anchors;
# 1164 : :
# 1165 : : /** SipHasher seeds for deterministic randomness */
# 1166 : : const uint64_t nSeed0, nSeed1;
# 1167 : :
# 1168 : : /** flag for waking the message processor. */
# 1169 : : bool fMsgProcWake GUARDED_BY(mutexMsgProc);
# 1170 : :
# 1171 : : std::condition_variable condMsgProc;
# 1172 : : Mutex mutexMsgProc;
# 1173 : : std::atomic<bool> flagInterruptMsgProc{false};
# 1174 : :
# 1175 : : /**
# 1176 : : * This is signaled when network activity should cease.
# 1177 : : * A pointer to it is saved in `m_i2p_sam_session`, so make sure that
# 1178 : : * the lifetime of `interruptNet` is not shorter than
# 1179 : : * the lifetime of `m_i2p_sam_session`.
# 1180 : : */
# 1181 : : CThreadInterrupt interruptNet;
# 1182 : :
# 1183 : : /**
# 1184 : : * I2P SAM session.
# 1185 : : * Used to accept incoming and make outgoing I2P connections.
# 1186 : : */
# 1187 : : std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
# 1188 : :
# 1189 : : std::thread threadDNSAddressSeed;
# 1190 : : std::thread threadSocketHandler;
# 1191 : : std::thread threadOpenAddedConnections;
# 1192 : : std::thread threadOpenConnections;
# 1193 : : std::thread threadMessageHandler;
# 1194 : : std::thread threadI2PAcceptIncoming;
# 1195 : :
# 1196 : : /** flag for deciding to connect to an extra outbound peer,
# 1197 : : * in excess of m_max_outbound_full_relay
# 1198 : : * This takes the place of a feeler connection */
# 1199 : : std::atomic_bool m_try_another_outbound_peer;
# 1200 : :
# 1201 : : /** flag for initiating extra block-relay-only peer connections.
# 1202 : : * this should only be enabled after initial chain sync has occurred,
# 1203 : : * as these connections are intended to be short-lived and low-bandwidth.
# 1204 : : */
# 1205 : : std::atomic_bool m_start_extra_block_relay_peers{false};
# 1206 : :
# 1207 : : /**
# 1208 : : * A vector of -bind=<address>:<port>=onion arguments each of which is
# 1209 : : * an address and port that are designated for incoming Tor connections.
# 1210 : : */
# 1211 : : std::vector<CService> m_onion_binds;
# 1212 : :
# 1213 : : /**
# 1214 : : * RAII helper to atomically create a copy of `m_nodes` and add a reference
# 1215 : : * to each of the nodes. The nodes are released when this object is destroyed.
# 1216 : : */
# 1217 : : class NodesSnapshot
# 1218 : : {
# 1219 : : public:
# 1220 : : explicit NodesSnapshot(const CConnman& connman, bool shuffle)
# 1221 : 525515 : {
# 1222 : 525515 : {
# 1223 : 525515 : LOCK(connman.m_nodes_mutex);
# 1224 : 525515 : m_nodes_copy = connman.m_nodes;
# 1225 [ + + ]: 818232 : for (auto& node : m_nodes_copy) {
# 1226 : 818232 : node->AddRef();
# 1227 : 818232 : }
# 1228 : 525515 : }
# 1229 [ + + ]: 525515 : if (shuffle) {
# 1230 : 209464 : Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
# 1231 : 209464 : }
# 1232 : 525515 : }
# 1233 : :
# 1234 : : ~NodesSnapshot()
# 1235 : 525515 : {
# 1236 [ + + ]: 818232 : for (auto& node : m_nodes_copy) {
# 1237 : 818232 : node->Release();
# 1238 : 818232 : }
# 1239 : 525515 : }
# 1240 : :
# 1241 : : const std::vector<CNode*>& Nodes() const
# 1242 : 841545 : {
# 1243 : 841545 : return m_nodes_copy;
# 1244 : 841545 : }
# 1245 : :
# 1246 : : private:
# 1247 : : std::vector<CNode*> m_nodes_copy;
# 1248 : : };
# 1249 : :
# 1250 : : friend struct CConnmanTest;
# 1251 : : friend struct ConnmanTestMsg;
# 1252 : : };
# 1253 : :
# 1254 : : /** Dump binary message to file, with timestamp */
# 1255 : : void CaptureMessageToFile(const CAddress& addr,
# 1256 : : const std::string& msg_type,
# 1257 : : Span<const unsigned char> data,
# 1258 : : bool is_incoming);
# 1259 : :
# 1260 : : /** Defaults to `CaptureMessageToFile()`, but can be overridden by unit tests. */
# 1261 : : extern std::function<void(const CAddress& addr,
# 1262 : : const std::string& msg_type,
# 1263 : : Span<const unsigned char> data,
# 1264 : : bool is_incoming)>
# 1265 : : CaptureMessage;
# 1266 : :
# 1267 : : struct NodeEvictionCandidate
# 1268 : : {
# 1269 : : NodeId id;
# 1270 : : std::chrono::seconds m_connected;
# 1271 : : std::chrono::microseconds m_min_ping_time;
# 1272 : : std::chrono::seconds m_last_block_time;
# 1273 : : std::chrono::seconds m_last_tx_time;
# 1274 : : bool fRelevantServices;
# 1275 : : bool m_relay_txs;
# 1276 : : bool fBloomFilter;
# 1277 : : uint64_t nKeyedNetGroup;
# 1278 : : bool prefer_evict;
# 1279 : : bool m_is_local;
# 1280 : : Network m_network;
# 1281 : : };
# 1282 : :
# 1283 : : /**
# 1284 : : * Select an inbound peer to evict after filtering out (protecting) peers having
# 1285 : : * distinct, difficult-to-forge characteristics. The protection logic picks out
# 1286 : : * fixed numbers of desirable peers per various criteria, followed by (mostly)
# 1287 : : * ratios of desirable or disadvantaged peers. If any eviction candidates
# 1288 : : * remain, the selection logic chooses a peer to evict.
# 1289 : : */
# 1290 : : [[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
# 1291 : :
# 1292 : : /** Protect desirable or disadvantaged inbound peers from eviction by ratio.
# 1293 : : *
# 1294 : : * This function protects half of the peers which have been connected the
# 1295 : : * longest, to replicate the non-eviction implicit behavior and preclude attacks
# 1296 : : * that start later.
# 1297 : : *
# 1298 : : * Half of these protected spots (1/4 of the total) are reserved for the
# 1299 : : * following categories of peers, sorted by longest uptime, even if they're not
# 1300 : : * longest uptime overall:
# 1301 : : *
# 1302 : : * - onion peers connected via our tor control service
# 1303 : : *
# 1304 : : * - localhost peers, as manually configured hidden services not using
# 1305 : : * `-bind=addr[:port]=onion` will not be detected as inbound onion connections
# 1306 : : *
# 1307 : : * - I2P peers
# 1308 : : *
# 1309 : : * - CJDNS peers
# 1310 : : *
# 1311 : : * This helps protect these privacy network peers, which tend to be otherwise
# 1312 : : * disadvantaged under our eviction criteria for their higher min ping times
# 1313 : : * relative to IPv4/IPv6 peers, and favorise the diversity of peer connections.
# 1314 : : */
# 1315 : : void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates);
# 1316 : :
# 1317 : : #endif // BITCOIN_NET_H
|