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