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 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 CNetMessage(CDataStream && recv_in)291 CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {} 292 SetVersion(int nVersionIn)293 void SetVersion(int nVersionIn) 294 { 295 m_recv.SetVersion(nVersionIn); 296 } 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; ~TransportDeserializer()313 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 Reset()334 void Reset() { 335 vRecv.clear(); 336 hdrbuf.clear(); 337 hdrbuf.resize(24); 338 in_data = false; 339 nHdrPos = 0; 340 nDataPos = 0; 341 data_hash.SetNull(); 342 hasher.Reset(); 343 } 344 345 public: V1TransportDeserializer(const CChainParams & chain_params,const NodeId node_id,int nTypeIn,int nVersionIn)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 { 352 Reset(); 353 } 354 Complete()355 bool Complete() const override 356 { 357 if (!in_data) 358 return false; 359 return (hdr.nMessageSize == nDataPos); 360 } SetVersion(int nVersionIn)361 void SetVersion(int nVersionIn) override 362 { 363 hdrbuf.SetVersion(nVersionIn); 364 vRecv.SetVersion(nVersionIn); 365 } Read(Span<const uint8_t> & msg_bytes)366 int Read(Span<const uint8_t>& msg_bytes) override 367 { 368 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes); 369 if (ret < 0) { 370 Reset(); 371 } else { 372 msg_bytes = msg_bytes.subspan(ret); 373 } 374 return ret; 375 } 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; ~TransportSerializer()385 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 */ GUARDED_BY(cs_vSend)407 size_t nSendSize GUARDED_BY(cs_vSend){0}; 408 /** Offset inside the first vSendMsg already sent */ GUARDED_BY(cs_vSend)409 size_t nSendOffset GUARDED_BY(cs_vSend){0}; GUARDED_BY(cs_vSend)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 GUARDED_BY(cs_vRecv)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 */ GUARDED_BY(cs_SubVer)441 std::string cleanSubVer GUARDED_BY(cs_SubVer){}; 442 bool m_prefer_evict{false}; // This peer is preferred for eviction. HasPermission(NetPermissionFlags permission)443 bool HasPermission(NetPermissionFlags permission) const { 444 return NetPermissions::HasFlag(m_permissionFlags, permission); 445 } 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 IsOutboundOrBlockRelayConn()460 bool IsOutboundOrBlockRelayConn() const { 461 switch (m_conn_type) { 462 case ConnectionType::OUTBOUND_FULL_RELAY: 463 case ConnectionType::BLOCK_RELAY: 464 return true; 465 case ConnectionType::INBOUND: 466 case ConnectionType::MANUAL: 467 case ConnectionType::ADDR_FETCH: 468 case ConnectionType::FEELER: 469 return false; 470 } // no default case, so the compiler can warn about missing cases 471 472 assert(false); 473 } 474 IsFullOutboundConn()475 bool IsFullOutboundConn() const { 476 return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY; 477 } 478 IsManualConn()479 bool IsManualConn() const { 480 return m_conn_type == ConnectionType::MANUAL; 481 } 482 IsBlockOnlyConn()483 bool IsBlockOnlyConn() const { 484 return m_conn_type == ConnectionType::BLOCK_RELAY; 485 } 486 IsFeelerConn()487 bool IsFeelerConn() const { 488 return m_conn_type == ConnectionType::FEELER; 489 } 490 IsAddrFetchConn()491 bool IsAddrFetchConn() const { 492 return m_conn_type == ConnectionType::ADDR_FETCH; 493 } 494 IsInboundConn()495 bool IsInboundConn() const { 496 return m_conn_type == ConnectionType::INBOUND; 497 } 498 ExpectServicesFromConn()499 bool ExpectServicesFromConn() const { 500 switch (m_conn_type) { 501 case ConnectionType::INBOUND: 502 case ConnectionType::MANUAL: 503 case ConnectionType::FEELER: 504 return false; 505 case ConnectionType::OUTBOUND_FULL_RELAY: 506 case ConnectionType::BLOCK_RELAY: 507 case ConnectionType::ADDR_FETCH: 508 return true; 509 } // no default case, so the compiler can warn about missing cases 510 511 assert(false); 512 } 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. GUARDED_BYTxRelay537 bool fRelayTxes GUARDED_BY(cs_filter){false}; PT_GUARDED_BYTxRelay538 std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr}; 539 540 mutable RecursiveMutex cs_tx_inventory; GUARDED_BYTxRelay541 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 GUARDED_BYTxRelay546 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 GetId()585 NodeId GetId() const { 586 return id; 587 } 588 GetLocalNonce()589 uint64_t GetLocalNonce() const { 590 return nLocalHostNonce; 591 } 592 GetRefCount()593 int GetRefCount() const 594 { 595 assert(nRefCount >= 0); 596 return nRefCount; 597 } 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 SetCommonVersion(int greatest_common_version)610 void SetCommonVersion(int greatest_common_version) 611 { 612 Assume(m_greatest_common_version == INIT_PROTO_VERSION); 613 m_greatest_common_version = greatest_common_version; 614 } GetCommonVersion()615 int GetCommonVersion() const 616 { 617 return m_greatest_common_version; 618 } 619 620 CService GetAddrLocal() const; 621 //! May not be called more than once 622 void SetAddrLocal(const CService& addrLocalIn); 623 AddRef()624 CNode* AddRef() 625 { 626 nRefCount++; 627 return this; 628 } 629 Release()630 void Release() 631 { 632 nRefCount--; 633 } 634 AddKnownTx(const uint256 & hash)635 void AddKnownTx(const uint256& hash) 636 { 637 if (m_tx_relay != nullptr) { 638 LOCK(m_tx_relay->cs_tx_inventory); 639 m_tx_relay->filterInventoryKnown.insert(hash); 640 } 641 } 642 PushTxInventory(const uint256 & hash)643 void PushTxInventory(const uint256& hash) 644 { 645 if (m_tx_relay == nullptr) return; 646 LOCK(m_tx_relay->cs_tx_inventory); 647 if (!m_tx_relay->filterInventoryKnown.contains(hash)) { 648 m_tx_relay->setInventoryTxToSend.insert(hash); 649 } 650 } 651 652 void CloseSocketDisconnect(); 653 654 void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap); 655 GetLocalServices()656 ServiceFlags GetLocalServices() const 657 { 658 return nLocalServices; 659 } 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 ConnectionTypeAsString()665 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. */ PongReceived(std::chrono::microseconds ping_time)668 void PongReceived(std::chrono::microseconds ping_time) { 669 m_last_ping_time = ping_time; 670 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time); 671 } 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 /// True if the user did not specify -bind= or -whitebind= and thus 772 /// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6). 773 bool bind_on_any; 774 bool m_use_addrman_outgoing = true; 775 std::vector<std::string> m_specified_outgoing; 776 std::vector<std::string> m_added_nodes; 777 std::vector<bool> m_asmap; 778 bool m_i2p_accept_incoming; 779 }; 780 Init(const Options & connOptions)781 void Init(const Options& connOptions) { 782 nLocalServices = connOptions.nLocalServices; 783 nMaxConnections = connOptions.nMaxConnections; 784 m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections); 785 m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay; 786 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing; 787 nMaxAddnode = connOptions.nMaxAddnode; 788 nMaxFeeler = connOptions.nMaxFeeler; 789 m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler; 790 clientInterface = connOptions.uiInterface; 791 m_banman = connOptions.m_banman; 792 m_msgproc = connOptions.m_msgproc; 793 nSendBufferMaxSize = connOptions.nSendBufferMaxSize; 794 nReceiveFloodSize = connOptions.nReceiveFloodSize; 795 m_peer_connect_timeout = connOptions.m_peer_connect_timeout; 796 { 797 LOCK(cs_totalBytesSent); 798 nMaxOutboundLimit = connOptions.nMaxOutboundLimit; 799 } 800 vWhitelistedRange = connOptions.vWhitelistedRange; 801 { 802 LOCK(cs_vAddedNodes); 803 vAddedNodes = connOptions.m_added_nodes; 804 } 805 m_onion_binds = connOptions.onion_binds; 806 } 807 808 CConnman(uint64_t seed0, uint64_t seed1, CAddrMan& addrman, bool network_active = true); 809 ~CConnman(); 810 bool Start(CScheduler& scheduler, const Options& options); 811 812 void StopThreads(); 813 void StopNodes(); Stop()814 void Stop() 815 { 816 StopThreads(); 817 StopNodes(); 818 }; 819 820 void Interrupt(); GetNetworkActive()821 bool GetNetworkActive() const { return fNetworkActive; }; GetUseAddrmanOutgoing()822 bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; }; 823 void SetNetworkActive(bool active); 824 void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type); 825 bool CheckIncomingNonce(uint64_t nonce); 826 827 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func); 828 829 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg); 830 831 using NodeFn = std::function<void(CNode*)>; ForEachNode(const NodeFn & func)832 void ForEachNode(const NodeFn& func) 833 { 834 LOCK(cs_vNodes); 835 for (auto&& node : vNodes) { 836 if (NodeFullyConnected(node)) 837 func(node); 838 } 839 }; 840 ForEachNode(const NodeFn & func)841 void ForEachNode(const NodeFn& func) const 842 { 843 LOCK(cs_vNodes); 844 for (auto&& node : vNodes) { 845 if (NodeFullyConnected(node)) 846 func(node); 847 } 848 }; 849 850 // Addrman functions 851 /** 852 * Return all or many randomly selected addresses, optionally by network. 853 * 854 * @param[in] max_addresses Maximum number of addresses to return (0 = all). 855 * @param[in] max_pct Maximum percentage of addresses to return (0 = all). 856 * @param[in] network Select only addresses of this network (nullopt = all). 857 */ 858 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const; 859 /** 860 * Cache is used to minimize topology leaks, so it should 861 * be used for all non-trusted calls, for example, p2p. 862 * A non-malicious call (from RPC or a peer with addr permission) should 863 * call the function without a parameter to avoid using the cache. 864 */ 865 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct); 866 867 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding 868 // a peer that is better than all our current peers. 869 void SetTryNewOutboundPeer(bool flag); 870 bool GetTryNewOutboundPeer() const; 871 StartExtraBlockRelayPeers()872 void StartExtraBlockRelayPeers() { 873 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n"); 874 m_start_extra_block_relay_peers = true; 875 } 876 877 // Return the number of outbound peers we have in excess of our target (eg, 878 // if we previously called SetTryNewOutboundPeer(true), and have since set 879 // to false, we may have extra peers that we wish to disconnect). This may 880 // return a value less than (num_outbound_connections - num_outbound_slots) 881 // in cases where some outbound connections are not yet fully connected, or 882 // not yet fully disconnected. 883 int GetExtraFullOutboundCount() const; 884 // Count the number of block-relay-only peers we have over our limit. 885 int GetExtraBlockRelayCount() const; 886 887 bool AddNode(const std::string& node); 888 bool RemoveAddedNode(const std::string& node); 889 std::vector<AddedNodeInfo> GetAddedNodeInfo() const; 890 891 /** 892 * Attempts to open a connection. Currently only used from tests. 893 * 894 * @param[in] address Address of node to try connecting to 895 * @param[in] conn_type ConnectionType::OUTBOUND or ConnectionType::BLOCK_RELAY 896 * or ConnectionType::ADDR_FETCH 897 * @return bool Returns false if there are no available 898 * slots for this connection: 899 * - conn_type not a supported ConnectionType 900 * - Max total outbound connection capacity filled 901 * - Max connection capacity for type is filled 902 */ 903 bool AddConnection(const std::string& address, ConnectionType conn_type); 904 905 size_t GetNodeCount(ConnectionDirection) const; 906 void GetNodeStats(std::vector<CNodeStats>& vstats) const; 907 bool DisconnectNode(const std::string& node); 908 bool DisconnectNode(const CSubNet& subnet); 909 bool DisconnectNode(const CNetAddr& addr); 910 bool DisconnectNode(NodeId id); 911 912 //! Used to convey which local services we are offering peers during node 913 //! connection. 914 //! 915 //! The data returned by this is used in CNode construction, 916 //! which is used to advertise which services we are offering 917 //! that peer during `net_processing.cpp:PushNodeVersion()`. 918 ServiceFlags GetLocalServices() const; 919 920 uint64_t GetMaxOutboundTarget() const; 921 std::chrono::seconds GetMaxOutboundTimeframe() const; 922 923 //! check if the outbound target is reached 924 //! if param historicalBlockServingLimit is set true, the function will 925 //! response true if the limit for serving historical blocks has been reached 926 bool OutboundTargetReached(bool historicalBlockServingLimit) const; 927 928 //! response the bytes left in the current max outbound cycle 929 //! in case of no limit, it will always response 0 930 uint64_t GetOutboundTargetBytesLeft() const; 931 932 //! returns the time left in the current max outbound cycle 933 //! in case of no limit, it will always return 0 934 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const; 935 936 uint64_t GetTotalBytesRecv() const; 937 uint64_t GetTotalBytesSent() const; 938 939 /** Get a unique deterministic randomizer. */ 940 CSipHasher GetDeterministicRandomizer(uint64_t id) const; 941 942 unsigned int GetReceiveFloodSize() const; 943 944 void WakeMessageHandler(); 945 946 /** Attempts to obfuscate tx time through exponentially distributed emitting. 947 Works assuming that a single interval is used. 948 Variable intervals will result in privacy decrease. 949 */ 950 std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval); 951 SetAsmap(std::vector<bool> asmap)952 void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); } 953 954 /** Return true if we should disconnect the peer for failing an inactivity check. */ 955 bool ShouldRunInactivityChecks(const CNode& node, std::optional<int64_t> now=std::nullopt) const; 956 957 private: 958 struct ListenSocket { 959 public: 960 SOCKET socket; AddSocketPermissionFlagsListenSocket961 inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); } ListenSocketListenSocket962 ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {} 963 private: 964 NetPermissionFlags m_permissions; 965 }; 966 967 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions); 968 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions); 969 bool InitBinds(const Options& options); 970 971 void ThreadOpenAddedConnections(); 972 void AddAddrFetch(const std::string& strDest); 973 void ProcessAddrFetch(); 974 void ThreadOpenConnections(std::vector<std::string> connect); 975 void ThreadMessageHandler(); 976 void ThreadI2PAcceptIncoming(); 977 void AcceptConnection(const ListenSocket& hListenSocket); 978 979 /** 980 * Create a `CNode` object from a socket that has just been accepted and add the node to 981 * the `vNodes` member. 982 * @param[in] hSocket Connected socket to communicate with the peer. 983 * @param[in] permissionFlags The peer's permissions. 984 * @param[in] addr_bind The address and port at our side of the connection. 985 * @param[in] addr The address and port at the peer's side of the connection. 986 */ 987 void CreateNodeFromAcceptedSocket(SOCKET hSocket, 988 NetPermissionFlags permissionFlags, 989 const CAddress& addr_bind, 990 const CAddress& addr); 991 992 void DisconnectNodes(); 993 void NotifyNumConnectionsChanged(); 994 /** Return true if the peer is inactive and should be disconnected. */ 995 bool InactivityCheck(const CNode& node) const; 996 bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set); 997 void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set); 998 void SocketHandler(); 999 void ThreadSocketHandler(); 1000 void ThreadDNSAddressSeed(); 1001 1002 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const; 1003 1004 CNode* FindNode(const CNetAddr& ip); 1005 CNode* FindNode(const CSubNet& subNet); 1006 CNode* FindNode(const std::string& addrName); 1007 CNode* FindNode(const CService& addr); 1008 1009 /** 1010 * Determine whether we're already connected to a given address, in order to 1011 * avoid initiating duplicate connections. 1012 */ 1013 bool AlreadyConnectedToAddress(const CAddress& addr); 1014 1015 bool AttemptToEvictConnection(); 1016 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type); 1017 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const; 1018 1019 void DeleteNode(CNode* pnode); 1020 1021 NodeId GetNewNodeId(); 1022 1023 size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend); 1024 void DumpAddresses(); 1025 1026 // Network stats 1027 void RecordBytesRecv(uint64_t bytes); 1028 void RecordBytesSent(uint64_t bytes); 1029 1030 /** 1031 * Return vector of current BLOCK_RELAY peers. 1032 */ 1033 std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const; 1034 1035 // Whether the node should be passed out in ForEach* callbacks 1036 static bool NodeFullyConnected(const CNode* pnode); 1037 1038 // Network usage totals 1039 mutable RecursiveMutex cs_totalBytesRecv; 1040 mutable RecursiveMutex cs_totalBytesSent; GUARDED_BY(cs_totalBytesRecv)1041 uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0}; GUARDED_BY(cs_totalBytesSent)1042 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0}; 1043 1044 // outbound limit & stats GUARDED_BY(cs_totalBytesSent)1045 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent) {0}; GUARDED_BY(cs_totalBytesSent)1046 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent) {0}; 1047 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent); 1048 1049 // P2P timeout in seconds 1050 int64_t m_peer_connect_timeout; 1051 1052 // Whitelisted ranges. Any node connecting from these is automatically 1053 // whitelisted (as well as those connecting to whitelisted binds). 1054 std::vector<NetWhitelistPermissions> vWhitelistedRange; 1055 1056 unsigned int nSendBufferMaxSize{0}; 1057 unsigned int nReceiveFloodSize{0}; 1058 1059 std::vector<ListenSocket> vhListenSocket; 1060 std::atomic<bool> fNetworkActive{true}; 1061 bool fAddressesInitialized{false}; 1062 CAddrMan& addrman; 1063 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex); 1064 RecursiveMutex m_addr_fetches_mutex; 1065 std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes); 1066 mutable RecursiveMutex cs_vAddedNodes; 1067 std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes); 1068 std::list<CNode*> vNodesDisconnected; 1069 mutable RecursiveMutex cs_vNodes; 1070 std::atomic<NodeId> nLastNodeId{0}; 1071 unsigned int nPrevNodeCount{0}; 1072 1073 /** 1074 * Cache responses to addr requests to minimize privacy leak. 1075 * Attack example: scraping addrs in real-time may allow an attacker 1076 * to infer new connections of the victim by detecting new records 1077 * with fresh timestamps (per self-announcement). 1078 */ 1079 struct CachedAddrResponse { 1080 std::vector<CAddress> m_addrs_response_cache; 1081 std::chrono::microseconds m_cache_entry_expiration{0}; 1082 }; 1083 1084 /** 1085 * Addr responses stored in different caches 1086 * per (network, local socket) prevent cross-network node identification. 1087 * If a node for example is multi-homed under Tor and IPv6, 1088 * a single cache (or no cache at all) would let an attacker 1089 * to easily detect that it is the same node by comparing responses. 1090 * Indexing by local socket prevents leakage when a node has multiple 1091 * listening addresses on the same network. 1092 * 1093 * The used memory equals to 1000 CAddress records (or around 40 bytes) per 1094 * distinct Network (up to 5) we have/had an inbound peer from, 1095 * resulting in at most ~196 KB. Every separate local socket may 1096 * add up to ~196 KB extra. 1097 */ 1098 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches; 1099 1100 /** 1101 * Services this instance offers. 1102 * 1103 * This data is replicated in each CNode instance we create during peer 1104 * connection (in ConnectNode()) under a member also called 1105 * nLocalServices. 1106 * 1107 * This data is not marked const, but after being set it should not 1108 * change. See the note in CNode::nLocalServices documentation. 1109 * 1110 * \sa CNode::nLocalServices 1111 */ 1112 ServiceFlags nLocalServices; 1113 1114 std::unique_ptr<CSemaphore> semOutbound; 1115 std::unique_ptr<CSemaphore> semAddnode; 1116 int nMaxConnections; 1117 1118 // How many full-relay (tx, block, addr) outbound peers we want 1119 int m_max_outbound_full_relay; 1120 1121 // How many block-relay only outbound peers we want 1122 // We do not relay tx or addr messages with these peers 1123 int m_max_outbound_block_relay; 1124 1125 int nMaxAddnode; 1126 int nMaxFeeler; 1127 int m_max_outbound; 1128 bool m_use_addrman_outgoing; 1129 CClientUIInterface* clientInterface; 1130 NetEventsInterface* m_msgproc; 1131 /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */ 1132 BanMan* m_banman; 1133 1134 /** 1135 * Addresses that were saved during the previous clean shutdown. We'll 1136 * attempt to make block-relay-only connections to them. 1137 */ 1138 std::vector<CAddress> m_anchors; 1139 1140 /** SipHasher seeds for deterministic randomness */ 1141 const uint64_t nSeed0, nSeed1; 1142 1143 /** flag for waking the message processor. */ 1144 bool fMsgProcWake GUARDED_BY(mutexMsgProc); 1145 1146 std::condition_variable condMsgProc; 1147 Mutex mutexMsgProc; 1148 std::atomic<bool> flagInterruptMsgProc{false}; 1149 1150 /** 1151 * This is signaled when network activity should cease. 1152 * A pointer to it is saved in `m_i2p_sam_session`, so make sure that 1153 * the lifetime of `interruptNet` is not shorter than 1154 * the lifetime of `m_i2p_sam_session`. 1155 */ 1156 CThreadInterrupt interruptNet; 1157 1158 /** 1159 * I2P SAM session. 1160 * Used to accept incoming and make outgoing I2P connections. 1161 */ 1162 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session; 1163 1164 std::thread threadDNSAddressSeed; 1165 std::thread threadSocketHandler; 1166 std::thread threadOpenAddedConnections; 1167 std::thread threadOpenConnections; 1168 std::thread threadMessageHandler; 1169 std::thread threadI2PAcceptIncoming; 1170 1171 /** flag for deciding to connect to an extra outbound peer, 1172 * in excess of m_max_outbound_full_relay 1173 * This takes the place of a feeler connection */ 1174 std::atomic_bool m_try_another_outbound_peer; 1175 1176 /** flag for initiating extra block-relay-only peer connections. 1177 * this should only be enabled after initial chain sync has occurred, 1178 * as these connections are intended to be short-lived and low-bandwidth. 1179 */ 1180 std::atomic_bool m_start_extra_block_relay_peers{false}; 1181 1182 std::atomic<std::chrono::microseconds> m_next_send_inv_to_incoming{0us}; 1183 1184 /** 1185 * A vector of -bind=<address>:<port>=onion arguments each of which is 1186 * an address and port that are designated for incoming Tor connections. 1187 */ 1188 std::vector<CService> m_onion_binds; 1189 1190 friend struct CConnmanTest; 1191 friend struct ConnmanTestMsg; 1192 }; 1193 1194 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */ 1195 std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval); 1196 1197 /** Dump binary message to file, with timestamp */ 1198 void CaptureMessage(const CAddress& addr, const std::string& msg_type, const Span<const unsigned char>& data, bool is_incoming); 1199 1200 struct NodeEvictionCandidate 1201 { 1202 NodeId id; 1203 int64_t nTimeConnected; 1204 std::chrono::microseconds m_min_ping_time; 1205 int64_t nLastBlockTime; 1206 int64_t nLastTXTime; 1207 bool fRelevantServices; 1208 bool fRelayTxes; 1209 bool fBloomFilter; 1210 uint64_t nKeyedNetGroup; 1211 bool prefer_evict; 1212 bool m_is_local; 1213 Network m_network; 1214 }; 1215 1216 /** 1217 * Select an inbound peer to evict after filtering out (protecting) peers having 1218 * distinct, difficult-to-forge characteristics. The protection logic picks out 1219 * fixed numbers of desirable peers per various criteria, followed by (mostly) 1220 * ratios of desirable or disadvantaged peers. If any eviction candidates 1221 * remain, the selection logic chooses a peer to evict. 1222 */ 1223 [[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates); 1224 1225 /** Protect desirable or disadvantaged inbound peers from eviction by ratio. 1226 * 1227 * This function protects half of the peers which have been connected the 1228 * longest, to replicate the non-eviction implicit behavior and preclude attacks 1229 * that start later. 1230 * 1231 * Half of these protected spots (1/4 of the total) are reserved for the 1232 * following categories of peers, sorted by longest uptime, even if they're not 1233 * longest uptime overall: 1234 * 1235 * - onion peers connected via our tor control service 1236 * 1237 * - localhost peers, as manually configured hidden services not using 1238 * `-bind=addr[:port]=onion` will not be detected as inbound onion connections 1239 * 1240 * - I2P peers 1241 * 1242 * This helps protect these privacy network peers, which tend to be otherwise 1243 * disadvantaged under our eviction criteria for their higher min ping times 1244 * relative to IPv4/IPv6 peers, and favorise the diversity of peer connections. 1245 */ 1246 void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates); 1247 1248 #endif // BITCOIN_NET_H 1249