net_processing.cpp raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-2022 The Limenka 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  #include <net_processing.h>
   7  
   8  #include <addrman.h>
   9  #include <banman.h>
  10  #include <blockencodings.h>
  11  #include <blockfilter.h>
  12  #include <chainparams.h>
  13  #include <common/args.h>
  14  #include <consensus/amount.h>
  15  #include <consensus/validation.h>
  16  #include <deploymentstatus.h>
  17  #include <hash.h>
  18  #include <headerssync.h>
  19  #include <index/blockfilterindex.h>
  20  #include <kernel/chain.h>
  21  #include <kernel/mempool_entry.h>
  22  #include <logging.h>
  23  #include <merkleblock.h>
  24  #include <netbase.h>
  25  #include <netmessagemaker.h>
  26  #include <node/blockstorage.h>
  27  #include <node/timeoffsets.h>
  28  #include <node/txdownloadman.h>
  29  #include <node/txreconciliation.h>
  30  #include <node/warnings.h>
  31  #include <policy/fees.h>
  32  #include <policy/policy.h>
  33  #include <policy/settings.h>
  34  #include <primitives/block.h>
  35  #include <primitives/transaction.h>
  36  #include <random.h>
  37  #include <scheduler.h>
  38  #include <streams.h>
  39  #include <sync.h>
  40  #include <tinyformat.h>
  41  #include <txmempool.h>
  42  #include <txorphanage.h>
  43  #include <txrequest.h>
  44  #include <util/check.h>
  45  #include <util/strencodings.h>
  46  #include <util/time.h>
  47  #include <util/trace.h>
  48  #include <validation.h>
  49  
  50  #include <algorithm>
  51  #include <atomic>
  52  #include <future>
  53  #include <memory>
  54  #include <optional>
  55  #include <ranges>
  56  #include <typeinfo>
  57  #include <utility>
  58  
  59  using namespace util::hex_literals;
  60  
  61  TRACEPOINT_SEMAPHORE(net, inbound_message);
  62  TRACEPOINT_SEMAPHORE(net, misbehaving_connection);
  63  
  64  /** Headers download timeout.
  65   *  Timeout = base + per_header * (expected number of headers) */
  66  static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min;
  67  static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;
  68  /** How long to wait for a peer to respond to a getheaders request */
  69  static constexpr auto HEADERS_RESPONSE_TIME{2min};
  70  /** Protect at least this many outbound peers from disconnection due to slow/
  71   * behind headers chain.
  72   */
  73  static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
  74  /** Timeout for (unprotected) outbound peers to sync to our chainwork */
  75  static constexpr auto CHAIN_SYNC_TIMEOUT{20min};
  76  /** How frequently to check for stale tips */
  77  static constexpr auto STALE_CHECK_INTERVAL{10min};
  78  /** How frequently to check for extra outbound peers and disconnect */
  79  static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};
  80  /** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */
  81  static constexpr auto MINIMUM_CONNECT_TIME{30s};
  82  /** SHA256("main address relay")[0:8] */
  83  static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
  84  /// Age after which a stale block will no longer be served if requested as
  85  /// protection against fingerprinting. Set to one month, denominated in seconds.
  86  static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
  87  /// Age after which a block is considered historical for purposes of rate
  88  /// limiting block relay. Set to one week, denominated in seconds.
  89  static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
  90  /** Time between pings automatically sent out for latency probing and keepalive */
  91  static constexpr auto PING_INTERVAL{2min};
  92  /** The maximum number of entries in a locator */
  93  static const unsigned int MAX_LOCATOR_SZ = 101;
  94  /** The maximum number of entries in an 'inv' protocol message */
  95  static const unsigned int MAX_INV_SZ = 50000;
  96  /** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */
  97  static const unsigned int MAX_GETDATA_SZ = 1000;
  98  /** Number of blocks that can be requested at any given time from a single peer. */
  99  static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
 100  /** Default time during which a peer must stall block download progress before being disconnected.
 101   * the actual timeout is increased temporarily if peers are disconnected for hitting the timeout */
 102  static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT{2s};
 103  /** Maximum timeout for stalling block download. */
 104  static constexpr auto BLOCK_STALLING_TIMEOUT_MAX{64s};
 105  /** Maximum depth of blocks we're willing to serve as compact blocks to peers
 106   *  when requested. For older blocks, a regular BLOCK response will be sent. */
 107  static const int MAX_CMPCTBLOCK_DEPTH = 5;
 108  /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */
 109  static const int MAX_BLOCKTXN_DEPTH = 10;
 110  static_assert(MAX_BLOCKTXN_DEPTH <= MIN_BLOCKS_TO_KEEP, "MAX_BLOCKTXN_DEPTH too high");
 111  /** Size of the "block download window": how far ahead of our current height do we fetch?
 112   *  Larger windows tolerate larger download speed differences between peer, but increase the potential
 113   *  degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably
 114   *  want to make this a per-peer adaptive value at some point. */
 115  static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
 116  /** Block download timeout base, expressed in multiples of the block interval (i.e. 10 min) */
 117  static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1;
 118  /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */
 119  static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5;
 120  /** Maximum number of headers to announce when relaying blocks with headers message.*/
 121  static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
 122  /** Minimum blocks required to signal NODE_NETWORK_LIMITED */
 123  static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
 124  /** Window, in blocks, for connecting to NODE_NETWORK_LIMITED peers */
 125  static const unsigned int NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS = 144;
 126  /** Average delay between local address broadcasts */
 127  static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h};
 128  /** Average delay between peer address broadcasts */
 129  static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s};
 130  /** Delay between rotating the peers we relay a particular address to */
 131  static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h};
 132  /** Average delay between trickled inventory transmissions for inbound peers.
 133   *  Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */
 134  static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s};
 135  /** Average delay between trickled inventory transmissions for outbound peers.
 136   *  Use a smaller delay as there is less privacy concern for them.
 137   *  Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */
 138  static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s};
 139  /** Maximum rate of inventory items to send per second.
 140   *  Limits the impact of low-fee transaction floods. */
 141  static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND{14};
 142  /** Target number of tx inventory items to send per transmission. */
 143  static constexpr unsigned int INVENTORY_BROADCAST_TARGET = INVENTORY_BROADCAST_PER_SECOND * count_seconds(INBOUND_INVENTORY_BROADCAST_INTERVAL);
 144  /** Maximum number of inventory items to send per transmission. */
 145  static constexpr unsigned int INVENTORY_BROADCAST_MAX = 1000;
 146  static_assert(INVENTORY_BROADCAST_MAX >= INVENTORY_BROADCAST_TARGET, "INVENTORY_BROADCAST_MAX too low");
 147  static_assert(INVENTORY_BROADCAST_MAX <= node::MAX_PEER_TX_ANNOUNCEMENTS, "INVENTORY_BROADCAST_MAX too high");
 148  /** Average delay between feefilter broadcasts in seconds. */
 149  static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min};
 150  /** Maximum feefilter broadcast delay after significant change. */
 151  static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min};
 152  /** Maximum number of compact filters that may be requested with one getcfilters. See BIP 157. */
 153  static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
 154  /** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */
 155  static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;
 156  /** the maximum percentage of addresses from our addrman to return in response to a getaddr message. */
 157  static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
 158  /** The maximum number of address records permitted in an ADDR message. */
 159  static constexpr size_t MAX_ADDR_TO_SEND{1000};
 160  /** The maximum rate of address records we're willing to process on average. Can be bypassed using
 161   *  the NetPermissionFlags::Addr permission. */
 162  static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
 163  /** The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND
 164   *  based increments won't go above this, but the MAX_ADDR_TO_SEND increment following GETADDR
 165   *  is exempt from this limit). */
 166  static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND};
 167  /** The compactblocks version we support. See BIP 152. */
 168  static constexpr uint64_t CMPCTBLOCKS_VERSION{2};
 169  
 170  // Internal stuff
 171  namespace {
 172  /** Blocks that are in flight, and that are in the queue to be downloaded. */
 173  struct QueuedBlock {
 174      /** BlockIndex. We must have this since we only request blocks when we've already validated the header. */
 175      const CBlockIndex* pindex;
 176      /** Optional, used for CMPCTBLOCK downloads */
 177      std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
 178  };
 179  
 180  /**
 181   * Data structure for an individual peer. This struct is not protected by
 182   * cs_main since it does not contain validation-critical data.
 183   *
 184   * Memory is owned by shared pointers and this object is destructed when
 185   * the refcount drops to zero.
 186   *
 187   * Mutexes inside this struct must not be held when locking m_peer_mutex.
 188   *
 189   * TODO: move most members from CNodeState to this structure.
 190   * TODO: move remaining application-layer data members from CNode to this structure.
 191   */
 192  struct Peer {
 193      /** Same id as the CNode object for this peer */
 194      const NodeId m_id{0};
 195  
 196      /** Services we offered to this peer.
 197       *
 198       *  This is supplied by CConnman during peer initialization. It's const
 199       *  because there is no protocol defined for renegotiating services
 200       *  initially offered to a peer. The set of local services we offer should
 201       *  not change after initialization.
 202       *
 203       *  An interesting example of this is NODE_NETWORK and initial block
 204       *  download: a node which starts up from scratch doesn't have any blocks
 205       *  to serve, but still advertises NODE_NETWORK because it will eventually
 206       *  fulfill this role after IBD completes. P2P code is written in such a
 207       *  way that it can gracefully handle peers who don't make good on their
 208       *  service advertisements. */
 209      const ServiceFlags m_our_services;
 210      /** Services this peer offered to us. */
 211      std::atomic<ServiceFlags> m_their_services{NODE_NONE};
 212  
 213      //! Whether this peer is an inbound connection
 214      const bool m_is_inbound;
 215  
 216      /** Protects misbehavior data members */
 217      Mutex m_misbehavior_mutex;
 218      /** Whether this peer should be disconnected and marked as discouraged (unless it has NetPermissionFlags::NoBan permission). */
 219      bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false};
 220  
 221      /** Protects block inventory data members */
 222      Mutex m_block_inv_mutex;
 223      /** List of blocks that we'll announce via an `inv` message.
 224       * There is no final sorting before sending, as they are always sent
 225       * immediately and in the order requested. */
 226      std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex);
 227      /** Unfiltered list of blocks that we'd like to announce via a `headers`
 228       * message. If we can't announce via a `headers` message, we'll fall back to
 229       * announcing via `inv`. */
 230      std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex);
 231      /** The final block hash that we sent in an `inv` message to this peer.
 232       * When the peer requests this block, we send an `inv` message to trigger
 233       * the peer to request the next sequence of block hashes.
 234       * Most peers use headers-first syncing, which doesn't use this mechanism */
 235      uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {};
 236  
 237      /** Set to true once initial VERSION message was sent (only relevant for outbound peers). */
 238      bool m_outbound_version_message_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
 239  
 240      /** This peer's reported block height when we connected */
 241      std::atomic<int> m_starting_height{-1};
 242  
 243      /** The pong reply we're expecting, or 0 if no pong expected. */
 244      std::atomic<uint64_t> m_ping_nonce_sent{0};
 245      /** When the last ping was sent, or 0 if no ping was ever sent */
 246      std::atomic<std::chrono::microseconds> m_ping_start{0us};
 247      /** Whether a ping has been requested by the user */
 248      std::atomic<bool> m_ping_queued{false};
 249  
 250      /** Whether this peer relays txs via wtxid */
 251      std::atomic<bool> m_wtxid_relay{false};
 252      /** The feerate in the most recent BIP133 `feefilter` message sent to the peer.
 253       *  It is *not* a p2p protocol violation for the peer to send us
 254       *  transactions with a lower fee rate than this. See BIP133. */
 255      CAmount m_fee_filter_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0};
 256      /** Timestamp after which we will send the next BIP133 `feefilter` message
 257        * to the peer. */
 258      std::chrono::microseconds m_next_send_feefilter GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0};
 259  
 260      struct TxRelay {
 261          mutable RecursiveMutex m_bloom_filter_mutex;
 262          /** Whether we relay transactions to this peer. */
 263          bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false};
 264          /** A bloom filter for which transactions to announce to the peer. See BIP37. */
 265          std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr};
 266  
 267          mutable RecursiveMutex m_tx_inventory_mutex;
 268          /** A filter of all the (w)txids that the peer has announced to
 269           *  us or we have announced to the peer. We use this to avoid announcing
 270           *  the same (w)txid to a peer that already has the transaction. */
 271          CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
 272          /** Set of transaction ids we still have to announce (txid for
 273           *  non-wtxid-relay peers, wtxid for wtxid-relay peers). We use the
 274           *  mempool to sort transactions in dependency order before relay, so
 275           *  this does not have to be sorted. */
 276          std::set<uint256> m_tx_inventory_to_send GUARDED_BY(m_tx_inventory_mutex);
 277          /** Whether the peer has requested us to send our complete mempool. Only
 278           *  permitted if the peer has NetPermissionFlags::Mempool or we advertise
 279           *  NODE_BLOOM. See BIP35. */
 280          bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};
 281          /** The next time after which we will send an `inv` message containing
 282           *  transaction announcements to this peer. */
 283          std::chrono::microseconds m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){0};
 284          /** The mempool sequence num at which we sent the last `inv` message to this peer.
 285           *  Can relay txs with lower sequence numbers than this (see CTxMempool::info_for_relay). */
 286          uint64_t m_last_inv_sequence GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1};
 287  
 288          /** Minimum fee rate with which to filter transaction announcements to this node. See BIP133. */
 289          std::atomic<CAmount> m_fee_filter_received{0};
 290      };
 291  
 292      /* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */
 293      TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
 294      {
 295          LOCK(m_tx_relay_mutex);
 296          Assume(!m_tx_relay);
 297          m_tx_relay = std::make_unique<Peer::TxRelay>();
 298          return m_tx_relay.get();
 299      };
 300  
 301      TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
 302      {
 303          return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get());
 304      };
 305  
 306      /** A vector of addresses to send to the peer, limited to MAX_ADDR_TO_SEND. */
 307      std::vector<CAddress> m_addrs_to_send GUARDED_BY(NetEventsInterface::g_msgproc_mutex);
 308      /** Probabilistic filter to track recent addr messages relayed with this
 309       *  peer. Used to avoid relaying redundant addresses to this peer.
 310       *
 311       *  We initialize this filter for outbound peers (other than
 312       *  block-relay-only connections) or when an inbound peer sends us an
 313       *  address related message (ADDR, ADDRV2, GETADDR).
 314       *
 315       *  Presence of this filter must correlate with m_addr_relay_enabled.
 316       **/
 317      std::unique_ptr<CRollingBloomFilter> m_addr_known GUARDED_BY(NetEventsInterface::g_msgproc_mutex);
 318      /** Whether we are participating in address relay with this connection.
 319       *
 320       *  We set this bool to true for outbound peers (other than
 321       *  block-relay-only connections), or when an inbound peer sends us an
 322       *  address related message (ADDR, ADDRV2, GETADDR).
 323       *
 324       *  We use this bool to decide whether a peer is eligible for gossiping
 325       *  addr messages. This avoids relaying to peers that are unlikely to
 326       *  forward them, effectively blackholing self announcements. Reasons
 327       *  peers might support addr relay on the link include that they connected
 328       *  to us as a block-relay-only peer or they are a light client.
 329       *
 330       *  This field must correlate with whether m_addr_known has been
 331       *  initialized.*/
 332      std::atomic_bool m_addr_relay_enabled{false};
 333      /** Whether a getaddr request to this peer is outstanding. */
 334      bool m_getaddr_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
 335      /** Guards address sending timers. */
 336      mutable Mutex m_addr_send_times_mutex;
 337      /** Time point to send the next ADDR message to this peer. */
 338      std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
 339      /** Time point to possibly re-announce our local address to this peer. */
 340      std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
 341      /** Whether the peer has signaled support for receiving ADDRv2 (BIP155)
 342       *  messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */
 343      std::atomic_bool m_wants_addrv2{false};
 344      /** Whether this peer has already sent us a getaddr message. */
 345      bool m_getaddr_recvd GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
 346      /** Number of addresses that can be processed from this peer. Start at 1 to
 347       *  permit self-announcement. */
 348      double m_addr_token_bucket GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1.0};
 349      /** When m_addr_token_bucket was last updated */
 350      std::chrono::microseconds m_addr_token_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){GetTime<std::chrono::microseconds>()};
 351      /** Total number of addresses that were dropped due to rate limiting. */
 352      std::atomic<uint64_t> m_addr_rate_limited{0};
 353      /** Total number of addresses that were processed (excludes rate-limited ones). */
 354      std::atomic<uint64_t> m_addr_processed{0};
 355  
 356      /** Whether we've sent this peer a getheaders in response to an inv prior to initial-headers-sync completing */
 357      bool m_inv_triggered_getheaders_before_sync GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
 358  
 359      /** Protects m_getdata_requests **/
 360      Mutex m_getdata_requests_mutex;
 361      /** Work queue of items requested by this peer **/
 362      std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);
 363  
 364      /** Time of the last getheaders message to this peer */
 365      NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};
 366  
 367      /** Protects m_headers_sync **/
 368      Mutex m_headers_sync_mutex;
 369      /** Headers-sync state for this peer (eg for initial sync, or syncing large
 370       * reorgs) **/
 371      std::unique_ptr<HeadersSyncState> m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex) GUARDED_BY(m_headers_sync_mutex) {};
 372  
 373      /** Whether we've sent our peer a sendheaders message. **/
 374      std::atomic<bool> m_sent_sendheaders{false};
 375  
 376      /** When to potentially disconnect peer for stalling headers download */
 377      std::chrono::microseconds m_headers_sync_timeout GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0us};
 378  
 379      /** Whether this peer wants invs or headers (when possible) for block announcements */
 380      bool m_prefers_headers GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
 381  
 382      /** Time offset computed during the version handshake based on the
 383       * timestamp the peer sent in the version message. */
 384      std::atomic<std::chrono::seconds> m_time_offset{0s};
 385  
 386      /** Number of consecutive deserialization failures from this peer.
 387       *  Used to detect and disconnect peers sending malformed messages. */
 388      uint32_t m_deserialization_failures GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0};
 389  
 390      explicit Peer(NodeId id, ServiceFlags our_services, bool is_inbound)
 391          : m_id{id}
 392          , m_our_services{our_services}
 393          , m_is_inbound{is_inbound}
 394      {}
 395  
 396  private:
 397      mutable Mutex m_tx_relay_mutex;
 398  
 399      /** Transaction relay data. May be a nullptr. */
 400      std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex);
 401  };
 402  
 403  using PeerRef = std::shared_ptr<Peer>;
 404  
 405  /**
 406   * Maintain validation-specific state about nodes, protected by cs_main, instead
 407   * by CNode's own locks. This simplifies asynchronous operation, where
 408   * processing of incoming data is done after the ProcessMessage call returns,
 409   * and we're no longer holding the node's locks.
 410   */
 411  struct CNodeState {
 412      //! The best known block we know this peer has announced.
 413      const CBlockIndex* pindexBestKnownBlock{nullptr};
 414      //! The hash of the last unknown block this peer has announced.
 415      uint256 hashLastUnknownBlock{};
 416      //! The last full block we both have.
 417      const CBlockIndex* pindexLastCommonBlock{nullptr};
 418      //! The best header we have sent our peer.
 419      const CBlockIndex* pindexBestHeaderSent{nullptr};
 420      //! Whether we've started headers synchronization with this peer.
 421      bool fSyncStarted{false};
 422      //! Since when we're stalling block download progress (in microseconds), or 0.
 423      std::chrono::microseconds m_stalling_since{0us};
 424      std::list<QueuedBlock> vBlocksInFlight;
 425      //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
 426      std::chrono::microseconds m_downloading_since{0us};
 427      //! Whether we consider this a preferred download peer.
 428      bool fPreferredDownload{false};
 429      /** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */
 430      bool m_requested_hb_cmpctblocks{false};
 431      /** Whether this peer will send us cmpctblocks if we request them. */
 432      bool m_provides_cmpctblocks{false};
 433  
 434      /** State used to enforce CHAIN_SYNC_TIMEOUT and EXTRA_PEER_CHECK_INTERVAL logic.
 435        *
 436        * Both are only in effect for outbound, non-manual, non-protected connections.
 437        * Any peer protected (m_protect = true) is not chosen for eviction. A peer is
 438        * marked as protected if all of these are true:
 439        *   - its connection type is IsBlockOnlyConn() == false
 440        *   - it gave us a valid connecting header
 441        *   - we haven't reached MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT yet
 442        *   - its chain tip has at least as much work as ours
 443        *
 444        * CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip,
 445        * set a timeout CHAIN_SYNC_TIMEOUT in the future:
 446        *   - If at timeout their best known block now has more work than our tip
 447        *     when the timeout was set, then either reset the timeout or clear it
 448        *     (after comparing against our current tip's work)
 449        *   - If at timeout their best known block still has less work than our
 450        *     tip did when the timeout was set, then send a getheaders message,
 451        *     and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
 452        *     If their best known block is still behind when that new timeout is
 453        *     reached, disconnect.
 454        *
 455        * EXTRA_PEER_CHECK_INTERVAL: after each interval, if we have too many outbound peers,
 456        * drop the outbound one that least recently announced us a new block.
 457        */
 458      struct ChainSyncTimeoutState {
 459          //! A timeout used for checking whether our peer has sufficiently synced
 460          std::chrono::seconds m_timeout{0s};
 461          //! A header with the work we require on our peer's chain
 462          const CBlockIndex* m_work_header{nullptr};
 463          //! After timeout is reached, set to true after sending getheaders
 464          bool m_sent_getheaders{false};
 465          //! Whether this peer is protected from disconnection due to a bad/slow chain
 466          bool m_protect{false};
 467      };
 468  
 469      ChainSyncTimeoutState m_chain_sync;
 470  
 471      //! Time of last new block announcement
 472      int64_t m_last_block_announcement{0};
 473  };
 474  
 475  class PeerManagerImpl final : public PeerManager
 476  {
 477  public:
 478      PeerManagerImpl(CConnman& connman, AddrMan& addrman,
 479                      BanMan* banman, ChainstateManager& chainman,
 480                      CTxMemPool& pool, node::Warnings& warnings, Options opts);
 481  
 482      /** Overridden from CValidationInterface. */
 483      void ActiveTipChange(const CBlockIndex& new_tip, bool) override
 484          EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex);
 485      void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override
 486          EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex);
 487      void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override
 488          EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex);
 489      void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
 490          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 491      void BlockChecked(const CBlock& block, const BlockValidationState& state) override
 492          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 493      void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override
 494          EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);
 495  
 496      /** Implement NetEventsInterface */
 497      void InitializeNode(const CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_tx_download_mutex);
 498      void FinalizeNode(const CNode& node) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, !m_tx_download_mutex);
 499      bool HasAllDesirableServiceFlags(ServiceFlags services) const override;
 500      bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override
 501          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex, !m_tx_download_mutex);
 502      bool SendMessages(CNode* pto) override
 503          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, g_msgproc_mutex, !m_tx_download_mutex);
 504  
 505      /** Implement PeerManager */
 506      void StartScheduledTasks(CScheduler& scheduler) override;
 507      void CheckForStaleTipAndEvictPeers() override;
 508      std::optional<std::string> FetchBlock(NodeId peer_id, const uint256& hash, const CBlockIndex* block_index) override
 509          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 510      bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 511      std::vector<TxOrphanage::OrphanTxBase> GetOrphanTransactions() override EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex);
 512      PeerManagerInfo GetInfo() const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 513      void LimitOrphanTxSize(uint32_t nMaxOrphans) override EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex);
 514      void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 515      void RelayTransaction(const uint256& txid, const uint256& wtxid) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 516      void SetBestBlock(int height, std::chrono::seconds time) override
 517      {
 518          m_best_height = height;
 519          m_best_block_time = time;
 520      };
 521      void UnitTestMisbehaving(NodeId peer_id) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), ""); };
 522      void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv,
 523                          const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override
 524          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex, !m_tx_download_mutex);
 525      void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override;
 526      ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const override;
 527      int GetNumberOfPeersWithValidatedDownloads() const override EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
 528  
 529  private:
 530      /** Consider evicting an outbound peer based on the amount of time they've been behind our tip */
 531      void ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_msgproc_mutex);
 532  
 533      /** If we have extra outbound peers, try to disconnect the one with the oldest block announcement */
 534      void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 535  
 536      /** Retrieve unbroadcast transactions from the mempool and reattempt sending to peers */
 537      void ReattemptInitialBroadcast(CScheduler& scheduler) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 538  
 539      /** Get a shared pointer to the Peer object.
 540       *  May return an empty shared_ptr if the Peer object can't be found. */
 541      PeerRef GetPeerRef(NodeId id) const EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 542  
 543      /** Get a shared pointer to the Peer object and remove it from m_peer_map.
 544       *  May return an empty shared_ptr if the Peer object can't be found. */
 545      PeerRef RemovePeer(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 546  
 547      /** Mark a peer as misbehaving, which will cause it to be disconnected and its
 548       *  address discouraged. */
 549      void Misbehaving(Peer& peer, const std::string& message);
 550  
 551      /**
 552       * Potentially mark a node discouraged based on the contents of a BlockValidationState object
 553       *
 554       * @param[in] via_compact_block this bool is passed in because net_processing should
 555       * punish peers differently depending on whether the data was provided in a compact
 556       * block message or not. If the compact block had a valid header, but contained invalid
 557       * txs, the peer should not be punished. See BIP 152.
 558       */
 559      void MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
 560                                   bool via_compact_block, const std::string& message = "")
 561          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
 562  
 563      /** Maybe disconnect a peer and discourage future connections from its address.
 564       *
 565       * @param[in]   pnode     The node to check.
 566       * @param[in]   peer      The peer object to check.
 567       * @return                True if the peer was marked for disconnection in this function
 568       */
 569      bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer);
 570  
 571      /** Handle a transaction whose result was not MempoolAcceptResult::ResultType::VALID.
 572       * @param[in]   first_time_failure            Whether we should consider inserting into vExtraTxnForCompact, adding
 573       *                                            a new orphan to resolve, or looking for a package to submit.
 574       *                                            Set to true for transactions just received over p2p.
 575       *                                            Set to false if the tx has already been rejected before,
 576       *                                            e.g. is already in the orphanage, to avoid adding duplicate entries.
 577       * Updates m_txrequest, m_lazy_recent_rejects, m_lazy_recent_rejects_reconsiderable, m_orphanage, and vExtraTxnForCompact.
 578       *
 579       * @returns a PackageToValidate if this transaction has a reconsiderable failure and an eligible package was found,
 580       * or std::nullopt otherwise.
 581       */
 582      std::optional<node::PackageToValidate> ProcessInvalidTx(NodeId nodeid, const CTransactionRef& tx, const TxValidationState& result,
 583                                                        bool first_time_failure)
 584          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, m_tx_download_mutex);
 585  
 586      /** Handle a transaction whose result was MempoolAcceptResult::ResultType::VALID.
 587       * Updates m_txrequest, m_orphanage, and vExtraTxnForCompact. Also queues the tx for relay. */
 588      void ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions)
 589          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, m_tx_download_mutex);
 590  
 591      /** Handle the results of package validation: calls ProcessValidTx and ProcessInvalidTx for
 592       * individual transactions, and caches rejection for the package as a group.
 593       */
 594      void ProcessPackageResult(const node::PackageToValidate& package_to_validate, const PackageMempoolAcceptResult& package_result)
 595          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, m_tx_download_mutex);
 596  
 597      /**
 598       * Reconsider orphan transactions after a parent has been accepted to the mempool.
 599       *
 600       * @peer[in]  peer     The peer whose orphan transactions we will reconsider. Generally only
 601       *                     one orphan will be reconsidered on each call of this function. If an
 602       *                     accepted orphan has orphaned children, those will need to be
 603       *                     reconsidered, creating more work, possibly for other peers.
 604       * @return             True if meaningful work was done (an orphan was accepted/rejected).
 605       *                     If no meaningful work was done, then the work set for this peer
 606       *                     will be empty.
 607       */
 608      bool ProcessOrphanTx(Peer& peer)
 609          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, !m_tx_download_mutex);
 610  
 611      /** Process a single headers message from a peer.
 612       *
 613       * @param[in]   pfrom     CNode of the peer
 614       * @param[in]   peer      The peer sending us the headers
 615       * @param[in]   headers   The headers received. Note that this may be modified within ProcessHeadersMessage.
 616       * @param[in]   via_compact_block   Whether this header came in via compact block handling.
 617      */
 618      void ProcessHeadersMessage(CNode& pfrom, Peer& peer,
 619                                 std::vector<CBlockHeader>&& headers,
 620                                 bool via_compact_block)
 621          EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
 622      /** Various helpers for headers processing, invoked by ProcessHeadersMessage() */
 623      /** Return true if headers are continuous and have valid proof-of-work (DoS points assigned on failure) */
 624      bool CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer);
 625      /** Calculate an anti-DoS work threshold for headers chains */
 626      arith_uint256 GetAntiDoSWorkThreshold();
 627      /** Deal with state tracking and headers sync for peers that send
 628       * non-connecting headers (this can happen due to BIP 130 headers
 629       * announcements for blocks interacting with the 2hr (MAX_FUTURE_BLOCK_TIME) rule). */
 630      void HandleUnconnectingHeaders(CNode& pfrom, Peer& peer, const std::vector<CBlockHeader>& headers) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 631      /** Return true if the headers connect to each other, false otherwise */
 632      bool CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const;
 633      /** Try to continue a low-work headers sync that has already begun.
 634       * Assumes the caller has already verified the headers connect, and has
 635       * checked that each header satisfies the proof-of-work target included in
 636       * the header.
 637       *  @param[in]  peer                            The peer we're syncing with.
 638       *  @param[in]  pfrom                           CNode of the peer
 639       *  @param[in,out] headers                      The headers to be processed.
 640       *  @return     True if the passed in headers were successfully processed
 641       *              as the continuation of a low-work headers sync in progress;
 642       *              false otherwise.
 643       *              If false, the passed in headers will be returned back to
 644       *              the caller.
 645       *              If true, the returned headers may be empty, indicating
 646       *              there is no more work for the caller to do; or the headers
 647       *              may be populated with entries that have passed anti-DoS
 648       *              checks (and therefore may be validated for block index
 649       *              acceptance by the caller).
 650       */
 651      bool IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom,
 652              std::vector<CBlockHeader>& headers)
 653          EXCLUSIVE_LOCKS_REQUIRED(peer.m_headers_sync_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
 654      /** Check work on a headers chain to be processed, and if insufficient,
 655       * initiate our anti-DoS headers sync mechanism.
 656       *
 657       * @param[in]   peer                The peer whose headers we're processing.
 658       * @param[in]   pfrom               CNode of the peer
 659       * @param[in]   chain_start_header  Where these headers connect in our index.
 660       * @param[in,out]   headers             The headers to be processed.
 661       *
 662       * @return      True if chain was low work (headers will be empty after
 663       *              calling); false otherwise.
 664       */
 665      bool TryLowWorkHeadersSync(Peer& peer, CNode& pfrom,
 666                                    const CBlockIndex* chain_start_header,
 667                                    std::vector<CBlockHeader>& headers)
 668          EXCLUSIVE_LOCKS_REQUIRED(!peer.m_headers_sync_mutex, !m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
 669  
 670      /** Return true if the given header is an ancestor of
 671       *  m_chainman.m_best_header or our current tip */
 672      bool IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 673  
 674      /** Request further headers from this peer with a given locator.
 675       * We don't issue a getheaders message if we have a recent one outstanding.
 676       * This returns true if a getheaders is actually sent, and false otherwise.
 677       */
 678      bool MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 679      /** Potentially fetch blocks from this peer upon receipt of a new headers tip */
 680      void HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header);
 681      /** Update peer state based on received headers message */
 682      void UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers)
 683          EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 684  
 685      void SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req);
 686  
 687      /** Send a message to a peer */
 688      void PushMessage(CNode& node, CSerializedNetMsg&& msg) const { m_connman.PushMessage(&node, std::move(msg)); }
 689      template <typename... Args>
 690      void MakeAndPushMessage(CNode& node, std::string msg_type, Args&&... args) const
 691      {
 692          m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...));
 693      }
 694  
 695      /** Send a version message to a peer */
 696      void PushNodeVersion(CNode& pnode, const Peer& peer);
 697  
 698      /** Send a ping message every PING_INTERVAL or if requested via RPC. May
 699       *  mark the peer to be disconnected if a ping has timed out.
 700       *  We use mockable time for ping timeouts, so setmocktime may cause pings
 701       *  to time out. */
 702      void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now);
 703  
 704      /** Send `addr` messages on a regular schedule. */
 705      void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 706  
 707      /** Send a single `sendheaders` message, after we have completed headers sync with a peer. */
 708      void MaybeSendSendHeaders(CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 709  
 710      /** Relay (gossip) an address to a few randomly chosen nodes.
 711       *
 712       * @param[in] originator   The id of the peer that sent us the address. We don't want to relay it back.
 713       * @param[in] addr         Address to relay.
 714       * @param[in] fReachable   Whether the address' network is reachable. We relay unreachable
 715       *                         addresses less.
 716       */
 717      void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex);
 718  
 719      /** Send `feefilter` message. */
 720      void MaybeSendFeefilter(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 721  
 722      FastRandomContext m_rng GUARDED_BY(NetEventsInterface::g_msgproc_mutex);
 723  
 724      FeeFilterRounder m_fee_filter_rounder GUARDED_BY(NetEventsInterface::g_msgproc_mutex);
 725  
 726      const CChainParams& m_chainparams;
 727      CConnman& m_connman;
 728      AddrMan& m_addrman;
 729      /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
 730      BanMan* const m_banman;
 731      ChainstateManager& m_chainman;
 732      CTxMemPool& m_mempool;
 733  
 734      /** Synchronizes tx download including TxRequestTracker, rejection filters, and TxOrphanage.
 735       * Lock invariants:
 736       * - A txhash (txid or wtxid) in m_txrequest is not also in m_orphanage.
 737       * - A txhash (txid or wtxid) in m_txrequest is not also in m_lazy_recent_rejects.
 738       * - A txhash (txid or wtxid) in m_txrequest is not also in m_lazy_recent_rejects_reconsiderable.
 739       * - A txhash (txid or wtxid) in m_txrequest is not also in m_lazy_recent_confirmed_transactions.
 740       * - Each data structure's limits hold (m_orphanage max size, m_txrequest per-peer limits, etc).
 741       */
 742      Mutex m_tx_download_mutex ACQUIRED_BEFORE(m_mempool.cs);
 743      node::TxDownloadManager m_txdownloadman GUARDED_BY(m_tx_download_mutex);
 744  
 745      std::unique_ptr<TxReconciliationTracker> m_txreconciliation;
 746  
 747      /** The height of the best chain */
 748      std::atomic<int> m_best_height{-1};
 749      /** The time of the best chain tip block */
 750      std::atomic<std::chrono::seconds> m_best_block_time{0s};
 751  
 752      /** Next time to check for stale tip */
 753      std::chrono::seconds m_stale_tip_check_time GUARDED_BY(cs_main){0s};
 754  
 755      node::Warnings& m_warnings;
 756      TimeOffsets m_outbound_time_offsets{m_warnings};
 757  
 758      const Options m_opts;
 759  
 760      bool RejectIncomingTxs(const CNode& peer) const;
 761  
 762      /** Whether we've completed initial sync yet, for determining when to turn
 763        * on extra block-relay-only peers. */
 764      bool m_initial_sync_finished GUARDED_BY(cs_main){false};
 765  
 766      /** Protects m_peer_map. This mutex must not be locked while holding a lock
 767       *  on any of the mutexes inside a Peer object. */
 768      mutable Mutex m_peer_mutex;
 769      /**
 770       * Map of all Peer objects, keyed by peer id. This map is protected
 771       * by the m_peer_mutex. Once a shared pointer reference is
 772       * taken, the lock may be released. Individual fields are protected by
 773       * their own locks.
 774       */
 775      std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex);
 776  
 777      /** Map maintaining per-node state. */
 778      std::map<NodeId, CNodeState> m_node_states GUARDED_BY(cs_main);
 779  
 780      /** Get a pointer to a const CNodeState, used when not mutating the CNodeState object. */
 781      const CNodeState* State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 782      /** Get a pointer to a mutable CNodeState. */
 783      CNodeState* State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 784  
 785      uint32_t GetFetchFlags(const Peer& peer) const;
 786  
 787      std::map<uint64_t, std::chrono::microseconds> m_next_inv_to_inbounds_per_network_key GUARDED_BY(g_msgproc_mutex);
 788  
 789      /** Number of nodes with fSyncStarted. */
 790      int nSyncStarted GUARDED_BY(cs_main) = 0;
 791  
 792      /** Hash of the last block we received via INV */
 793      uint256 m_last_block_inv_triggering_headers_sync GUARDED_BY(g_msgproc_mutex){};
 794  
 795      /**
 796       * Sources of received blocks, saved to be able punish them when processing
 797       * happens afterwards.
 798       * Set mapBlockSource[hash].second to false if the node should not be
 799       * punished if the block is invalid.
 800       */
 801      std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main);
 802  
 803      /** Number of peers with wtxid relay. */
 804      std::atomic<int> m_wtxid_relay_peers{0};
 805  
 806      /** Number of outbound peers without NODE_REDUCED_DATA (BIP-110). Limited to 2. */
 807      std::atomic<unsigned int> m_num_non_bip110_outbound{0};
 808  
 809      /** Number of outbound peers with m_chain_sync.m_protect. */
 810      int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
 811  
 812      /** Number of preferable block download peers. */
 813      int m_num_preferred_download_peers GUARDED_BY(cs_main){0};
 814  
 815      /** Stalling timeout for blocks in IBD */
 816      std::atomic<std::chrono::seconds> m_block_stalling_timeout{BLOCK_STALLING_TIMEOUT_DEFAULT};
 817  
 818      /**
 819       * For sending `inv`s to inbound peers, we use a single (exponentially
 820       * distributed) timer for all peers with the same network key. If we used a separate timer for each
 821       * peer, a spy node could make multiple inbound connections to us to
 822       * accurately determine when we received a transaction (and potentially
 823       * determine the transaction's origin). Each network key has its own timer
 824       * to make fingerprinting harder. */
 825      std::chrono::microseconds NextInvToInbounds(std::chrono::microseconds now,
 826                                                  std::chrono::seconds average_interval,
 827                                                  uint64_t network_key) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 828  
 829  
 830      // All of the following cache a recent block, and are protected by m_most_recent_block_mutex
 831      Mutex m_most_recent_block_mutex;
 832      std::shared_ptr<const CBlock> m_most_recent_block GUARDED_BY(m_most_recent_block_mutex);
 833      std::shared_ptr<const CBlockHeaderAndShortTxIDs> m_most_recent_compact_block GUARDED_BY(m_most_recent_block_mutex);
 834      uint256 m_most_recent_block_hash GUARDED_BY(m_most_recent_block_mutex);
 835      std::unique_ptr<const std::map<uint256, CTransactionRef>> m_most_recent_block_txs GUARDED_BY(m_most_recent_block_mutex);
 836  
 837      // Data about the low-work headers synchronization, aggregated from all peers' HeadersSyncStates.
 838      /** Mutex guarding the other m_headers_presync_* variables. */
 839      Mutex m_headers_presync_mutex;
 840      /** A type to represent statistics about a peer's low-work headers sync.
 841       *
 842       * - The first field is the total verified amount of work in that synchronization.
 843       * - The second is:
 844       *   - nullopt: the sync is in REDOWNLOAD phase (phase 2).
 845       *   - {height, timestamp}: the sync has the specified tip height and block timestamp (phase 1).
 846       */
 847      using HeadersPresyncStats = std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>;
 848      /** Statistics for all peers in low-work headers sync. */
 849      std::map<NodeId, HeadersPresyncStats> m_headers_presync_stats GUARDED_BY(m_headers_presync_mutex) {};
 850      /** The peer with the most-work entry in m_headers_presync_stats. */
 851      NodeId m_headers_presync_bestpeer GUARDED_BY(m_headers_presync_mutex) {-1};
 852      /** The m_headers_presync_stats improved, and needs signalling. */
 853      std::atomic_bool m_headers_presync_should_signal{false};
 854  
 855      /** Height of the highest block announced using BIP 152 high-bandwidth mode. */
 856      int m_highest_fast_announce GUARDED_BY(::cs_main){0};
 857  
 858      /** Have we requested this block from a peer */
 859      bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 860  
 861      /** Have we requested this block from an outbound peer */
 862      bool IsBlockRequestedFromOutbound(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_peer_mutex);
 863  
 864      /** Have we requested this block from a specific peer */
 865      bool IsBlockRequestedFromPeer(const uint256& hash, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 866  
 867      /** Remove this block from our tracked requested blocks. Called if:
 868       *  - the block has been received from a peer
 869       *  - the request for the block has timed out
 870       * If "from_peer" is specified, then only remove the block if it is in
 871       * flight from that peer (to avoid one peer's network traffic from
 872       * affecting another's state).
 873       */
 874      void RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 875  
 876      /* Mark a block as in flight
 877       * Returns false, still setting pit, if the block was already in flight from the same peer
 878       * pit will only be valid as long as the same cs_main lock is being held
 879       */
 880      bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 881  
 882      bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 883  
 884      /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
 885       *  at most count entries.
 886       */
 887      void FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 888  
 889      /** Request blocks for the background chainstate, if one is in use. */
 890      void TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex* from_tip, const CBlockIndex* target_block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 891  
 892      /**
 893      * \brief Find next blocks to download from a peer after a starting block.
 894      *
 895      * \param vBlocks      Vector of blocks to download which will be appended to.
 896      * \param peer         Peer which blocks will be downloaded from.
 897      * \param state        Pointer to the state of the peer.
 898      * \param pindexWalk   Pointer to the starting block to add to vBlocks.
 899      * \param count        Maximum number of blocks to allow in vBlocks. No more
 900      *                     blocks will be added if it reaches this size.
 901      * \param nWindowEnd   Maximum height of blocks to allow in vBlocks. No
 902      *                     blocks will be added above this height.
 903      * \param activeChain  Optional pointer to a chain to compare against. If
 904      *                     provided, any next blocks which are already contained
 905      *                     in this chain will not be appended to vBlocks, but
 906      *                     instead will be used to update the
 907      *                     state->pindexLastCommonBlock pointer.
 908      * \param nodeStaller  Optional pointer to a NodeId variable that will receive
 909      *                     the ID of another peer that might be causing this peer
 910      *                     to stall. This is set to the ID of the peer which
 911      *                     first requested the first in-flight block in the
 912      *                     download window. It is only set if vBlocks is empty at
 913      *                     the end of this function call and if increasing
 914      *                     nWindowEnd by 1 would cause it to be non-empty (which
 915      *                     indicates the download might be stalled because every
 916      *                     block in the window is in flight and no other peer is
 917      *                     trying to download the next block).
 918      */
 919      void FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain=nullptr, NodeId* nodeStaller=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 920  
 921      /* Multimap used to preserve insertion order */
 922      typedef std::multimap<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator>> BlockDownloadMap;
 923      BlockDownloadMap mapBlocksInFlight GUARDED_BY(cs_main);
 924  
 925      /** When our tip was last updated. */
 926      std::atomic<std::chrono::seconds> m_last_tip_update{0s};
 927  
 928      /** Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). */
 929      CTransactionRef FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid)
 930          EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, NetEventsInterface::g_msgproc_mutex);
 931  
 932      void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
 933          EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex, NetEventsInterface::g_msgproc_mutex)
 934          LOCKS_EXCLUDED(::cs_main);
 935  
 936      /** Process a new block. Perform any post-processing housekeeping */
 937      void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked);
 938  
 939      /** Process compact block txns  */
 940      void ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions)
 941          EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex, !m_most_recent_block_mutex);
 942  
 943      /**
 944       * When a peer sends us a valid block, instruct it to announce blocks to us
 945       * using CMPCTBLOCK if possible by adding its nodeid to the end of
 946       * lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by
 947       * removing the first element if necessary.
 948       */
 949      void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_peer_mutex);
 950  
 951      /** Stack of nodes which we have set to announce using compact blocks */
 952      std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
 953  
 954      /** Number of peers from which we're downloading blocks. */
 955      int m_peers_downloading_from GUARDED_BY(cs_main) = 0;
 956  
 957      void AddToCompactExtraTransactions(const CTransactionRef& tx, size_t tx_dynamic_usage) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
 958  
 959      /** Orphan/conflicted/etc transactions that are kept for compact block reconstruction.
 960       *  The last -blockreconstructionextratxn/DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN of
 961       *  these are kept in a ring buffer */
 962      std::vector<CTransactionRef> vExtraTxnForCompact GUARDED_BY(g_msgproc_mutex);
 963      /** Offset into vExtraTxnForCompact to insert the next tx */
 964      size_t vExtraTxnForCompactIt GUARDED_BY(g_msgproc_mutex) = 0;
 965      size_t blockreconstructionextratxn_memusage{0};
 966  
 967      /** Check whether the last unknown block a peer advertised is not yet known. */
 968      void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 969      /** Update tracking information about which blocks a peer is assumed to have. */
 970      void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 971      bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 972  
 973      /**
 974       * Estimates the distance, in blocks, between the best-known block and the network chain tip.
 975       * Utilizes the best-block time and the chainparams blocks spacing to approximate it.
 976       */
 977      int64_t ApproximateBestBlockDepth() const;
 978  
 979      /**
 980       * To prevent fingerprinting attacks, only send blocks/headers outside of
 981       * the active chain if they are no more than a month older (both in time,
 982       * and in best equivalent proof of work) than the best header chain we know
 983       * about and we fully-validated them at some point.
 984       */
 985      bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 986      bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 987      void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
 988          EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex, !m_most_recent_block_mutex);
 989  
 990      /**
 991       * Validation logic for compact filters request handling.
 992       *
 993       * May disconnect from the peer in the case of a bad request.
 994       *
 995       * @param[in]   node            The node that we received the request from
 996       * @param[in]   peer            The peer that we received the request from
 997       * @param[in]   filter_type     The filter type the request is for. Must be basic filters.
 998       * @param[in]   start_height    The start height for the request
 999       * @param[in]   stop_hash       The stop_hash for the request
1000       * @param[in]   max_height_diff The maximum number of items permitted to request, as specified in BIP 157
1001       * @param[out]  stop_index      The CBlockIndex for the stop_hash block, if the request can be serviced.
1002       * @param[out]  filter_index    The filter index, if the request can be serviced.
1003       * @return                      True if the request can be serviced.
1004       */
1005      bool PrepareBlockFilterRequest(CNode& node, Peer& peer,
1006                                     BlockFilterType filter_type, uint32_t start_height,
1007                                     const uint256& stop_hash, uint32_t max_height_diff,
1008                                     const CBlockIndex*& stop_index,
1009                                     BlockFilterIndex*& filter_index);
1010  
1011      /**
1012       * Handle a cfilters request.
1013       *
1014       * May disconnect from the peer in the case of a bad request.
1015       *
1016       * @param[in]   node            The node that we received the request from
1017       * @param[in]   peer            The peer that we received the request from
1018       * @param[in]   vRecv           The raw message received
1019       */
1020      void ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv);
1021  
1022      /**
1023       * Handle a cfheaders request.
1024       *
1025       * May disconnect from the peer in the case of a bad request.
1026       *
1027       * @param[in]   node            The node that we received the request from
1028       * @param[in]   peer            The peer that we received the request from
1029       * @param[in]   vRecv           The raw message received
1030       */
1031      void ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv);
1032  
1033      /**
1034       * Handle a getcfcheckpt request.
1035       *
1036       * May disconnect from the peer in the case of a bad request.
1037       *
1038       * @param[in]   node            The node that we received the request from
1039       * @param[in]   peer            The peer that we received the request from
1040       * @param[in]   vRecv           The raw message received
1041       */
1042      void ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv);
1043  
1044      /** Checks if address relay is permitted with peer. If needed, initializes
1045       * the m_addr_known bloom filter and sets m_addr_relay_enabled to true.
1046       *
1047       *  @return   True if address relay is enabled with peer
1048       *            False if address relay is disallowed
1049       */
1050      bool SetupAddressRelay(const CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1051  
1052      void AddAddressKnown(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1053      void PushAddress(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1054  };
1055  
1056  const CNodeState* PeerManagerImpl::State(NodeId pnode) const
1057  {
1058      std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
1059      if (it == m_node_states.end())
1060          return nullptr;
1061      return &it->second;
1062  }
1063  
1064  CNodeState* PeerManagerImpl::State(NodeId pnode)
1065  {
1066      return const_cast<CNodeState*>(std::as_const(*this).State(pnode));
1067  }
1068  
1069  /**
1070   * Whether the peer supports the address. For example, a peer that does not
1071   * implement BIP155 cannot receive Tor v3 addresses because it requires
1072   * ADDRv2 (BIP155) encoding.
1073   */
1074  static bool IsAddrCompatible(const Peer& peer, const CAddress& addr)
1075  {
1076      return peer.m_wants_addrv2 || addr.IsAddrV1Compatible();
1077  }
1078  
1079  void PeerManagerImpl::AddAddressKnown(Peer& peer, const CAddress& addr)
1080  {
1081      assert(peer.m_addr_known);
1082      peer.m_addr_known->insert(addr.GetKey());
1083  }
1084  
1085  void PeerManagerImpl::PushAddress(Peer& peer, const CAddress& addr)
1086  {
1087      // Known checking here is only to save space from duplicates.
1088      // Before sending, we'll filter it again for known addresses that were
1089      // added after addresses were pushed.
1090      assert(peer.m_addr_known);
1091      if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) {
1092          if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) {
1093              peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] = addr;
1094          } else {
1095              peer.m_addrs_to_send.push_back(addr);
1096          }
1097      }
1098  }
1099  
1100  static void AddKnownTx(Peer& peer, const uint256& hash)
1101  {
1102      auto tx_relay = peer.GetTxRelay();
1103      if (!tx_relay) return;
1104  
1105      LOCK(tx_relay->m_tx_inventory_mutex);
1106      tx_relay->m_tx_inventory_known_filter.insert(hash);
1107  }
1108  
1109  /** Whether this peer can serve us blocks. */
1110  static bool CanServeBlocks(const Peer& peer)
1111  {
1112      return peer.m_their_services & (NODE_NETWORK|NODE_NETWORK_LIMITED);
1113  }
1114  
1115  /** Whether this peer can only serve limited recent blocks (e.g. because
1116   *  it prunes old blocks) */
1117  static bool IsLimitedPeer(const Peer& peer)
1118  {
1119      return (!(peer.m_their_services & NODE_NETWORK) &&
1120               (peer.m_their_services & NODE_NETWORK_LIMITED));
1121  }
1122  
1123  /** Whether this peer can serve us witness data */
1124  static bool CanServeWitnesses(const Peer& peer)
1125  {
1126      return peer.m_their_services & NODE_WITNESS;
1127  }
1128  
1129  std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
1130                                                               std::chrono::seconds average_interval,
1131                                                               uint64_t network_key)
1132  {
1133      auto [it, inserted] = m_next_inv_to_inbounds_per_network_key.try_emplace(network_key, 0us);
1134      auto& timer{it->second};
1135      if (timer < now) {
1136          timer = now + m_rng.rand_exp_duration(average_interval);
1137      }
1138      return timer;
1139  }
1140  
1141  bool PeerManagerImpl::IsBlockRequested(const uint256& hash)
1142  {
1143      return mapBlocksInFlight.count(hash);
1144  }
1145  
1146  bool PeerManagerImpl::IsBlockRequestedFromOutbound(const uint256& hash)
1147  {
1148      for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) {
1149          auto [nodeid, block_it] = range.first->second;
1150          PeerRef peer{GetPeerRef(nodeid)};
1151          if (peer && !peer->m_is_inbound) return true;
1152      }
1153  
1154      return false;
1155  }
1156  
1157  bool PeerManagerImpl::IsBlockRequestedFromPeer(const uint256& hash, NodeId peer)
1158  {
1159      for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) {
1160          auto [nodeid, block_it] = range.first->second;
1161          if (nodeid == peer) return true;
1162      }
1163  
1164      return false;
1165  }
1166  
1167  void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer)
1168  {
1169      auto range = mapBlocksInFlight.equal_range(hash);
1170      if (range.first == range.second) {
1171          // Block was not requested from any peer
1172          return;
1173      }
1174  
1175      // We should not have requested too many of this block
1176      Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK);
1177  
1178      while (range.first != range.second) {
1179          auto [node_id, list_it] = range.first->second;
1180  
1181          if (from_peer && *from_peer != node_id) {
1182              range.first++;
1183              continue;
1184          }
1185  
1186          CNodeState& state = *Assert(State(node_id));
1187  
1188          if (state.vBlocksInFlight.begin() == list_it) {
1189              // First block on the queue was received, update the start download time for the next one
1190              state.m_downloading_since = std::max(state.m_downloading_since, GetTime<std::chrono::microseconds>());
1191          }
1192          state.vBlocksInFlight.erase(list_it);
1193  
1194          if (state.vBlocksInFlight.empty()) {
1195              // Last validated block on the queue for this peer was received.
1196              m_peers_downloading_from--;
1197          }
1198          state.m_stalling_since = 0us;
1199  
1200          range.first = mapBlocksInFlight.erase(range.first);
1201      }
1202  }
1203  
1204  bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit)
1205  {
1206      const uint256& hash{block.GetBlockHash()};
1207  
1208      CNodeState *state = State(nodeid);
1209      assert(state != nullptr);
1210  
1211      Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK);
1212  
1213      // Short-circuit most stuff in case it is from the same node
1214      for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) {
1215          if (range.first->second.first == nodeid) {
1216              if (pit) {
1217                  *pit = &range.first->second.second;
1218              }
1219              return false;
1220          }
1221      }
1222  
1223      // Make sure it's not being fetched already from same peer.
1224      RemoveBlockRequest(hash, nodeid);
1225  
1226      std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
1227              {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool) : nullptr)});
1228      if (state->vBlocksInFlight.size() == 1) {
1229          // We're starting a block download (batch) from this peer.
1230          state->m_downloading_since = GetTime<std::chrono::microseconds>();
1231          m_peers_downloading_from++;
1232      }
1233      auto itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it)));
1234      if (pit) {
1235          *pit = &itInFlight->second.second;
1236      }
1237      return true;
1238  }
1239  
1240  void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid)
1241  {
1242      AssertLockHeld(cs_main);
1243  
1244      // When in -blocksonly mode, never request high-bandwidth mode from peers. Our
1245      // mempool will not contain the transactions necessary to reconstruct the
1246      // compact block.
1247      if (m_opts.ignore_incoming_txs) return;
1248  
1249      CNodeState* nodestate = State(nodeid);
1250      PeerRef peer{GetPeerRef(nodeid)};
1251      if (!nodestate || !nodestate->m_provides_cmpctblocks) {
1252          // Don't request compact blocks if the peer has not signalled support
1253          return;
1254      }
1255  
1256      int num_outbound_hb_peers = 0;
1257      for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
1258          if (*it == nodeid) {
1259              lNodesAnnouncingHeaderAndIDs.erase(it);
1260              lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
1261              return;
1262          }
1263          PeerRef peer_ref{GetPeerRef(*it)};
1264          if (peer_ref && !peer_ref->m_is_inbound) ++num_outbound_hb_peers;
1265      }
1266      if (peer && peer->m_is_inbound) {
1267          // If we're adding an inbound HB peer, make sure we're not removing
1268          // our last outbound HB peer in the process.
1269          if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 1) {
1270              PeerRef remove_peer{GetPeerRef(lNodesAnnouncingHeaderAndIDs.front())};
1271              if (remove_peer && !remove_peer->m_is_inbound) {
1272                  // Put the HB outbound peer in the second slot, so that it
1273                  // doesn't get removed.
1274                  std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
1275              }
1276          }
1277      }
1278      m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1279          AssertLockHeld(::cs_main);
1280          if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
1281              // As per BIP152, we only get 3 of our peers to announce
1282              // blocks using compact encodings.
1283              m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this](CNode* pnodeStop){
1284                  MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION);
1285                  // save BIP152 bandwidth state: we select peer to be low-bandwidth
1286                  pnodeStop->m_bip152_highbandwidth_to = false;
1287                  return true;
1288              });
1289              lNodesAnnouncingHeaderAndIDs.pop_front();
1290          }
1291          MakeAndPushMessage(*pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/true, /*version=*/CMPCTBLOCKS_VERSION);
1292          // save BIP152 bandwidth state: we select peer to be high-bandwidth
1293          pfrom->m_bip152_highbandwidth_to = true;
1294          lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
1295          return true;
1296      });
1297  }
1298  
1299  bool PeerManagerImpl::TipMayBeStale()
1300  {
1301      AssertLockHeld(cs_main);
1302      const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
1303      if (m_last_tip_update.load() == 0s) {
1304          m_last_tip_update = GetTime<std::chrono::seconds>();
1305      }
1306      return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty();
1307  }
1308  
1309  int64_t PeerManagerImpl::ApproximateBestBlockDepth() const
1310  {
1311      return (GetTime<std::chrono::seconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing;
1312  }
1313  
1314  bool PeerManagerImpl::CanDirectFetch()
1315  {
1316      return m_chainman.ActiveChain().Tip()->Time() > NodeClock::now() - m_chainparams.GetConsensus().PowTargetSpacing() * 20;
1317  }
1318  
1319  static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1320  {
1321      if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
1322          return true;
1323      if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
1324          return true;
1325      return false;
1326  }
1327  
1328  void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) {
1329      CNodeState *state = State(nodeid);
1330      assert(state != nullptr);
1331  
1332      if (!state->hashLastUnknownBlock.IsNull()) {
1333          const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
1334          if (pindex && pindex->nChainWork > 0) {
1335              if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1336                  state->pindexBestKnownBlock = pindex;
1337              }
1338              state->hashLastUnknownBlock.SetNull();
1339          }
1340      }
1341  }
1342  
1343  void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
1344      CNodeState *state = State(nodeid);
1345      assert(state != nullptr);
1346  
1347      ProcessBlockAvailability(nodeid);
1348  
1349      const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
1350      if (pindex && pindex->nChainWork > 0) {
1351          // An actually better block was announced.
1352          if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1353              state->pindexBestKnownBlock = pindex;
1354          }
1355      } else {
1356          // An unknown block was announced; just assume that the latest one is the best one.
1357          state->hashLastUnknownBlock = hash;
1358      }
1359  }
1360  
1361  // Logic for calculating which blocks to download from a given peer, given our current tip.
1362  void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller)
1363  {
1364      if (count == 0)
1365          return;
1366  
1367      vBlocks.reserve(vBlocks.size() + count);
1368      CNodeState *state = State(peer.m_id);
1369      assert(state != nullptr);
1370  
1371      // Make sure pindexBestKnownBlock is up to date, we'll need it.
1372      ProcessBlockAvailability(peer.m_id);
1373  
1374      if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) {
1375          // This peer has nothing interesting.
1376          return;
1377      }
1378  
1379      // When we sync with AssumeUtxo and discover the snapshot is not in the peer's best chain, abort:
1380      // We can't reorg to this chain due to missing undo data until the background sync has finished,
1381      // so downloading blocks from it would be futile.
1382      const CBlockIndex* snap_base{m_chainman.GetSnapshotBaseBlock()};
1383      if (snap_base && state->pindexBestKnownBlock->GetAncestor(snap_base->nHeight) != snap_base) {
1384          LogDebug(BCLog::NET, "Not downloading blocks from peer=%d, which doesn't have the snapshot block in its best chain.\n", peer.m_id);
1385          return;
1386      }
1387  
1388      // Bootstrap quickly by guessing a parent of our best tip is the forking point.
1389      // Guessing wrong in either direction is not a problem.
1390      // Also reset pindexLastCommonBlock after a snapshot was loaded, so that blocks after the snapshot will be prioritised for download.
1391      if (state->pindexLastCommonBlock == nullptr ||
1392          (snap_base && state->pindexLastCommonBlock->nHeight < snap_base->nHeight)) {
1393          state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())];
1394      }
1395  
1396      // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
1397      // of its current tip anymore. Go back enough to fix that.
1398      state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
1399      if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
1400          return;
1401  
1402      const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
1403      // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
1404      // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
1405      // download that next block if the window were 1 larger.
1406      int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1407  
1408      FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);
1409  }
1410  
1411  void PeerManagerImpl::TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex *from_tip, const CBlockIndex* target_block)
1412  {
1413      Assert(from_tip);
1414      Assert(target_block);
1415  
1416      if (vBlocks.size() >= count) {
1417          return;
1418      }
1419  
1420      vBlocks.reserve(count);
1421      CNodeState *state = Assert(State(peer.m_id));
1422  
1423      if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->GetAncestor(target_block->nHeight) != target_block) {
1424          // This peer can't provide us the complete series of blocks leading up to the
1425          // assumeutxo snapshot base.
1426          //
1427          // Presumably this peer's chain has less work than our ActiveChain()'s tip, or else we
1428          // will eventually crash when we try to reorg to it. Let other logic
1429          // deal with whether we disconnect this peer.
1430          //
1431          // TODO at some point in the future, we might choose to request what blocks
1432          // this peer does have from the historical chain, despite it not having a
1433          // complete history beneath the snapshot base.
1434          return;
1435      }
1436  
1437      FindNextBlocks(vBlocks, peer, state, from_tip, count, std::min<int>(from_tip->nHeight + BLOCK_DOWNLOAD_WINDOW, target_block->nHeight));
1438  }
1439  
1440  void PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain, NodeId* nodeStaller)
1441  {
1442      std::vector<const CBlockIndex*> vToFetch;
1443      int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1444      bool is_limited_peer = IsLimitedPeer(peer);
1445      NodeId waitingfor = -1;
1446      while (pindexWalk->nHeight < nMaxHeight) {
1447          // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
1448          // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
1449          // as iterating over ~100 CBlockIndex* entries anyway.
1450          int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
1451          vToFetch.resize(nToFetch);
1452          pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
1453          vToFetch[nToFetch - 1] = pindexWalk;
1454          for (unsigned int i = nToFetch - 1; i > 0; i--) {
1455              vToFetch[i - 1] = vToFetch[i]->pprev;
1456          }
1457  
1458          // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
1459          // are not yet downloaded and not in flight to vBlocks. In the meantime, update
1460          // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
1461          // already part of our chain (and therefore don't need it even if pruned).
1462          for (const CBlockIndex* pindex : vToFetch) {
1463              if (!pindex->IsValid(BLOCK_VALID_TREE)) {
1464                  // We consider the chain that this peer is on invalid.
1465                  return;
1466              }
1467  
1468              if (!CanServeWitnesses(peer) && DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {
1469                  // We wouldn't download this block or its descendants from this peer.
1470                  return;
1471              }
1472  
1473              if (pindex->nStatus & BLOCK_HAVE_DATA || (activeChain && activeChain->Contains(pindex))) {
1474                  if (activeChain && pindex->HaveNumChainTxs()) {
1475                      state->pindexLastCommonBlock = pindex;
1476                  }
1477                  continue;
1478              }
1479  
1480              // Is block in-flight?
1481              if (IsBlockRequested(pindex->GetBlockHash())) {
1482                  if (waitingfor == -1) {
1483                      // This is the first already-in-flight block.
1484                      waitingfor = mapBlocksInFlight.lower_bound(pindex->GetBlockHash())->second.first;
1485                  }
1486                  continue;
1487              }
1488  
1489              // The block is not already downloaded, and not yet in flight.
1490              if (pindex->nHeight > nWindowEnd) {
1491                  // We reached the end of the window.
1492                  if (vBlocks.size() == 0 && waitingfor != peer.m_id) {
1493                      // We aren't able to fetch anything, but we would be if the download window was one larger.
1494                      if (nodeStaller) *nodeStaller = waitingfor;
1495                  }
1496                  return;
1497              }
1498  
1499              // Don't request blocks that go further than what limited peers can provide
1500              if (is_limited_peer && (state->pindexBestKnownBlock->nHeight - pindex->nHeight >= static_cast<int>(NODE_NETWORK_LIMITED_MIN_BLOCKS) - 2 /* two blocks buffer for possible races */)) {
1501                  continue;
1502              }
1503  
1504              vBlocks.push_back(pindex);
1505              if (vBlocks.size() == count) {
1506                  return;
1507              }
1508          }
1509      }
1510  }
1511  
1512  } // namespace
1513  
1514  void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer)
1515  {
1516      uint64_t my_services{peer.m_our_services};
1517      const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())};
1518      uint64_t nonce = pnode.GetLocalNonce();
1519      const int nNodeStartingHeight{m_best_height};
1520      NodeId nodeid = pnode.GetId();
1521      CAddress addr = pnode.addr;
1522  
1523      CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService();
1524      uint64_t your_services{addr.nServices};
1525  
1526      const bool tx_relay{!RejectIncomingTxs(pnode)};
1527      MakeAndPushMessage(pnode, NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime,
1528              your_services, CNetAddr::V1(addr_you), // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime)
1529              my_services, CNetAddr::V1(CService{}), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime)
1530              nonce, strSubVersion, nNodeStartingHeight, tx_relay);
1531  
1532      if (fLogIPs) {
1533          LogDebug(BCLog::NET, "send version message: version %d, blocks=%d, them=%s, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addr_you.ToStringAddrPort(), tx_relay, nodeid);
1534      } else {
1535          LogDebug(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid);
1536      }
1537  }
1538  
1539  void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
1540  {
1541      LOCK(cs_main);
1542      CNodeState *state = State(node);
1543      if (state) state->m_last_block_announcement = time_in_seconds;
1544  }
1545  
1546  void PeerManagerImpl::InitializeNode(const CNode& node, ServiceFlags our_services)
1547  {
1548      NodeId nodeid = node.GetId();
1549      {
1550          LOCK(cs_main); // For m_node_states
1551          m_node_states.try_emplace(m_node_states.end(), nodeid);
1552      }
1553      WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty(nodeid));
1554  
1555      if (NetPermissions::HasFlag(node.m_permission_flags, NetPermissionFlags::BloomFilter)) {
1556          our_services = static_cast<ServiceFlags>(our_services | NODE_BLOOM);
1557      }
1558      if (NetPermissions::HasFlag(node.m_permission_flags, NetPermissionFlags::BlockFilters)) {
1559          our_services = static_cast<ServiceFlags>(our_services | NODE_COMPACT_FILTERS);
1560      }
1561  
1562      PeerRef peer = std::make_shared<Peer>(nodeid, our_services, node.IsInboundConn());
1563      {
1564          LOCK(m_peer_mutex);
1565          m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
1566      }
1567  }
1568  
1569  void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler)
1570  {
1571      std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs();
1572  
1573      for (const auto& txid : unbroadcast_txids) {
1574          CTransactionRef tx = m_mempool.get(txid);
1575  
1576          if (tx != nullptr) {
1577              RelayTransaction(txid, tx->GetWitnessHash());
1578          } else {
1579              m_mempool.RemoveUnbroadcastTx(txid, true);
1580          }
1581      }
1582  
1583      // Schedule next run for 10-15 minutes in the future.
1584      // We add randomness on every cycle to avoid the possibility of P2P fingerprinting.
1585      const auto delta = 10min + FastRandomContext().randrange<std::chrono::milliseconds>(5min);
1586      scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1587  }
1588  
1589  void PeerManagerImpl::FinalizeNode(const CNode& node)
1590  {
1591      NodeId nodeid = node.GetId();
1592      {
1593      LOCK(cs_main);
1594      {
1595          // We remove the PeerRef from g_peer_map here, but we don't always
1596          // destruct the Peer. Sometimes another thread is still holding a
1597          // PeerRef, so the refcount is >= 1. Be careful not to do any
1598          // processing here that assumes Peer won't be changed before it's
1599          // destructed.
1600          PeerRef peer = RemovePeer(nodeid);
1601          assert(peer != nullptr);
1602          m_wtxid_relay_peers -= peer->m_wtxid_relay;
1603          assert(m_wtxid_relay_peers >= 0);
1604          // Decrement non-BIP110 counter if this was a non-BIP110 outbound peer
1605          if (node.m_is_non_bip110_outbound) {
1606              assert(m_num_non_bip110_outbound > 0);
1607              --m_num_non_bip110_outbound;
1608          }
1609      }
1610      CNodeState *state = State(nodeid);
1611      assert(state != nullptr);
1612  
1613      if (state->fSyncStarted)
1614          nSyncStarted--;
1615  
1616      for (const QueuedBlock& entry : state->vBlocksInFlight) {
1617          auto range = mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash());
1618          while (range.first != range.second) {
1619              auto [node_id, list_it] = range.first->second;
1620              if (node_id != nodeid) {
1621                  range.first++;
1622              } else {
1623                  range.first = mapBlocksInFlight.erase(range.first);
1624              }
1625          }
1626      }
1627      {
1628          LOCK(m_tx_download_mutex);
1629          m_txdownloadman.DisconnectedPeer(nodeid);
1630      }
1631      if (m_txreconciliation) m_txreconciliation->ForgetPeer(nodeid);
1632      m_num_preferred_download_peers -= state->fPreferredDownload;
1633      m_peers_downloading_from -= (!state->vBlocksInFlight.empty());
1634      assert(m_peers_downloading_from >= 0);
1635      m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
1636      assert(m_outbound_peers_with_protect_from_disconnect >= 0);
1637  
1638      m_node_states.erase(nodeid);
1639  
1640      if (m_node_states.empty()) {
1641          // Do a consistency check after the last peer is removed.
1642          assert(mapBlocksInFlight.empty());
1643          assert(m_num_preferred_download_peers == 0);
1644          assert(m_peers_downloading_from == 0);
1645          assert(m_outbound_peers_with_protect_from_disconnect == 0);
1646          assert(m_wtxid_relay_peers == 0);
1647          WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty());
1648      }
1649      } // cs_main
1650      if (node.fSuccessfullyConnected &&
1651          !node.IsBlockOnlyConn() && !node.IsInboundConn()) {
1652          // Only change visible addrman state for full outbound peers.  We don't
1653          // call Connected() for feeler connections since they don't have
1654          // fSuccessfullyConnected set.
1655          m_addrman.Connected(node.addr);
1656      }
1657      {
1658          LOCK(m_headers_presync_mutex);
1659          m_headers_presync_stats.erase(nodeid);
1660      }
1661      LogDebug(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
1662  }
1663  
1664  bool PeerManagerImpl::HasAllDesirableServiceFlags(ServiceFlags services) const
1665  {
1666      // Shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services)
1667      return !(GetDesirableServiceFlags(services) & (~services));
1668  }
1669  
1670  ServiceFlags PeerManagerImpl::GetDesirableServiceFlags(ServiceFlags services) const
1671  {
1672      if (services & NODE_NETWORK_LIMITED) {
1673          // Limited peers are desirable when we are close to the tip.
1674          if (ApproximateBestBlockDepth() < NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS) {
1675              return ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS);
1676          }
1677      }
1678      return ServiceFlags(NODE_NETWORK | NODE_WITNESS);
1679  }
1680  
1681  PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const
1682  {
1683      LOCK(m_peer_mutex);
1684      auto it = m_peer_map.find(id);
1685      return it != m_peer_map.end() ? it->second : nullptr;
1686  }
1687  
1688  PeerRef PeerManagerImpl::RemovePeer(NodeId id)
1689  {
1690      PeerRef ret;
1691      LOCK(m_peer_mutex);
1692      auto it = m_peer_map.find(id);
1693      if (it != m_peer_map.end()) {
1694          ret = std::move(it->second);
1695          m_peer_map.erase(it);
1696      }
1697      return ret;
1698  }
1699  
1700  int PeerManagerImpl::GetNumberOfPeersWithValidatedDownloads() const
1701  {
1702      AssertLockHeld(m_chainman.GetMutex());
1703      return m_peers_downloading_from;
1704  }
1705  
1706  bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const
1707  {
1708      {
1709          LOCK(cs_main);
1710          const CNodeState* state = State(nodeid);
1711          if (state == nullptr)
1712              return false;
1713          stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
1714          stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
1715          for (const QueuedBlock& queue : state->vBlocksInFlight) {
1716              if (queue.pindex)
1717                  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
1718          }
1719          stats.m_last_block_announcement = NodeSeconds{std::chrono::seconds{state->m_last_block_announcement}};
1720      }
1721  
1722      PeerRef peer = GetPeerRef(nodeid);
1723      if (peer == nullptr) return false;
1724      stats.their_services = peer->m_their_services;
1725      stats.m_starting_height = peer->m_starting_height;
1726      // It is common for nodes with good ping times to suddenly become lagged,
1727      // due to a new block arriving or other large transfer.
1728      // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
1729      // since pingtime does not update until the ping is complete, which might take a while.
1730      // So, if a ping is taking an unusually long time in flight,
1731      // the caller can immediately detect that this is happening.
1732      auto ping_wait{0us};
1733      if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) {
1734          ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
1735      }
1736  
1737      if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
1738          stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs);
1739          stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load();
1740      } else {
1741          stats.m_relay_txs = false;
1742          stats.m_fee_filter_received = 0;
1743      }
1744  
1745      stats.m_ping_wait = ping_wait;
1746      stats.m_addr_processed = peer->m_addr_processed.load();
1747      stats.m_addr_rate_limited = peer->m_addr_rate_limited.load();
1748      stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load();
1749      {
1750          LOCK(peer->m_headers_sync_mutex);
1751          if (peer->m_headers_sync) {
1752              stats.presync_height = peer->m_headers_sync->GetPresyncHeight();
1753          }
1754      }
1755      stats.time_offset = peer->m_time_offset;
1756      stats.m_misbehavior_score = WITH_LOCK(peer->m_misbehavior_mutex, return peer->m_should_discourage) ? 100 : 0;
1757  
1758      return true;
1759  }
1760  
1761  std::vector<TxOrphanage::OrphanTxBase> PeerManagerImpl::GetOrphanTransactions()
1762  {
1763      LOCK(m_tx_download_mutex);
1764      return m_txdownloadman.GetOrphanTransactions();
1765  }
1766  
1767  PeerManagerInfo PeerManagerImpl::GetInfo() const
1768  {
1769      return PeerManagerInfo{
1770          .median_outbound_time_offset = m_outbound_time_offsets.Median(),
1771          .ignores_incoming_txs = m_opts.ignore_incoming_txs,
1772      };
1773  }
1774  
1775  void PeerManagerImpl::LimitOrphanTxSize(uint32_t nMaxOrphans)
1776  {
1777      LOCK(g_msgproc_mutex);
1778      LOCK2(cs_main, m_tx_download_mutex);
1779      m_txdownloadman.SetMaxOrphanTxs(nMaxOrphans);
1780  }
1781  
1782  void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx, const size_t tx_dynamic_usage)
1783  {
1784      if (m_opts.max_extra_txs <= 0)
1785          return;
1786      if (!vExtraTxnForCompact.size())
1787          vExtraTxnForCompact.resize(m_opts.max_extra_txs);
1788  
1789      {
1790          auto& entry = vExtraTxnForCompact[vExtraTxnForCompactIt];
1791          if (entry) blockreconstructionextratxn_memusage -= RecursiveDynamicUsage(*entry);
1792          entry = tx;
1793          blockreconstructionextratxn_memusage += tx_dynamic_usage;
1794      }
1795      vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs;
1796  
1797      while (blockreconstructionextratxn_memusage > m_opts.max_extra_txs_size) {
1798          auto& entry = vExtraTxnForCompact[vExtraTxnForCompactIt];
1799          if (entry) blockreconstructionextratxn_memusage -= RecursiveDynamicUsage(*entry);
1800          entry.reset();
1801          vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs;
1802      }
1803  }
1804  
1805  void PeerManagerImpl::Misbehaving(Peer& peer, const std::string& message)
1806  {
1807      LOCK(peer.m_misbehavior_mutex);
1808  
1809      const std::string message_prefixed = message.empty() ? "" : (": " + message);
1810      peer.m_should_discourage = true;
1811      LogDebug(BCLog::NET, "Misbehaving: peer=%d%s\n", peer.m_id, message_prefixed);
1812      TRACEPOINT(net, misbehaving_connection,
1813          peer.m_id,
1814          message.c_str()
1815      );
1816  }
1817  
1818  static void HandleDoSPunishment(CConnman& connman, NodeId node_id, const int nDoS, const char * const what_is_it) {
1819      // We never actually DoS ban for invalid blocks, merely disconnect nodes if we're relying on them as a primary node
1820      const std::string msg = strprintf("peer=%d got DoS score %d on invalid %s", node_id, nDoS, what_is_it);
1821      connman.ForNode(node_id, [msg](CNode* node) {
1822          if (node->PunishInvalidBlocks()) {
1823              LogDebug(BCLog::NET, "%s; simply disconnecting\n", msg);
1824              node->fDisconnect = true;
1825          } else {
1826              LogDebug(BCLog::NET, "%s; tolerating\n", msg);
1827          }
1828          return true;
1829      });
1830  }
1831  
1832  void PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
1833                                                bool via_compact_block, const std::string& message)
1834  {
1835      switch (state.GetResult()) {
1836      case BlockValidationResult::BLOCK_RESULT_UNSET:
1837          break;
1838      case BlockValidationResult::BLOCK_HEADER_LOW_WORK:
1839          // We didn't try to process the block because the header chain may have
1840          // too little work.
1841          break;
1842      // The node is providing invalid data:
1843      case BlockValidationResult::BLOCK_CONSENSUS:
1844      case BlockValidationResult::BLOCK_MUTATED:
1845          if (!via_compact_block) {
1846              HandleDoSPunishment(m_connman, nodeid, 100, "block");
1847              return;
1848          }
1849          break;
1850      case BlockValidationResult::BLOCK_CACHED_INVALID:
1851          {
1852              // Discourage outbound (but not inbound) peers if on an invalid chain.
1853              // Exempt HB compact block peers. Manual connections are always protected from discouragement.
1854              if (!via_compact_block) {
1855                  HandleDoSPunishment(m_connman, nodeid, 100, "block");
1856                  return;
1857              }
1858              break;
1859          }
1860      case BlockValidationResult::BLOCK_INVALID_HEADER:
1861      case BlockValidationResult::BLOCK_CHECKPOINT:
1862      case BlockValidationResult::BLOCK_INVALID_PREV:
1863          HandleDoSPunishment(m_connman, nodeid, 100, "block header");
1864          return;
1865      // Conflicting (but not necessarily invalid) data or different policy:
1866      case BlockValidationResult::BLOCK_MISSING_PREV:
1867          HandleDoSPunishment(m_connman, nodeid, 100, "block header");
1868          return;
1869      case BlockValidationResult::BLOCK_TIME_FUTURE:
1870          break;
1871      }
1872      if (message != "") {
1873          LogDebug(BCLog::NET, "peer=%d: %s\n", nodeid, message);
1874      }
1875  }
1876  
1877  bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
1878  {
1879      AssertLockHeld(cs_main);
1880      if (m_chainman.ActiveChain().Contains(pindex)) return true;
1881      return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (m_chainman.m_best_header != nullptr) &&
1882             (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
1883             (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
1884  }
1885  
1886  std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const uint256& hash, const CBlockIndex* block_index)
1887  {
1888      if (m_chainman.m_blockman.LoadingBlocks()) return "Loading blocks ...";
1889  
1890      // Ensure this peer exists and hasn't been disconnected
1891      PeerRef peer = GetPeerRef(peer_id);
1892      if (peer == nullptr) return "Peer does not exist";
1893  
1894      // Ignore pre-segwit peers
1895      if (!CanServeWitnesses(*peer)) return "Pre-SegWit peer";
1896  
1897      LOCK(cs_main);
1898  
1899      if (IsBlockRequestedFromPeer(hash, peer_id)) return "Already requested from this peer";
1900  
1901      // Mark block as in-flight unless we don't have the header.
1902      if (block_index != nullptr) {
1903      // Forget about all prior requests
1904      RemoveBlockRequest(hash, std::nullopt);
1905  
1906      // Mark block as in-flight
1907          Assume(BlockRequested(peer_id, *block_index));
1908      }
1909  
1910      // Construct message to request the block
1911      std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)};
1912  
1913      // Send block request message to the peer
1914      bool success = m_connman.ForNode(peer_id, [this, &invs](CNode* node) {
1915          this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs);
1916          return true;
1917      });
1918  
1919      if (!success) return "Peer not fully connected";
1920  
1921      LogDebug(BCLog::NET, "Requesting block %s from peer=%d\n",
1922                   hash.ToString(), peer_id);
1923      return std::nullopt;
1924  }
1925  
1926  std::optional<std::string> PeerManager::FetchBlock(NodeId peer_id, const CBlockIndex& block_index)
1927  {
1928      const uint256& hash{block_index.GetBlockHash()};
1929      return FetchBlock(peer_id, hash, &block_index);
1930  }
1931  
1932  std::unique_ptr<PeerManager> PeerManager::make(CConnman& connman, AddrMan& addrman,
1933                                                 BanMan* banman, ChainstateManager& chainman,
1934                                                 CTxMemPool& pool, node::Warnings& warnings, Options opts)
1935  {
1936      return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman, pool, warnings, opts);
1937  }
1938  
1939  static_assert(CORE_INCREMENTAL_RELAY_FEE < DEFAULT_INCREMENTAL_RELAY_FEE, "Trinary logic for m_fee_filter_rounder is based on assumption that CORE_INCREMENTAL_RELAY_FEE is less than DEFAULT_INCREMENTAL_RELAY_FEE");
1940  PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman,
1941                                   BanMan* banman, ChainstateManager& chainman,
1942                                   CTxMemPool& pool, node::Warnings& warnings, Options opts)
1943      : m_rng{opts.deterministic_rng},
1944        m_fee_filter_rounder{CFeeRate{pool.m_opts.incremental_relay_feerate.GetFeePerK() < DEFAULT_INCREMENTAL_RELAY_FEE ? CORE_INCREMENTAL_RELAY_FEE : DEFAULT_INCREMENTAL_RELAY_FEE}, m_rng},
1945        m_chainparams(chainman.GetParams()),
1946        m_connman(connman),
1947        m_addrman(addrman),
1948        m_banman(banman),
1949        m_chainman(chainman),
1950        m_mempool(pool),
1951        m_txdownloadman(node::TxDownloadOptions{pool, m_rng, opts.max_orphan_txs, opts.deterministic_rng}),
1952        m_warnings{warnings},
1953        m_opts{opts}
1954  {
1955      // While Erlay support is incomplete, it must be enabled explicitly via -txreconciliation.
1956      // This argument can go away after Erlay support is complete.
1957      if (opts.reconcile_txs) {
1958          m_txreconciliation = std::make_unique<TxReconciliationTracker>(TXRECONCILIATION_VERSION);
1959      }
1960  }
1961  
1962  void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler)
1963  {
1964      // Stale tip checking and peer eviction are on two different timers, but we
1965      // don't want them to get out of sync due to drift in the scheduler, so we
1966      // combine them in one function and schedule at the quicker (peer-eviction)
1967      // timer.
1968      static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
1969      scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL});
1970  
1971      // schedule next run for 10-15 minutes in the future
1972      const auto delta = 10min + FastRandomContext().randrange<std::chrono::milliseconds>(5min);
1973      scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1974  }
1975  
1976  void PeerManagerImpl::ActiveTipChange(const CBlockIndex& new_tip, bool is_ibd)
1977  {
1978      // Ensure mempool mutex was released, otherwise deadlock may occur if another thread holding
1979      // m_tx_download_mutex waits on the mempool mutex.
1980      AssertLockNotHeld(m_mempool.cs);
1981      AssertLockNotHeld(m_tx_download_mutex);
1982  
1983      if (!is_ibd) {
1984          LOCK(m_tx_download_mutex);
1985          // If the chain tip has changed, previously rejected transactions might now be valid, e.g. due
1986          // to a timelock. Reset the rejection filters to give those transactions another chance if we
1987          // see them again.
1988          m_txdownloadman.ActiveTipChange();
1989      }
1990  }
1991  
1992  /**
1993   * Evict orphan txn pool entries based on a newly connected
1994   * block, remember the recently confirmed transactions, and delete tracked
1995   * announcements for them. Also save the time of the last tip update and
1996   * possibly reduce dynamic block stalling timeout.
1997   */
1998  void PeerManagerImpl::BlockConnected(
1999      ChainstateRole role,
2000      const std::shared_ptr<const CBlock>& pblock,
2001      const CBlockIndex* pindex)
2002  {
2003      // Update this for all chainstate roles so that we don't mistakenly see peers
2004      // helping us do background IBD as having a stale tip.
2005      m_last_tip_update = GetTime<std::chrono::seconds>();
2006  
2007      // In case the dynamic timeout was doubled once or more, reduce it slowly back to its default value
2008      auto stalling_timeout = m_block_stalling_timeout.load();
2009      Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT);
2010      if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) {
2011          const auto new_timeout = std::max(std::chrono::duration_cast<std::chrono::seconds>(stalling_timeout * 0.85), BLOCK_STALLING_TIMEOUT_DEFAULT);
2012          if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) {
2013              LogDebug(BCLog::NET, "Decreased stalling timeout to %d seconds\n", count_seconds(new_timeout));
2014          }
2015      }
2016  
2017      // The following task can be skipped since we don't maintain a mempool for
2018      // the ibd/background chainstate.
2019      if (role == ChainstateRole::BACKGROUND) {
2020          return;
2021      }
2022      LOCK(m_tx_download_mutex);
2023      m_txdownloadman.BlockConnected(pblock);
2024  }
2025  
2026  void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex)
2027  {
2028      LOCK(m_tx_download_mutex);
2029      m_txdownloadman.BlockDisconnected();
2030  }
2031  
2032  /**
2033   * Maintain state about the best-seen block and fast-announce a compact block
2034   * to compatible peers.
2035   */
2036  void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)
2037  {
2038      auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock, FastRandomContext().rand64());
2039  
2040      LOCK(cs_main);
2041  
2042      if (pindex->nHeight <= m_highest_fast_announce)
2043          return;
2044      m_highest_fast_announce = pindex->nHeight;
2045  
2046      if (!DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) return;
2047  
2048      uint256 hashBlock(pblock->GetHash());
2049      const std::shared_future<CSerializedNetMsg> lazy_ser{
2050          std::async(std::launch::deferred, [&] { return NetMsg::Make(NetMsgType::CMPCTBLOCK, *pcmpctblock); })};
2051  
2052      {
2053          auto most_recent_block_txs = std::make_unique<std::map<uint256, CTransactionRef>>();
2054          for (const auto& tx : pblock->vtx) {
2055              most_recent_block_txs->emplace(tx->GetHash(), tx);
2056              most_recent_block_txs->emplace(tx->GetWitnessHash(), tx);
2057          }
2058  
2059          LOCK(m_most_recent_block_mutex);
2060          m_most_recent_block_hash = hashBlock;
2061          m_most_recent_block = pblock;
2062          m_most_recent_compact_block = pcmpctblock;
2063          m_most_recent_block_txs = std::move(most_recent_block_txs);
2064      }
2065  
2066      m_connman.ForEachNode([this, pindex, &lazy_ser, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
2067          AssertLockHeld(::cs_main);
2068  
2069          if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
2070              return;
2071          ProcessBlockAvailability(pnode->GetId());
2072          CNodeState &state = *State(pnode->GetId());
2073          // If the peer has, or we announced to them the previous block already,
2074          // but we don't think they have this one, go ahead and announce it
2075          if (state.m_requested_hb_cmpctblocks && !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
2076  
2077              LogDebug(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock",
2078                      hashBlock.ToString(), pnode->GetId());
2079  
2080              const CSerializedNetMsg& ser_cmpctblock{lazy_ser.get()};
2081              PushMessage(*pnode, ser_cmpctblock.Copy());
2082              state.pindexBestHeaderSent = pindex;
2083          }
2084      });
2085  }
2086  
2087  /**
2088   * Update our best height and announce any block hashes which weren't previously
2089   * in m_chainman.ActiveChain() to our peers.
2090   */
2091  void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
2092  {
2093      SetBestBlock(pindexNew->nHeight, std::chrono::seconds{pindexNew->GetBlockTime()});
2094  
2095      // Don't relay inventory during initial block download.
2096      if (fInitialDownload) return;
2097  
2098      // Find the hashes of all blocks that weren't previously in the best chain.
2099      std::vector<uint256> vHashes;
2100      const CBlockIndex *pindexToAnnounce = pindexNew;
2101      while (pindexToAnnounce != pindexFork) {
2102          vHashes.push_back(pindexToAnnounce->GetBlockHash());
2103          pindexToAnnounce = pindexToAnnounce->pprev;
2104          if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
2105              // Limit announcements in case of a huge reorganization.
2106              // Rely on the peer's synchronization mechanism in that case.
2107              break;
2108          }
2109      }
2110  
2111      {
2112          LOCK(m_peer_mutex);
2113          for (auto& it : m_peer_map) {
2114              Peer& peer = *it.second;
2115              LOCK(peer.m_block_inv_mutex);
2116              for (const uint256& hash : vHashes | std::views::reverse) {
2117                  peer.m_blocks_for_headers_relay.push_back(hash);
2118              }
2119          }
2120      }
2121  
2122      m_connman.WakeMessageHandler();
2123  }
2124  
2125  /**
2126   * Handle invalid block rejection and consequent peer discouragement, maintain which
2127   * peers announce compact blocks.
2128   */
2129  void PeerManagerImpl::BlockChecked(const CBlock& block, const BlockValidationState& state)
2130  {
2131      LOCK(cs_main);
2132  
2133      const uint256 hash(block.GetHash());
2134      std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
2135  
2136      // If the block failed validation, we know where it came from and we're still connected
2137      // to that peer, maybe punish.
2138      if (state.IsInvalid() &&
2139          it != mapBlockSource.end() &&
2140          State(it->second.first)) {
2141              MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second);
2142      }
2143      // Check that:
2144      // 1. The block is valid
2145      // 2. We're not in initial block download
2146      // 3. This is currently the best block we're aware of. We haven't updated
2147      //    the tip yet so we have no way to check this directly here. Instead we
2148      //    just check that there are currently no other blocks in flight.
2149      else if (state.IsValid() &&
2150               !m_chainman.IsInitialBlockDownload() &&
2151               mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
2152          if (it != mapBlockSource.end()) {
2153              MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
2154          }
2155      }
2156      if (it != mapBlockSource.end())
2157          mapBlockSource.erase(it);
2158  }
2159  
2160  //////////////////////////////////////////////////////////////////////////////
2161  //
2162  // Messages
2163  //
2164  
2165  bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash)
2166  {
2167      return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
2168  }
2169  
2170  void PeerManagerImpl::SendPings()
2171  {
2172      LOCK(m_peer_mutex);
2173      for(auto& it : m_peer_map) it.second->m_ping_queued = true;
2174  }
2175  
2176  void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid)
2177  {
2178      LOCK(m_peer_mutex);
2179      for(auto& it : m_peer_map) {
2180          Peer& peer = *it.second;
2181          auto tx_relay = peer.GetTxRelay();
2182          if (!tx_relay) continue;
2183  
2184          LOCK(tx_relay->m_tx_inventory_mutex);
2185          // Only queue transactions for announcement once the version handshake
2186          // is completed. The time of arrival for these transactions is
2187          // otherwise at risk of leaking to a spy, if the spy is able to
2188          // distinguish transactions received during the handshake from the rest
2189          // in the announcement.
2190          if (tx_relay->m_next_inv_send_time == 0s) continue;
2191  
2192          const uint256& hash{peer.m_wtxid_relay ? wtxid : txid};
2193          if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) {
2194              tx_relay->m_tx_inventory_to_send.insert(hash);
2195          }
2196      };
2197  }
2198  
2199  void PeerManagerImpl::RelayAddress(NodeId originator,
2200                                     const CAddress& addr,
2201                                     bool fReachable)
2202  {
2203      // We choose the same nodes within a given 24h window (if the list of connected
2204      // nodes does not change) and we don't relay to nodes that already know an
2205      // address. So within 24h we will likely relay a given address once. This is to
2206      // prevent a peer from unjustly giving their address better propagation by sending
2207      // it to us repeatedly.
2208  
2209      if (!fReachable && !addr.IsRelayable()) return;
2210  
2211      // Relay to a limited number of other nodes
2212      // Use deterministic randomness to send to the same nodes for 24 hours
2213      // at a time so the m_addr_knowns of the chosen nodes prevent repeats
2214      const uint64_t hash_addr{CServiceHash(0, 0)(addr)};
2215      const auto current_time{GetTime<std::chrono::seconds>()};
2216      // Adding address hash makes exact rotation time different per address, while preserving periodicity.
2217      const uint64_t time_addr{(static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) / count_seconds(ROTATE_ADDR_RELAY_DEST_INTERVAL)};
2218      const CSipHasher hasher{m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY)
2219                                  .Write(hash_addr)
2220                                  .Write(time_addr)};
2221  
2222      // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers.
2223      unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
2224  
2225      std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}};
2226      assert(nRelayNodes <= best.size());
2227  
2228      LOCK(m_peer_mutex);
2229  
2230      for (auto& [id, peer] : m_peer_map) {
2231          if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) {
2232              uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
2233              for (unsigned int i = 0; i < nRelayNodes; i++) {
2234                   if (hashKey > best[i].first) {
2235                       std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
2236                       best[i] = std::make_pair(hashKey, peer.get());
2237                       break;
2238                   }
2239              }
2240          }
2241      };
2242  
2243      for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
2244          PushAddress(*best[i].second, addr);
2245      }
2246  }
2247  
2248  void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
2249  {
2250      std::shared_ptr<const CBlock> a_recent_block;
2251      std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
2252      {
2253          LOCK(m_most_recent_block_mutex);
2254          a_recent_block = m_most_recent_block;
2255          a_recent_compact_block = m_most_recent_compact_block;
2256      }
2257  
2258      bool need_activate_chain = false;
2259      {
2260          LOCK(cs_main);
2261          const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
2262          if (pindex) {
2263              if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
2264                      pindex->IsValid(BLOCK_VALID_TREE)) {
2265                  // If we have the block and all of its parents, but have not yet validated it,
2266                  // we might be in the middle of connecting it (ie in the unlock of cs_main
2267                  // before ActivateBestChain but after AcceptBlock).
2268                  // In this case, we need to run ActivateBestChain prior to checking the relay
2269                  // conditions below.
2270                  need_activate_chain = true;
2271              }
2272          }
2273      } // release cs_main before calling ActivateBestChain
2274      if (need_activate_chain) {
2275          BlockValidationState state;
2276          if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
2277              LogDebug(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
2278          }
2279      }
2280  
2281      const CBlockIndex* pindex{nullptr};
2282      const CBlockIndex* tip{nullptr};
2283      bool can_direct_fetch{false};
2284      FlatFilePos block_pos{};
2285      {
2286          LOCK(cs_main);
2287          pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
2288          if (!pindex) {
2289              return;
2290          }
2291          if (!BlockRequestAllowed(pindex)) {
2292              LogDebug(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId());
2293              return;
2294          }
2295          // disconnect node in case we have reached the outbound limit for serving historical blocks
2296          if (m_connman.OutboundTargetReached(true) &&
2297              (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk() || inv.IsMsgFilteredWitnessBlk()) &&
2298              !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target
2299          ) {
2300              LogDebug(BCLog::NET, "historical block serving limit reached, %s\n", pfrom.DisconnectMsg(fLogIPs));
2301              pfrom.fDisconnect = true;
2302              return;
2303          }
2304          tip = m_chainman.ActiveChain().Tip();
2305          // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
2306          if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && (
2307                  (((peer.m_our_services & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) && (tip->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
2308             )) {
2309              LogDebug(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, %s\n", pfrom.DisconnectMsg(fLogIPs));
2310              //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
2311              pfrom.fDisconnect = true;
2312              return;
2313          }
2314          // Pruned nodes may have deleted the block, so check whether
2315          // it's available before trying to send.
2316          if (!(pindex->nStatus & BLOCK_HAVE_DATA)) {
2317              return;
2318          }
2319          can_direct_fetch = CanDirectFetch();
2320          block_pos = pindex->GetBlockPos();
2321      }
2322  
2323      std::shared_ptr<const CBlock> pblock;
2324      if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
2325          pblock = a_recent_block;
2326      } else if (inv.IsMsgWitnessBlk()) {
2327          // Fast-path: in this case it is possible to serve the block directly from disk,
2328          // as the network format matches the format on disk
2329          std::vector<uint8_t> block_data;
2330          if (!m_chainman.m_blockman.ReadRawBlock(block_data, block_pos, /*lowprio=*/true)) {
2331              if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) {
2332                  LogDebug(BCLog::NET, "Block was pruned before it could be read, %s\n", pfrom.DisconnectMsg(fLogIPs));
2333              } else {
2334                  LogError("Cannot load block from disk, %s\n", pfrom.DisconnectMsg(fLogIPs));
2335              }
2336              pfrom.fDisconnect = true;
2337              return;
2338          }
2339          MakeAndPushMessage(pfrom, NetMsgType::BLOCK, Span{block_data});
2340          // Don't set pblock as we've sent the block
2341      } else {
2342          // Send block from disk
2343          std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
2344          if (!m_chainman.m_blockman.ReadBlock(*pblockRead, block_pos, /*expected_hash=*/ inv.hash, /*lowprio=*/true)) {
2345              if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) {
2346                  LogDebug(BCLog::NET, "Block was pruned before it could be read, %s\n", pfrom.DisconnectMsg(fLogIPs));
2347              } else {
2348                  LogError("Cannot load block from disk, %s\n", pfrom.DisconnectMsg(fLogIPs));
2349              }
2350              pfrom.fDisconnect = true;
2351              return;
2352          }
2353          pblock = pblockRead;
2354      }
2355      if (pblock) {
2356          if (inv.IsMsgBlk()) {
2357              MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_NO_WITNESS(*pblock));
2358          } else if (inv.IsMsgWitnessBlk()) {
2359              MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock));
2360          } else if (inv.IsMsgFilteredBlk() || inv.IsMsgFilteredWitnessBlk()) {
2361              bool sendMerkleBlock = false;
2362              CMerkleBlock merkleBlock;
2363              if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
2364                  LOCK(tx_relay->m_bloom_filter_mutex);
2365                  if (tx_relay->m_bloom_filter) {
2366                      sendMerkleBlock = true;
2367                      merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
2368                  }
2369              }
2370              if (sendMerkleBlock) {
2371                  MakeAndPushMessage(pfrom, NetMsgType::MERKLEBLOCK, merkleBlock);
2372                  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
2373                  // This avoids hurting performance by pointlessly requiring a round-trip
2374                  // Note that there is currently no way for a node to request any single transactions we didn't send here -
2375                  // they must either disconnect and retry or request the full block.
2376                  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
2377                  // however we MUST always provide at least what the remote peer needs
2378                  const auto maybe_with_witness = (inv.IsMsgFilteredWitnessBlk() ? TX_WITH_WITNESS : TX_NO_WITNESS);
2379                  typedef std::pair<unsigned int, uint256> PairType;
2380                  for (PairType& pair : merkleBlock.vMatchedTxn)
2381                      MakeAndPushMessage(pfrom, NetMsgType::TX, maybe_with_witness(*pblock->vtx[pair.first]));
2382              }
2383              // else
2384              // no response
2385          } else if (inv.IsMsgCmpctBlk()) {
2386              // If a peer is asking for old blocks, we're almost guaranteed
2387              // they won't have a useful mempool to match against a compact block,
2388              // and we don't feel like constructing the object for them, so
2389              // instead we respond with the full, non-compact block.
2390              if (can_direct_fetch && pindex->nHeight >= tip->nHeight - MAX_CMPCTBLOCK_DEPTH) {
2391                  if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
2392                      MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, *a_recent_compact_block);
2393                  } else {
2394                      CBlockHeaderAndShortTxIDs cmpctblock{*pblock, m_rng.rand64()};
2395                      MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, cmpctblock);
2396                  }
2397              } else {
2398                  MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock));
2399              }
2400          }
2401      }
2402  
2403      {
2404          LOCK(peer.m_block_inv_mutex);
2405          // Trigger the peer node to send a getblocks request for the next batch of inventory
2406          if (inv.hash == peer.m_continuation_block) {
2407              // Send immediately. This must send even if redundant,
2408              // and we want it right after the last block so they don't
2409              // wait for other stuff first.
2410              std::vector<CInv> vInv;
2411              vInv.emplace_back(MSG_BLOCK, tip->GetBlockHash());
2412              MakeAndPushMessage(pfrom, NetMsgType::INV, vInv);
2413              peer.m_continuation_block.SetNull();
2414          }
2415      }
2416  }
2417  
2418  CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid)
2419  {
2420      // If a tx was in the mempool prior to the last INV for this peer, permit the request.
2421      auto txinfo = m_mempool.info_for_relay(gtxid, tx_relay.m_last_inv_sequence);
2422      if (txinfo.tx) {
2423          return std::move(txinfo.tx);
2424      }
2425  
2426      // Or it might be from the most recent block
2427      {
2428          LOCK(m_most_recent_block_mutex);
2429          if (m_most_recent_block_txs != nullptr) {
2430              auto it = m_most_recent_block_txs->find(gtxid.GetHash());
2431              if (it != m_most_recent_block_txs->end()) return it->second;
2432          }
2433      }
2434  
2435      return {};
2436  }
2437  
2438  void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
2439  {
2440      AssertLockNotHeld(cs_main);
2441  
2442      auto tx_relay = peer.GetTxRelay();
2443  
2444      std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
2445      std::vector<CInv> vNotFound;
2446  
2447      // Process as many TX items from the front of the getdata queue as
2448      // possible, since they're common and it's efficient to batch process
2449      // them.
2450      while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) {
2451          if (interruptMsgProc) return;
2452          // The send buffer provides backpressure. If there's no space in
2453          // the buffer, pause processing until the next call.
2454          if (pfrom.fPauseSend) break;
2455  
2456          const CInv &inv = *it++;
2457  
2458          if (tx_relay == nullptr) {
2459              // Ignore GETDATA requests for transactions from block-relay-only
2460              // peers and peers that asked us not to announce transactions.
2461              continue;
2462          }
2463  
2464          CTransactionRef tx = FindTxForGetData(*tx_relay, ToGenTxid(inv));
2465          if (tx) {
2466              // WTX and WITNESS_TX imply we serialize with witness
2467              const auto maybe_with_witness = (inv.IsMsgTx() ? TX_NO_WITNESS : TX_WITH_WITNESS);
2468              MakeAndPushMessage(pfrom, NetMsgType::TX, maybe_with_witness(*tx));
2469              m_mempool.RemoveUnbroadcastTx(tx->GetHash());
2470          } else {
2471              vNotFound.push_back(inv);
2472          }
2473      }
2474  
2475      // Only process one BLOCK item per call, since they're uncommon and can be
2476      // expensive to process.
2477      if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
2478          const CInv &inv = *it++;
2479          if (inv.IsGenBlkMsg()) {
2480              ProcessGetBlockData(pfrom, peer, inv);
2481          }
2482          // else: If the first item on the queue is an unknown type, we erase it
2483          // and continue processing the queue on the next call.
2484      }
2485  
2486      peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
2487  
2488      if (!vNotFound.empty()) {
2489          // Let the peer know that we didn't find what it asked for, so it doesn't
2490          // have to wait around forever.
2491          // SPV clients care about this message: it's needed when they are
2492          // recursively walking the dependencies of relevant unconfirmed
2493          // transactions. SPV clients want to do that because they want to know
2494          // about (and store and rebroadcast and risk analyze) the dependencies
2495          // of transactions relevant to them, without having to download the
2496          // entire memory pool.
2497          // Also, other nodes can use these messages to automatically request a
2498          // transaction from some other peer that announced it, and stop
2499          // waiting for us to respond.
2500          // In normal operation, we often send NOTFOUND messages for parents of
2501          // transactions that we relay; if a peer is missing a parent, they may
2502          // assume we have them and request the parents from us.
2503          MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound);
2504      }
2505  }
2506  
2507  uint32_t PeerManagerImpl::GetFetchFlags(const Peer& peer) const
2508  {
2509      uint32_t nFetchFlags = 0;
2510      if (CanServeWitnesses(peer)) {
2511          nFetchFlags |= MSG_WITNESS_FLAG;
2512      }
2513      return nFetchFlags;
2514  }
2515  
2516  void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req)
2517  {
2518      BlockTransactions resp(req);
2519      for (size_t i = 0; i < req.indexes.size(); i++) {
2520          if (req.indexes[i] >= block.vtx.size()) {
2521              Misbehaving(peer, "getblocktxn with out-of-bounds tx indices");
2522              return;
2523          }
2524          resp.txn[i] = block.vtx[req.indexes[i]];
2525      }
2526  
2527      MakeAndPushMessage(pfrom, NetMsgType::BLOCKTXN, resp);
2528  }
2529  
2530  bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer)
2531  {
2532      // Do these headers have proof-of-work matching what's claimed?
2533      if (!HasValidProofOfWork(headers, consensusParams)) {
2534          Misbehaving(peer, "header with invalid proof of work");
2535          return false;
2536      }
2537  
2538      // Are these headers connected to each other?
2539      if (!CheckHeadersAreContinuous(headers)) {
2540          Misbehaving(peer, "non-continuous headers sequence");
2541          return false;
2542      }
2543      return true;
2544  }
2545  
2546  arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold()
2547  {
2548      arith_uint256 near_chaintip_work = 0;
2549      LOCK(cs_main);
2550      if (m_chainman.ActiveChain().Tip() != nullptr) {
2551          const CBlockIndex *tip = m_chainman.ActiveChain().Tip();
2552          // Use a 144 block buffer, so that we'll accept headers that fork from
2553          // near our tip.
2554          near_chaintip_work = tip->nChainWork - std::min<arith_uint256>(144*GetBlockProof(*tip), tip->nChainWork);
2555      }
2556      return std::max(near_chaintip_work, m_chainman.MinimumChainWork());
2557  }
2558  
2559  /**
2560   * Special handling for unconnecting headers that might be part of a block
2561   * announcement.
2562   *
2563   * We'll send a getheaders message in response to try to connect the chain.
2564   */
2565  void PeerManagerImpl::HandleUnconnectingHeaders(CNode& pfrom, Peer& peer,
2566          const std::vector<CBlockHeader>& headers)
2567  {
2568      // Try to fill in the missing headers.
2569      const CBlockIndex* best_header{WITH_LOCK(cs_main, return m_chainman.m_best_header)};
2570      if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) {
2571          LogDebug(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d)\n",
2572              headers[0].GetHash().ToString(),
2573              headers[0].hashPrevBlock.ToString(),
2574              best_header->nHeight,
2575              pfrom.GetId());
2576      }
2577  
2578      // Set hashLastUnknownBlock for this peer, so that if we
2579      // eventually get the headers - even from a different peer -
2580      // we can use this peer to download.
2581      WITH_LOCK(cs_main, UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash()));
2582  
2583      if (pfrom.PunishInvalidBlocks()) {
2584          pfrom.fDisconnect = true;
2585      }
2586  }
2587  
2588  bool PeerManagerImpl::CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const
2589  {
2590      uint256 hashLastBlock;
2591      for (const CBlockHeader& header : headers) {
2592          if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2593              return false;
2594          }
2595          hashLastBlock = header.GetHash();
2596      }
2597      return true;
2598  }
2599  
2600  bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers)
2601  {
2602      if (peer.m_headers_sync) {
2603          auto result = peer.m_headers_sync->ProcessNextHeaders(headers, headers.size() == m_opts.max_headers_result);
2604          // If it is a valid continuation, we should treat the existing getheaders request as responded to.
2605          if (result.success) peer.m_last_getheaders_timestamp = {};
2606          if (result.request_more) {
2607              auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
2608              // If we were instructed to ask for a locator, it should not be empty.
2609              Assume(!locator.vHave.empty());
2610              // We can only be instructed to request more if processing was successful.
2611              Assume(result.success);
2612              if (!locator.vHave.empty()) {
2613                  // It should be impossible for the getheaders request to fail,
2614                  // because we just cleared the last getheaders timestamp.
2615                  bool sent_getheaders = MaybeSendGetHeaders(pfrom, locator, peer);
2616                  Assume(sent_getheaders);
2617                  LogDebug(BCLog::NET, "more getheaders (from %s) to peer=%d\n",
2618                      locator.vHave.front().ToString(), pfrom.GetId());
2619              }
2620          }
2621  
2622          if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) {
2623              peer.m_headers_sync.reset(nullptr);
2624  
2625              // Delete this peer's entry in m_headers_presync_stats.
2626              // If this is m_headers_presync_bestpeer, it will be replaced later
2627              // by the next peer that triggers the else{} branch below.
2628              LOCK(m_headers_presync_mutex);
2629              m_headers_presync_stats.erase(pfrom.GetId());
2630          } else {
2631              // Build statistics for this peer's sync.
2632              HeadersPresyncStats stats;
2633              stats.first = peer.m_headers_sync->GetPresyncWork();
2634              if (peer.m_headers_sync->GetState() == HeadersSyncState::State::PRESYNC) {
2635                  stats.second = {peer.m_headers_sync->GetPresyncHeight(),
2636                                  peer.m_headers_sync->GetPresyncTime()};
2637              }
2638  
2639              // Update statistics in stats.
2640              LOCK(m_headers_presync_mutex);
2641              m_headers_presync_stats[pfrom.GetId()] = stats;
2642              auto best_it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
2643              bool best_updated = false;
2644              if (best_it == m_headers_presync_stats.end()) {
2645                  // If the cached best peer is outdated, iterate over all remaining ones (including
2646                  // newly updated one) to find the best one.
2647                  NodeId peer_best{-1};
2648                  const HeadersPresyncStats* stat_best{nullptr};
2649                  for (const auto& [peer, stat] : m_headers_presync_stats) {
2650                      if (!stat_best || stat > *stat_best) {
2651                          peer_best = peer;
2652                          stat_best = &stat;
2653                      }
2654                  }
2655                  m_headers_presync_bestpeer = peer_best;
2656                  best_updated = (peer_best == pfrom.GetId());
2657              } else if (best_it->first == pfrom.GetId() || stats > best_it->second) {
2658                  // pfrom was and remains the best peer, or pfrom just became best.
2659                  m_headers_presync_bestpeer = pfrom.GetId();
2660                  best_updated = true;
2661              }
2662              if (best_updated && stats.second.has_value()) {
2663                  // If the best peer updated, and it is in its first phase, signal.
2664                  m_headers_presync_should_signal = true;
2665              }
2666          }
2667  
2668          if (result.success) {
2669              // We only overwrite the headers passed in if processing was
2670              // successful.
2671              headers.swap(result.pow_validated_headers);
2672          }
2673  
2674          return result.success;
2675      }
2676      // Either we didn't have a sync in progress, or something went wrong
2677      // processing these headers, or we are returning headers to the caller to
2678      // process.
2679      return false;
2680  }
2681  
2682  bool PeerManagerImpl::TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex* chain_start_header, std::vector<CBlockHeader>& headers)
2683  {
2684      // Calculate the claimed total work on this chain.
2685      arith_uint256 total_work = chain_start_header->nChainWork + CalculateClaimedHeadersWork(headers);
2686  
2687      // Our dynamic anti-DoS threshold (minimum work required on a headers chain
2688      // before we'll store it)
2689      arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
2690  
2691      // Avoid DoS via low-difficulty-headers by only processing if the headers
2692      // are part of a chain with sufficient work.
2693      if (total_work < minimum_chain_work) {
2694          // Only try to sync with this peer if their headers message was full;
2695          // otherwise they don't have more headers after this so no point in
2696          // trying to sync their too-little-work chain.
2697          if (headers.size() == m_opts.max_headers_result) {
2698              // Note: we could advance to the last header in this set that is
2699              // known to us, rather than starting at the first header (which we
2700              // may already have); however this is unlikely to matter much since
2701              // ProcessHeadersMessage() already handles the case where all
2702              // headers in a received message are already known and are
2703              // ancestors of m_best_header or chainActive.Tip(), by skipping
2704              // this logic in that case. So even if the first header in this set
2705              // of headers is known, some header in this set must be new, so
2706              // advancing to the first unknown header would be a small effect.
2707              LOCK(peer.m_headers_sync_mutex);
2708              peer.m_headers_sync.reset(new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(),
2709                  chain_start_header, minimum_chain_work));
2710  
2711              // Now a HeadersSyncState object for tracking this synchronization
2712              // is created, process the headers using it as normal. Failures are
2713              // handled inside of IsContinuationOfLowWorkHeadersSync.
2714              (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
2715          } else {
2716              LogDebug(BCLog::NET, "Ignoring low-work chain (height=%u) from peer=%d\n", chain_start_header->nHeight + headers.size(), pfrom.GetId());
2717          }
2718  
2719          // The peer has not yet given us a chain that meets our work threshold,
2720          // so we want to prevent further processing of the headers in any case.
2721          headers = {};
2722          return true;
2723      }
2724  
2725      return false;
2726  }
2727  
2728  bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex* header)
2729  {
2730      if (header == nullptr) {
2731          return false;
2732      } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) {
2733          return true;
2734      } else if (m_chainman.ActiveChain().Contains(header)) {
2735          return true;
2736      }
2737      return false;
2738  }
2739  
2740  bool PeerManagerImpl::MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer)
2741  {
2742      const auto current_time = NodeClock::now();
2743  
2744      // Only allow a new getheaders message to go out if we don't have a recent
2745      // one already in-flight
2746      if (current_time - peer.m_last_getheaders_timestamp > HEADERS_RESPONSE_TIME) {
2747          MakeAndPushMessage(pfrom, NetMsgType::GETHEADERS, locator, uint256());
2748          peer.m_last_getheaders_timestamp = current_time;
2749          return true;
2750      }
2751      return false;
2752  }
2753  
2754  /*
2755   * Given a new headers tip ending in last_header, potentially request blocks towards that tip.
2756   * We require that the given tip have at least as much work as our tip, and for
2757   * our current tip to be "close to synced" (see CanDirectFetch()).
2758   */
2759  void PeerManagerImpl::HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header)
2760  {
2761      LOCK(cs_main);
2762      CNodeState *nodestate = State(pfrom.GetId());
2763  
2764      if (CanDirectFetch() && last_header.IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork) {
2765          std::vector<const CBlockIndex*> vToFetch;
2766          const CBlockIndex* pindexWalk{&last_header};
2767          // Calculate all the blocks we'd need to switch to last_header, up to a limit.
2768          while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2769              if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
2770                      !IsBlockRequested(pindexWalk->GetBlockHash()) &&
2771                      (!DeploymentActiveAt(*pindexWalk, m_chainman, Consensus::DEPLOYMENT_SEGWIT) || CanServeWitnesses(peer))) {
2772                  // We don't have this block, and it's not yet in flight.
2773                  vToFetch.push_back(pindexWalk);
2774              }
2775              pindexWalk = pindexWalk->pprev;
2776          }
2777          // If pindexWalk still isn't on our main chain, we're looking at a
2778          // very large reorg at a time we think we're close to caught up to
2779          // the main chain -- this shouldn't really happen.  Bail out on the
2780          // direct fetch and rely on parallel download instead.
2781          if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
2782              LogDebug(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
2783                       last_header.GetBlockHash().ToString(),
2784                       last_header.nHeight);
2785          } else {
2786              std::vector<CInv> vGetData;
2787              // Download as much as possible, from earliest to latest.
2788              for (const CBlockIndex* pindex : vToFetch | std::views::reverse) {
2789                  if (nodestate->vBlocksInFlight.size() >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2790                      // Can't download any more from this peer
2791                      break;
2792                  }
2793                  uint32_t nFetchFlags = GetFetchFlags(peer);
2794                  vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash());
2795                  BlockRequested(pfrom.GetId(), *pindex);
2796                  LogDebug(BCLog::NET, "Requesting block %s from  peer=%d\n",
2797                          pindex->GetBlockHash().ToString(), pfrom.GetId());
2798              }
2799              if (vGetData.size() > 1) {
2800                  LogDebug(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2801                           last_header.GetBlockHash().ToString(),
2802                           last_header.nHeight);
2803              }
2804              if (vGetData.size() > 0) {
2805                  if (!m_opts.ignore_incoming_txs &&
2806                          nodestate->m_provides_cmpctblocks &&
2807                          vGetData.size() == 1 &&
2808                          mapBlocksInFlight.size() == 1 &&
2809                          last_header.pprev->IsValid(BLOCK_VALID_CHAIN)) {
2810                      // In any case, we want to download using a compact block, not a regular one
2811                      vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
2812                  }
2813                  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vGetData);
2814              }
2815          }
2816      }
2817  }
2818  
2819  /**
2820   * Given receipt of headers from a peer ending in last_header, along with
2821   * whether that header was new and whether the headers message was full,
2822   * update the state we keep for the peer.
2823   */
2824  void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer,
2825          const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers)
2826  {
2827      LOCK(cs_main);
2828      CNodeState *nodestate = State(pfrom.GetId());
2829  
2830      UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash());
2831  
2832      // From here, pindexBestKnownBlock should be guaranteed to be non-null,
2833      // because it is set in UpdateBlockAvailability. Some nullptr checks
2834      // are still present, however, as belt-and-suspenders.
2835  
2836      if (received_new_header && last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
2837          nodestate->m_last_block_announcement = GetTime();
2838      }
2839  
2840      // If we're in IBD, we want outbound peers that will serve us a useful
2841      // chain. Disconnect peers that are on chains with insufficient work.
2842      if (m_chainman.IsInitialBlockDownload() && !may_have_more_headers) {
2843          // If the peer has no more headers to give us, then we know we have
2844          // their tip.
2845          if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) {
2846              // This peer has too little work on their headers chain to help
2847              // us sync -- disconnect if it is an outbound disconnection
2848              // candidate.
2849              // Note: We compare their tip to the minimum chain work (rather than
2850              // m_chainman.ActiveChain().Tip()) because we won't start block download
2851              // until we have a headers chain that has at least
2852              // the minimum chain work, even if a peer has a chain past our tip,
2853              // as an anti-DoS measure.
2854              if (pfrom.IsOutboundOrBlockRelayConn()) {
2855                  LogInfo("outbound peer headers chain has insufficient work, %s\n", pfrom.DisconnectMsg(fLogIPs));
2856                  pfrom.fDisconnect = true;
2857              }
2858          }
2859      }
2860  
2861      // If this is an outbound full-relay peer, check to see if we should protect
2862      // it from the bad/lagging chain logic.
2863      // Note that outbound block-relay peers are excluded from this protection, and
2864      // thus always subject to eviction under the bad/lagging chain logic.
2865      // See ChainSyncTimeoutState.
2866      if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) {
2867          if (m_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) {
2868              LogDebug(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId());
2869              nodestate->m_chain_sync.m_protect = true;
2870              ++m_outbound_peers_with_protect_from_disconnect;
2871          }
2872      }
2873  }
2874  
2875  void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, Peer& peer,
2876                                              std::vector<CBlockHeader>&& headers,
2877                                              bool via_compact_block)
2878  {
2879      size_t nCount = headers.size();
2880  
2881      if (nCount == 0) {
2882          // Nothing interesting. Stop asking this peers for more headers.
2883          // If we were in the middle of headers sync, receiving an empty headers
2884          // message suggests that the peer suddenly has nothing to give us
2885          // (perhaps it reorged to our chain). Clear download state for this peer.
2886          LOCK(peer.m_headers_sync_mutex);
2887          if (peer.m_headers_sync) {
2888              peer.m_headers_sync.reset(nullptr);
2889              LOCK(m_headers_presync_mutex);
2890              m_headers_presync_stats.erase(pfrom.GetId());
2891          }
2892          // A headers message with no headers cannot be an announcement, so assume
2893          // it is a response to our last getheaders request, if there is one.
2894          peer.m_last_getheaders_timestamp = {};
2895          return;
2896      }
2897  
2898      // Before we do any processing, make sure these pass basic sanity checks.
2899      // We'll rely on headers having valid proof-of-work further down, as an
2900      // anti-DoS criteria (note: this check is required before passing any
2901      // headers into HeadersSyncState).
2902      if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) {
2903          // Misbehaving() calls are handled within CheckHeadersPoW(), so we can
2904          // just return. (Note that even if a header is announced via compact
2905          // block, the header itself should be valid, so this type of error can
2906          // always be punished.)
2907          return;
2908      }
2909  
2910      const CBlockIndex *pindexLast = nullptr;
2911  
2912      // We'll set already_validated_work to true if these headers are
2913      // successfully processed as part of a low-work headers sync in progress
2914      // (either in PRESYNC or REDOWNLOAD phase).
2915      // If true, this will mean that any headers returned to us (ie during
2916      // REDOWNLOAD) can be validated without further anti-DoS checks.
2917      bool already_validated_work = false;
2918  
2919      // If we're in the middle of headers sync, let it do its magic.
2920      bool have_headers_sync = false;
2921      {
2922          LOCK(peer.m_headers_sync_mutex);
2923  
2924          already_validated_work = IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
2925  
2926          // The headers we passed in may have been:
2927          // - untouched, perhaps if no headers-sync was in progress, or some
2928          //   failure occurred
2929          // - erased, such as if the headers were successfully processed and no
2930          //   additional headers processing needs to take place (such as if we
2931          //   are still in PRESYNC)
2932          // - replaced with headers that are now ready for validation, such as
2933          //   during the REDOWNLOAD phase of a low-work headers sync.
2934          // So just check whether we still have headers that we need to process,
2935          // or not.
2936          if (headers.empty()) {
2937              return;
2938          }
2939  
2940          have_headers_sync = !!peer.m_headers_sync;
2941      }
2942  
2943      // Do these headers connect to something in our block index?
2944      const CBlockIndex *chain_start_header{WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock))};
2945      bool headers_connect_blockindex{chain_start_header != nullptr};
2946  
2947      if (!headers_connect_blockindex) {
2948          // This could be a BIP 130 block announcement, use
2949          // special logic for handling headers that don't connect, as this
2950          // could be benign.
2951          HandleUnconnectingHeaders(pfrom, peer, headers);
2952          return;
2953      }
2954  
2955      // If headers connect, assume that this is in response to any outstanding getheaders
2956      // request we may have sent, and clear out the time of our last request. Non-connecting
2957      // headers cannot be a response to a getheaders request.
2958      peer.m_last_getheaders_timestamp = {};
2959  
2960      // If the headers we received are already in memory and an ancestor of
2961      // m_best_header or our tip, skip anti-DoS checks. These headers will not
2962      // use any more memory (and we are not leaking information that could be
2963      // used to fingerprint us).
2964      const CBlockIndex *last_received_header{nullptr};
2965      {
2966          LOCK(cs_main);
2967          last_received_header = m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash());
2968          if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
2969              already_validated_work = true;
2970          }
2971      }
2972  
2973      // If our peer has NetPermissionFlags::NoBan privileges, then bypass our
2974      // anti-DoS logic (this saves bandwidth when we connect to a trusted peer
2975      // on startup).
2976      if (pfrom.HasPermission(NetPermissionFlags::NoBan)) {
2977          already_validated_work = true;
2978      }
2979  
2980      // At this point, the headers connect to something in our block index.
2981      // Do anti-DoS checks to determine if we should process or store for later
2982      // processing.
2983      if (!already_validated_work && TryLowWorkHeadersSync(peer, pfrom,
2984                  chain_start_header, headers)) {
2985          // If we successfully started a low-work headers sync, then there
2986          // should be no headers to process any further.
2987          Assume(headers.empty());
2988          return;
2989      }
2990  
2991      // At this point, we have a set of headers with sufficient work on them
2992      // which can be processed.
2993  
2994      // If we don't have the last header, then this peer will have given us
2995      // something new (if these headers are valid).
2996      bool received_new_header{last_received_header == nullptr};
2997  
2998      // Now process all the headers.
2999      BlockValidationState state;
3000      if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true, state, &pindexLast)) {
3001          if (state.IsInvalid()) {
3002              MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received");
3003              return;
3004          }
3005      }
3006      assert(pindexLast);
3007  
3008      // Consider fetching more headers if we are not using our headers-sync mechanism.
3009      if (nCount == m_opts.max_headers_result && !have_headers_sync) {
3010          // Headers message had its maximum size; the peer may have more headers.
3011          if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) {
3012              LogDebug(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
3013                      pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
3014          }
3015      }
3016  
3017      UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast, received_new_header, nCount == m_opts.max_headers_result);
3018  
3019      // Consider immediately downloading blocks.
3020      HeadersDirectFetchBlocks(pfrom, peer, *pindexLast);
3021  
3022      return;
3023  }
3024  
3025  std::optional<node::PackageToValidate> PeerManagerImpl::ProcessInvalidTx(NodeId nodeid, const CTransactionRef& ptx, const TxValidationState& state,
3026                                         bool first_time_failure)
3027  {
3028      AssertLockNotHeld(m_peer_mutex);
3029      AssertLockHeld(g_msgproc_mutex);
3030      AssertLockHeld(m_tx_download_mutex);
3031  
3032      PeerRef peer{GetPeerRef(nodeid)};
3033  
3034      LogDebug(BCLog::MEMPOOLREJ, "%s (wtxid=%s) from peer=%d was not accepted: %s\n",
3035          ptx->GetHash().ToString(),
3036          ptx->GetWitnessHash().ToString(),
3037          nodeid,
3038          state.ToString());
3039  
3040      const auto& [add_extra_compact_tx, unique_parents, package_to_validate] = m_txdownloadman.MempoolRejectedTx(ptx, state, nodeid, first_time_failure);
3041  
3042      const size_t tx_dynamic_usage{RecursiveDynamicUsage(*ptx)};
3043      if (add_extra_compact_tx && tx_dynamic_usage < BLOCK_RECONSTRUCTION_EXTRA_TXN_PER_TXN_SIZE_LIMIT) {
3044          AddToCompactExtraTransactions(ptx, tx_dynamic_usage);
3045      }
3046      for (const Txid& parent_txid : unique_parents) {
3047          if (peer) AddKnownTx(*peer, parent_txid);
3048      }
3049  
3050      return package_to_validate;
3051  }
3052  
3053  void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions)
3054  {
3055      AssertLockNotHeld(m_peer_mutex);
3056      AssertLockHeld(g_msgproc_mutex);
3057      AssertLockHeld(m_tx_download_mutex);
3058  
3059      m_txdownloadman.MempoolAcceptedTx(tx);
3060  
3061      LogDebug(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (wtxid=%s) (poolsz %u txn, %u kB)\n",
3062               nodeid,
3063               tx->GetHash().ToString(),
3064               tx->GetWitnessHash().ToString(),
3065               m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000);
3066  
3067      RelayTransaction(tx->GetHash(), tx->GetWitnessHash());
3068  
3069      for (const CTransactionRef& removedTx : replaced_transactions) {
3070          const size_t tx_dynamic_usage{RecursiveDynamicUsage(*removedTx)};
3071          AddToCompactExtraTransactions(removedTx, tx_dynamic_usage);
3072      }
3073  }
3074  
3075  void PeerManagerImpl::ProcessPackageResult(const node::PackageToValidate& package_to_validate, const PackageMempoolAcceptResult& package_result)
3076  {
3077      AssertLockNotHeld(m_peer_mutex);
3078      AssertLockHeld(g_msgproc_mutex);
3079      AssertLockHeld(m_tx_download_mutex);
3080  
3081      const auto& package = package_to_validate.m_txns;
3082      const auto& senders = package_to_validate.m_senders;
3083  
3084      if (package_result.m_state.IsInvalid()) {
3085          m_txdownloadman.MempoolRejectedPackage(package);
3086      }
3087      // We currently only expect to process 1-parent-1-child packages. Remove if this changes.
3088      if (!Assume(package.size() == 2)) return;
3089  
3090      // Iterate backwards to erase in-package descendants from the orphanage before they become
3091      // relevant in AddChildrenToWorkSet.
3092      auto package_iter = package.rbegin();
3093      auto senders_iter = senders.rbegin();
3094      while (package_iter != package.rend()) {
3095          const auto& tx = *package_iter;
3096          const NodeId nodeid = *senders_iter;
3097          const auto it_result{package_result.m_tx_results.find(tx->GetWitnessHash())};
3098  
3099          // It is not guaranteed that a result exists for every transaction.
3100          if (it_result != package_result.m_tx_results.end()) {
3101              const auto& tx_result = it_result->second;
3102              switch (tx_result.m_result_type) {
3103                  case MempoolAcceptResult::ResultType::VALID:
3104                  {
3105                      ProcessValidTx(nodeid, tx, tx_result.m_replaced_transactions);
3106                      break;
3107                  }
3108                  case MempoolAcceptResult::ResultType::INVALID:
3109                  case MempoolAcceptResult::ResultType::DIFFERENT_WITNESS:
3110                  {
3111                      // Don't add to vExtraTxnForCompact, as these transactions should have already been
3112                      // added there when added to the orphanage or rejected for TX_RECONSIDERABLE.
3113                      // This should be updated if package submission is ever used for transactions
3114                      // that haven't already been validated before.
3115                      ProcessInvalidTx(nodeid, tx, tx_result.m_state, /*first_time_failure=*/false);
3116                      break;
3117                  }
3118                  case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY:
3119                  {
3120                      // AlreadyHaveTx() should be catching transactions that are already in mempool.
3121                      Assume(false);
3122                      break;
3123                  }
3124              }
3125          }
3126          package_iter++;
3127          senders_iter++;
3128      }
3129  }
3130  
3131  bool PeerManagerImpl::ProcessOrphanTx(Peer& peer)
3132  {
3133      AssertLockHeld(g_msgproc_mutex);
3134      LOCK2(::cs_main, m_tx_download_mutex);
3135  
3136      CTransactionRef porphanTx = nullptr;
3137  
3138      while (CTransactionRef porphanTx = m_txdownloadman.GetTxToReconsider(peer.m_id)) {
3139          const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx);
3140          const TxValidationState& state = result.m_state;
3141          const Txid& orphanHash = porphanTx->GetHash();
3142          const Wtxid& orphan_wtxid = porphanTx->GetWitnessHash();
3143  
3144          if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
3145              LogDebug(BCLog::TXPACKAGES, "   accepted orphan tx %s (wtxid=%s)\n", orphanHash.ToString(), orphan_wtxid.ToString());
3146              ProcessValidTx(peer.m_id, porphanTx, result.m_replaced_transactions);
3147              return true;
3148          } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) {
3149              LogDebug(BCLog::TXPACKAGES, "   invalid orphan tx %s (wtxid=%s) from peer=%d. %s\n",
3150                  orphanHash.ToString(),
3151                  orphan_wtxid.ToString(),
3152                  peer.m_id,
3153                  state.ToString());
3154  
3155              if (Assume(state.IsInvalid() &&
3156                         state.GetResult() != TxValidationResult::TX_UNKNOWN &&
3157                         state.GetResult() != TxValidationResult::TX_NO_MEMPOOL &&
3158                         state.GetResult() != TxValidationResult::TX_RESULT_UNSET)) {
3159                  ProcessInvalidTx(peer.m_id, porphanTx, state, /*first_time_failure=*/false);
3160              }
3161              return true;
3162          }
3163      }
3164  
3165      return false;
3166  }
3167  
3168  bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& node, Peer& peer,
3169                                                  BlockFilterType filter_type, uint32_t start_height,
3170                                                  const uint256& stop_hash, uint32_t max_height_diff,
3171                                                  const CBlockIndex*& stop_index,
3172                                                  BlockFilterIndex*& filter_index)
3173  {
3174      const bool supported_filter_type =
3175          (filter_type == BlockFilterType::BASIC &&
3176           (peer.m_our_services & NODE_COMPACT_FILTERS));
3177      if (!supported_filter_type) {
3178          LogDebug(BCLog::NET, "peer requested unsupported block filter type: %d, %s\n",
3179                   static_cast<uint8_t>(filter_type), node.DisconnectMsg(fLogIPs));
3180          node.fDisconnect = true;
3181          return false;
3182      }
3183  
3184      {
3185          LOCK(cs_main);
3186          stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
3187  
3188          // Check that the stop block exists and the peer would be allowed to fetch it.
3189          if (!stop_index || !BlockRequestAllowed(stop_index)) {
3190              LogDebug(BCLog::NET, "peer requested invalid block hash: %s, %s\n",
3191                       stop_hash.ToString(), node.DisconnectMsg(fLogIPs));
3192              node.fDisconnect = true;
3193              return false;
3194          }
3195      }
3196  
3197      uint32_t stop_height = stop_index->nHeight;
3198      if (start_height > stop_height) {
3199          LogDebug(BCLog::NET, "peer sent invalid getcfilters/getcfheaders with "
3200                   "start height %d and stop height %d, %s\n",
3201                   start_height, stop_height, node.DisconnectMsg(fLogIPs));
3202          node.fDisconnect = true;
3203          return false;
3204      }
3205      if (stop_height - start_height >= max_height_diff) {
3206          LogDebug(BCLog::NET, "peer requested too many cfilters/cfheaders: %d / %d, %s\n",
3207                   stop_height - start_height + 1, max_height_diff, node.DisconnectMsg(fLogIPs));
3208          node.fDisconnect = true;
3209          return false;
3210      }
3211  
3212      filter_index = GetBlockFilterIndex(filter_type);
3213      if (!filter_index) {
3214          LogDebug(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type));
3215          return false;
3216      }
3217  
3218      return true;
3219  }
3220  
3221  void PeerManagerImpl::ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv)
3222  {
3223      uint8_t filter_type_ser;
3224      uint32_t start_height;
3225      uint256 stop_hash;
3226  
3227      vRecv >> filter_type_ser >> start_height >> stop_hash;
3228  
3229      const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3230  
3231      const CBlockIndex* stop_index;
3232      BlockFilterIndex* filter_index;
3233      if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
3234                                     MAX_GETCFILTERS_SIZE, stop_index, filter_index)) {
3235          return;
3236      }
3237  
3238      std::vector<BlockFilter> filters;
3239      if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
3240          LogDebug(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
3241                       BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
3242          return;
3243      }
3244  
3245      for (const auto& filter : filters) {
3246          MakeAndPushMessage(node, NetMsgType::CFILTER, filter);
3247      }
3248  }
3249  
3250  void PeerManagerImpl::ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv)
3251  {
3252      uint8_t filter_type_ser;
3253      uint32_t start_height;
3254      uint256 stop_hash;
3255  
3256      vRecv >> filter_type_ser >> start_height >> stop_hash;
3257  
3258      const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3259  
3260      const CBlockIndex* stop_index;
3261      BlockFilterIndex* filter_index;
3262      if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
3263                                     MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) {
3264          return;
3265      }
3266  
3267      uint256 prev_header;
3268      if (start_height > 0) {
3269          const CBlockIndex* const prev_block =
3270              stop_index->GetAncestor(static_cast<int>(start_height - 1));
3271          if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
3272              LogDebug(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
3273                           BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString());
3274              return;
3275          }
3276      }
3277  
3278      std::vector<uint256> filter_hashes;
3279      if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) {
3280          LogDebug(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
3281                       BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
3282          return;
3283      }
3284  
3285      MakeAndPushMessage(node, NetMsgType::CFHEADERS,
3286                filter_type_ser,
3287                stop_index->GetBlockHash(),
3288                prev_header,
3289                filter_hashes);
3290  }
3291  
3292  void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv)
3293  {
3294      uint8_t filter_type_ser;
3295      uint256 stop_hash;
3296  
3297      vRecv >> filter_type_ser >> stop_hash;
3298  
3299      const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3300  
3301      const CBlockIndex* stop_index;
3302      BlockFilterIndex* filter_index;
3303      if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash,
3304                                     /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
3305                                     stop_index, filter_index)) {
3306          return;
3307      }
3308  
3309      std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
3310  
3311      // Populate headers.
3312      const CBlockIndex* block_index = stop_index;
3313      for (int i = headers.size() - 1; i >= 0; i--) {
3314          int height = (i + 1) * CFCHECKPT_INTERVAL;
3315          block_index = block_index->GetAncestor(height);
3316  
3317          if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
3318              LogDebug(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
3319                           BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());
3320              return;
3321          }
3322      }
3323  
3324      MakeAndPushMessage(node, NetMsgType::CFCHECKPT,
3325                filter_type_ser,
3326                stop_index->GetBlockHash(),
3327                headers);
3328  }
3329  
3330  void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)
3331  {
3332      bool new_block{false};
3333      m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block);
3334      if (new_block) {
3335          node.m_last_block_time = GetTime<std::chrono::seconds>();
3336          // In case this block came from a different peer than we requested
3337          // from, we can erase the block request now anyway (as we just stored
3338          // this block to disk).
3339          LOCK(cs_main);
3340          RemoveBlockRequest(block->GetHash(), std::nullopt);
3341      } else {
3342          LOCK(cs_main);
3343          mapBlockSource.erase(block->GetHash());
3344      }
3345  }
3346  
3347  void PeerManagerImpl::ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions)
3348  {
3349      std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3350      bool fBlockRead{false};
3351      {
3352          LOCK(cs_main);
3353  
3354          auto range_flight = mapBlocksInFlight.equal_range(block_transactions.blockhash);
3355          size_t already_in_flight = std::distance(range_flight.first, range_flight.second);
3356          bool requested_block_from_this_peer{false};
3357  
3358          // Multimap ensures ordering of outstanding requests. It's either empty or first in line.
3359          bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId());
3360  
3361          while (range_flight.first != range_flight.second) {
3362              auto [node_id, block_it] = range_flight.first->second;
3363              if (node_id == pfrom.GetId() && block_it->partialBlock) {
3364                  requested_block_from_this_peer = true;
3365                  break;
3366              }
3367              range_flight.first++;
3368          }
3369  
3370          if (!requested_block_from_this_peer) {
3371              LogDebug(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId());
3372              return;
3373          }
3374  
3375          PartiallyDownloadedBlock& partialBlock = *range_flight.first->second.second->partialBlock;
3376  
3377          if (partialBlock.header.IsNull()) {
3378              // It is possible for the header to be empty if a previous call to FillBlock wiped the header, but left
3379              // the PartiallyDownloadedBlock pointer around (i.e. did not call RemoveBlockRequest). In this case, we
3380              // should not call LookupBlockIndex below.
3381              RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId());
3382              Misbehaving(peer, "previous compact block reconstruction attempt failed");
3383              LogDebug(BCLog::NET, "Peer %d sent compact block transactions multiple times", pfrom.GetId());
3384              return;
3385          }
3386  
3387          // We should not have gotten this far in compact block processing unless it's attached to a known header
3388          const CBlockIndex* prev_block{Assume(m_chainman.m_blockman.LookupBlockIndex(partialBlock.header.hashPrevBlock))};
3389          ReadStatus status = partialBlock.FillBlock(*pblock, block_transactions.txn,
3390                                                     /*segwit_active=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT));
3391          if (status == READ_STATUS_INVALID) {
3392              RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect
3393              Misbehaving(peer, "invalid compact block/non-matching block transactions");
3394              return;
3395          } else if (status == READ_STATUS_FAILED) {
3396              if (first_in_flight) {
3397                  // Might have collided, fall back to getdata now :(
3398                  // We keep the failed partialBlock to disallow processing another compact block announcement from the same
3399                  // peer for the same block. We let the full block download below continue under the same m_downloading_since
3400                  // timer.
3401                  std::vector<CInv> invs;
3402                  invs.emplace_back(MSG_BLOCK | GetFetchFlags(peer), block_transactions.blockhash);
3403                  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, invs);
3404              } else {
3405                  RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId());
3406                  LogDebug(BCLog::NET, "Peer %d sent us a compact block but it failed to reconstruct, waiting on first download to complete\n", pfrom.GetId());
3407                  return;
3408              }
3409          } else {
3410              // Block is okay for further processing
3411              RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // it is now an empty pointer
3412              fBlockRead = true;
3413              // mapBlockSource is used for potentially punishing peers and
3414              // updating which peers send us compact blocks, so the race
3415              // between here and cs_main in ProcessNewBlock is fine.
3416              // BIP 152 permits peers to relay compact blocks after validating
3417              // the header only; we should not punish peers if the block turns
3418              // out to be invalid.
3419              mapBlockSource.emplace(block_transactions.blockhash, std::make_pair(pfrom.GetId(), false));
3420          }
3421      } // Don't hold cs_main when we call into ProcessNewBlock
3422      if (fBlockRead) {
3423          // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
3424          // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
3425          // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
3426          // disk-space attacks), but this should be safe due to the
3427          // protections in the compact block handler -- see related comment
3428          // in compact block optimistic reconstruction handling.
3429          ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
3430      }
3431      return;
3432  }
3433  
3434  void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv,
3435                                       const std::chrono::microseconds time_received,
3436                                       const std::atomic<bool>& interruptMsgProc)
3437  {
3438      AssertLockHeld(g_msgproc_mutex);
3439  
3440      LogDebug(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
3441  
3442      PeerRef peer = GetPeerRef(pfrom.GetId());
3443      if (peer == nullptr) return;
3444  
3445      if (msg_type == NetMsgType::VERSION) {
3446          if (pfrom.nVersion != 0) {
3447              LogDebug(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId());
3448              return;
3449          }
3450  
3451          int64_t nTime;
3452          CService addrMe;
3453          uint64_t nNonce = 1;
3454          ServiceFlags nServices;
3455          int nVersion;
3456          std::string cleanSubVer;
3457          int starting_height = -1;
3458          bool fRelay = true;
3459  
3460          vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
3461          if (nTime < 0) {
3462              nTime = 0;
3463          }
3464          vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer
3465          vRecv >> CNetAddr::V1(addrMe);
3466          if (!pfrom.IsInboundConn())
3467          {
3468              // Overwrites potentially existing services. In contrast to this,
3469              // unvalidated services received via gossip relay in ADDR/ADDRV2
3470              // messages are only ever added but cannot replace existing ones.
3471              m_addrman.SetServices(pfrom.addr, nServices);
3472          }
3473          if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices))
3474          {
3475              LogDebug(BCLog::NET, "peer does not offer the expected services (%08x offered, %08x expected), %s\n",
3476                       nServices,
3477                       GetDesirableServiceFlags(nServices),
3478                       pfrom.DisconnectMsg(fLogIPs));
3479              pfrom.fDisconnect = true;
3480              return;
3481          }
3482  
3483          if (nVersion < MIN_PEER_PROTO_VERSION) {
3484              // disconnect from peers older than this proto version
3485              LogDebug(BCLog::NET, "peer using obsolete version %i, %s\n", nVersion, pfrom.DisconnectMsg(fLogIPs));
3486              pfrom.fDisconnect = true;
3487              return;
3488          }
3489  
3490          if (!vRecv.empty()) {
3491              // The version message includes information about the sending node which we don't use:
3492              //   - 8 bytes (service bits)
3493              //   - 16 bytes (ipv6 address)
3494              //   - 2 bytes (port)
3495              vRecv.ignore(26);
3496              vRecv >> nNonce;
3497          }
3498          if (!vRecv.empty()) {
3499              std::string strSubVer;
3500              vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
3501              cleanSubVer = SanitizeString(strSubVer, SAFE_CHARS_PRINTABLE);
3502          }
3503          if (!vRecv.empty()) {
3504              vRecv >> starting_height;
3505          }
3506          if (!vRecv.empty())
3507              vRecv >> fRelay;
3508          // Disconnect if we connected to ourself
3509          if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce))
3510          {
3511              LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToStringAddrPort());
3512              pfrom.fDisconnect = true;
3513              return;
3514          }
3515  
3516          if (pfrom.IsInboundConn() && addrMe.IsRoutable())
3517          {
3518              SeenLocal(addrMe);
3519          }
3520  
3521          // Inbound peers send us their version message when they connect.
3522          // We send our version message in response.
3523          if (pfrom.IsInboundConn()) {
3524              PushNodeVersion(pfrom, *peer);
3525          }
3526  
3527          // Change version
3528          const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION);
3529          pfrom.SetCommonVersion(greatest_common_version);
3530          {
3531              LOCK(pfrom.m_subver_mutex);
3532              pfrom.cleanSubVer = cleanSubVer;
3533          }
3534          pfrom.nVersion = nVersion;
3535  
3536          if (greatest_common_version >= WTXID_RELAY_VERSION) {
3537              MakeAndPushMessage(pfrom, NetMsgType::WTXIDRELAY);
3538          }
3539  
3540          // Signal ADDRv2 support (BIP155).
3541          if (greatest_common_version >= 70016) {
3542              // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some
3543              // implementations reject messages they don't know. As a courtesy, don't send
3544              // it to nodes with a version before 70016, as no software is known to support
3545              // BIP155 that doesn't announce at least that protocol version number.
3546              MakeAndPushMessage(pfrom, NetMsgType::SENDADDRV2);
3547          }
3548  
3549          pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices);
3550          // BIP-110: Allow up to 2 non-BIP110 outbound peers.
3551          if (pfrom.ExpectServicesFromConn() && !(nServices & NODE_REDUCED_DATA)) {
3552              if (m_num_non_bip110_outbound >= m_opts.maxstaleoutbound) {
3553                  LogDebug(BCLog::NET, "peer lacks NODE_REDUCED_DATA and already have %u non-BIP110 outbound peers (limit %u), %s\n",
3554                           m_num_non_bip110_outbound,
3555                           m_opts.maxstaleoutbound,
3556                           pfrom.DisconnectMsg(fLogIPs));
3557                  pfrom.fDisconnect = true;
3558                  return;
3559              }
3560              ++m_num_non_bip110_outbound;
3561              pfrom.m_is_non_bip110_outbound = true;
3562              LogDebug(BCLog::NET, "connected to non-BIP110 outbound peer (%u/%u), %s\n",
3563                       m_num_non_bip110_outbound.load(),
3564                       m_opts.maxstaleoutbound,
3565                       pfrom.ConnectionTypeAsString());
3566          }
3567          peer->m_their_services = nServices;
3568          pfrom.SetAddrLocal(addrMe);
3569          peer->m_starting_height = starting_height;
3570  
3571          // Only initialize the Peer::TxRelay m_relay_txs data structure if:
3572          // - this isn't an outbound block-relay-only connection, and
3573          // - this isn't an outbound feeler connection, and
3574          // - fRelay=true (the peer wishes to receive transaction announcements)
3575          //   or we're offering NODE_BLOOM to this peer. NODE_BLOOM means that
3576          //   the peer may turn on transaction relay later.
3577          if (!pfrom.IsBlockOnlyConn() &&
3578              !pfrom.IsFeelerConn() &&
3579              (fRelay || (peer->m_our_services & NODE_BLOOM))) {
3580              auto* const tx_relay = peer->SetTxRelay();
3581              {
3582                  LOCK(tx_relay->m_bloom_filter_mutex);
3583                  tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message
3584              }
3585              if (fRelay) pfrom.m_relays_txs = true;
3586          }
3587  
3588          if (greatest_common_version >= WTXID_RELAY_VERSION && m_txreconciliation) {
3589              // Per BIP-330, we announce txreconciliation support if:
3590              // - protocol version per the peer's VERSION message supports WTXID_RELAY;
3591              // - transaction relay is supported per the peer's VERSION message
3592              // - this is not a block-relay-only connection and not a feeler
3593              // - this is not an addr fetch connection;
3594              // - we are not in -blocksonly mode.
3595              const auto* tx_relay = peer->GetTxRelay();
3596              if (tx_relay && WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs) &&
3597                  !pfrom.IsAddrFetchConn() && !m_opts.ignore_incoming_txs) {
3598                  const uint64_t recon_salt = m_txreconciliation->PreRegisterPeer(pfrom.GetId());
3599                  MakeAndPushMessage(pfrom, NetMsgType::SENDTXRCNCL,
3600                                     TXRECONCILIATION_VERSION, recon_salt);
3601              }
3602          }
3603  
3604          MakeAndPushMessage(pfrom, NetMsgType::VERACK);
3605  
3606          // Potentially mark this peer as a preferred download peer.
3607          {
3608              LOCK(cs_main);
3609              CNodeState* state = State(pfrom.GetId());
3610              state->fPreferredDownload = (!pfrom.IsInboundConn() || pfrom.HasPermission(NetPermissionFlags::NoBan)) && !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer);
3611              m_num_preferred_download_peers += state->fPreferredDownload;
3612          }
3613  
3614          // Attempt to initialize address relay for outbound peers and use result
3615          // to decide whether to send GETADDR, so that we don't send it to
3616          // inbound or outbound block-relay-only peers.
3617          bool send_getaddr{false};
3618          if (!pfrom.IsInboundConn()) {
3619              send_getaddr = SetupAddressRelay(pfrom, *peer);
3620          }
3621          if (send_getaddr) {
3622              // Do a one-time address fetch to help populate/update our addrman.
3623              // If we're starting up for the first time, our addrman may be pretty
3624              // empty, so this mechanism is important to help us connect to the network.
3625              // We skip this for block-relay-only peers. We want to avoid
3626              // potentially leaking addr information and we do not want to
3627              // indicate to the peer that we will participate in addr relay.
3628              MakeAndPushMessage(pfrom, NetMsgType::GETADDR);
3629              peer->m_getaddr_sent = true;
3630              // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response
3631              // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
3632              peer->m_addr_token_bucket += MAX_ADDR_TO_SEND;
3633          }
3634  
3635          if (!pfrom.IsInboundConn()) {
3636              // For non-inbound connections, we update the addrman to record
3637              // connection success so that addrman will have an up-to-date
3638              // notion of which peers are online and available.
3639              //
3640              // While we strive to not leak information about block-relay-only
3641              // connections via the addrman, not moving an address to the tried
3642              // table is also potentially detrimental because new-table entries
3643              // are subject to eviction in the event of addrman collisions.  We
3644              // mitigate the information-leak by never calling
3645              // AddrMan::Connected() on block-relay-only peers; see
3646              // FinalizeNode().
3647              //
3648              // This moves an address from New to Tried table in Addrman,
3649              // resolves tried-table collisions, etc.
3650              m_addrman.Good(pfrom.addr);
3651          }
3652  
3653          const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)};
3654          LogDebug(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s%s%s\n",
3655                    SanitizeString(cleanSubVer, SAFE_CHARS_DEFAULT, true), pfrom.nVersion,
3656                    peer->m_starting_height, addrMe.ToStringAddrPort(), fRelay, pfrom.GetId(),
3657                    fLogIPs ? "," : "", pfrom.LogIP(fLogIPs),
3658                    (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : ""));
3659  
3660          peer->m_time_offset = NodeSeconds{std::chrono::seconds{nTime}} - Now<NodeSeconds>();
3661          if (!pfrom.IsInboundConn()) {
3662              // Don't use timedata samples from inbound peers to make it
3663              // harder for others to create false warnings about our clock being out of sync.
3664              m_outbound_time_offsets.Add(peer->m_time_offset);
3665              m_outbound_time_offsets.WarnIfOutOfSync();
3666          }
3667  
3668          // If the peer is old enough to have the old alert system, send it the final alert.
3669          if (greatest_common_version <= 70012) {
3670              constexpr auto finalAlert{"60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"_hex};
3671              MakeAndPushMessage(pfrom, "alert", finalAlert);
3672          }
3673  
3674          // Feeler connections exist only to verify if address is online.
3675          if (pfrom.IsFeelerConn()) {
3676              LogDebug(BCLog::NET, "feeler connection completed, %s\n", pfrom.DisconnectMsg(fLogIPs));
3677              pfrom.fDisconnect = true;
3678          }
3679          return;
3680      }
3681  
3682      if (pfrom.nVersion == 0) {
3683          // Must have a version message before anything else
3684          LogDebug(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
3685          return;
3686      }
3687  
3688      if (msg_type == NetMsgType::VERACK) {
3689          if (pfrom.fSuccessfullyConnected) {
3690              LogDebug(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId());
3691              return;
3692          }
3693  
3694          // Log successful connections unconditionally for outbound, but not for inbound as those
3695          // can be triggered by an attacker at high rate.
3696          if (!pfrom.IsInboundConn() || LogAcceptCategory(BCLog::NET, BCLog::Level::Debug)) {
3697              const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)};
3698              LogPrintf("New %s %s peer connected: version: %d, blocks=%d, peer=%d%s%s%s\n",
3699                        pfrom.ConnectionTypeAsString(),
3700                        TransportTypeAsString(pfrom.m_transport->GetInfo().transport_type),
3701                        pfrom.nVersion.load(), peer->m_starting_height,
3702                        pfrom.GetId(),
3703                        fLogIPs ? "," : "", pfrom.LogIP(fLogIPs),
3704                        (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : ""));
3705          }
3706  
3707          if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) {
3708              // Tell our peer we are willing to provide version 2 cmpctblocks.
3709              // However, we do not request new block announcements using
3710              // cmpctblock messages.
3711              // We send this to non-NODE NETWORK peers as well, because
3712              // they may wish to request compact blocks from us
3713              MakeAndPushMessage(pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION);
3714          }
3715  
3716          if (m_txreconciliation) {
3717              if (!peer->m_wtxid_relay || !m_txreconciliation->IsPeerRegistered(pfrom.GetId())) {
3718                  // We could have optimistically pre-registered/registered the peer. In that case,
3719                  // we should forget about the reconciliation state here if this wasn't followed
3720                  // by WTXIDRELAY (since WTXIDRELAY can't be announced later).
3721                  m_txreconciliation->ForgetPeer(pfrom.GetId());
3722              }
3723          }
3724  
3725          if (auto tx_relay = peer->GetTxRelay()) {
3726              // `TxRelay::m_tx_inventory_to_send` must be empty before the
3727              // version handshake is completed as
3728              // `TxRelay::m_next_inv_send_time` is first initialised in
3729              // `SendMessages` after the verack is received. Any transactions
3730              // received during the version handshake would otherwise
3731              // immediately be advertised without random delay, potentially
3732              // leaking the time of arrival to a spy.
3733              Assume(WITH_LOCK(
3734                  tx_relay->m_tx_inventory_mutex,
3735                  return tx_relay->m_tx_inventory_to_send.empty() &&
3736                         tx_relay->m_next_inv_send_time == 0s));
3737          }
3738  
3739          {
3740              LOCK2(::cs_main, m_tx_download_mutex);
3741              const CNodeState* state = State(pfrom.GetId());
3742              m_txdownloadman.ConnectedPeer(pfrom.GetId(), node::TxDownloadConnectionInfo {
3743                  .m_preferred = state->fPreferredDownload,
3744                  .m_relay_permissions = pfrom.HasPermission(NetPermissionFlags::Relay),
3745                  .m_wtxid_relay = peer->m_wtxid_relay,
3746              });
3747          }
3748  
3749          pfrom.fSuccessfullyConnected = true;
3750          return;
3751      }
3752  
3753      if (msg_type == NetMsgType::SENDHEADERS) {
3754          peer->m_prefers_headers = true;
3755          return;
3756      }
3757  
3758      if (msg_type == NetMsgType::SENDCMPCT) {
3759          bool sendcmpct_hb{false};
3760          uint64_t sendcmpct_version{0};
3761          vRecv >> sendcmpct_hb >> sendcmpct_version;
3762  
3763          // Only support compact block relay with witnesses
3764          if (sendcmpct_version != CMPCTBLOCKS_VERSION) return;
3765  
3766          LOCK(cs_main);
3767          CNodeState* nodestate = State(pfrom.GetId());
3768          nodestate->m_provides_cmpctblocks = true;
3769          nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
3770          // save whether peer selects us as BIP152 high-bandwidth peer
3771          // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth)
3772          pfrom.m_bip152_highbandwidth_from = sendcmpct_hb;
3773          return;
3774      }
3775  
3776      // BIP339 defines feature negotiation of wtxidrelay, which must happen between
3777      // VERSION and VERACK to avoid relay problems from switching after a connection is up.
3778      if (msg_type == NetMsgType::WTXIDRELAY) {
3779          if (pfrom.fSuccessfullyConnected) {
3780              // Disconnect peers that send a wtxidrelay message after VERACK.
3781              LogDebug(BCLog::NET, "wtxidrelay received after verack, %s\n", pfrom.DisconnectMsg(fLogIPs));
3782              pfrom.fDisconnect = true;
3783              return;
3784          }
3785          if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) {
3786              if (!peer->m_wtxid_relay) {
3787                  peer->m_wtxid_relay = true;
3788                  m_wtxid_relay_peers++;
3789              } else {
3790                  LogDebug(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId());
3791              }
3792          } else {
3793              LogDebug(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId());
3794          }
3795          return;
3796      }
3797  
3798      // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen
3799      // between VERSION and VERACK.
3800      if (msg_type == NetMsgType::SENDADDRV2) {
3801          if (pfrom.fSuccessfullyConnected) {
3802              // Disconnect peers that send a SENDADDRV2 message after VERACK.
3803              LogDebug(BCLog::NET, "sendaddrv2 received after verack, %s\n", pfrom.DisconnectMsg(fLogIPs));
3804              pfrom.fDisconnect = true;
3805              return;
3806          }
3807          peer->m_wants_addrv2 = true;
3808          return;
3809      }
3810  
3811      // Received from a peer demonstrating readiness to announce transactions via reconciliations.
3812      // This feature negotiation must happen between VERSION and VERACK to avoid relay problems
3813      // from switching announcement protocols after the connection is up.
3814      if (msg_type == NetMsgType::SENDTXRCNCL) {
3815          if (!m_txreconciliation) {
3816              LogDebug(BCLog::NET, "sendtxrcncl from peer=%d ignored, as our node does not have txreconciliation enabled\n", pfrom.GetId());
3817              return;
3818          }
3819  
3820          if (pfrom.fSuccessfullyConnected) {
3821              LogDebug(BCLog::NET, "sendtxrcncl received after verack, %s\n", pfrom.DisconnectMsg(fLogIPs));
3822              pfrom.fDisconnect = true;
3823              return;
3824          }
3825  
3826          // Peer must not offer us reconciliations if we specified no tx relay support in VERSION.
3827          if (RejectIncomingTxs(pfrom)) {
3828              LogDebug(BCLog::NET, "sendtxrcncl received to which we indicated no tx relay, %s\n", pfrom.DisconnectMsg(fLogIPs));
3829              pfrom.fDisconnect = true;
3830              return;
3831          }
3832  
3833          // Peer must not offer us reconciliations if they specified no tx relay support in VERSION.
3834          // This flag might also be false in other cases, but the RejectIncomingTxs check above
3835          // eliminates them, so that this flag fully represents what we are looking for.
3836          const auto* tx_relay = peer->GetTxRelay();
3837          if (!tx_relay || !WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs)) {
3838              LogDebug(BCLog::NET, "sendtxrcncl received which indicated no tx relay to us, %s\n", pfrom.DisconnectMsg(fLogIPs));
3839              pfrom.fDisconnect = true;
3840              return;
3841          }
3842  
3843          uint32_t peer_txreconcl_version;
3844          uint64_t remote_salt;
3845          vRecv >> peer_txreconcl_version >> remote_salt;
3846  
3847          const ReconciliationRegisterResult result = m_txreconciliation->RegisterPeer(pfrom.GetId(), pfrom.IsInboundConn(),
3848                                                                                       peer_txreconcl_version, remote_salt);
3849          switch (result) {
3850          case ReconciliationRegisterResult::NOT_FOUND:
3851              LogDebug(BCLog::NET, "Ignore unexpected txreconciliation signal from peer=%d\n", pfrom.GetId());
3852              break;
3853          case ReconciliationRegisterResult::SUCCESS:
3854              break;
3855          case ReconciliationRegisterResult::ALREADY_REGISTERED:
3856              LogDebug(BCLog::NET, "txreconciliation protocol violation (sendtxrcncl received from already registered peer), %s\n", pfrom.DisconnectMsg(fLogIPs));
3857              pfrom.fDisconnect = true;
3858              return;
3859          case ReconciliationRegisterResult::PROTOCOL_VIOLATION:
3860              LogDebug(BCLog::NET, "txreconciliation protocol violation, %s\n", pfrom.DisconnectMsg(fLogIPs));
3861              pfrom.fDisconnect = true;
3862              return;
3863          }
3864          return;
3865      }
3866  
3867      if (!pfrom.fSuccessfullyConnected) {
3868          LogDebug(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
3869          return;
3870      }
3871  
3872      if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
3873          const auto ser_params{
3874              msg_type == NetMsgType::ADDRV2 ?
3875              // Set V2 param so that the CNetAddr and CAddress
3876              // unserialize methods know that an address in v2 format is coming.
3877              CAddress::V2_NETWORK :
3878              CAddress::V1_NETWORK,
3879          };
3880  
3881          unsigned int nCount = ReadCompactSize(vRecv);
3882          if (nCount > MAX_ADDR_TO_SEND) {
3883              Misbehaving(*peer, strprintf("%s message size = %u", msg_type, nCount));
3884              return;
3885          }
3886  
3887          std::vector<CAddress> vAddr;
3888          vAddr.resize(nCount);
3889  
3890          for (unsigned int n = 0; n < nCount; n++) {
3891              vRecv >> ser_params(vAddr[n]);
3892          }
3893  
3894          if (!SetupAddressRelay(pfrom, *peer)) {
3895              LogDebug(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
3896              return;
3897          }
3898  
3899          // Store the new addresses
3900          std::vector<CAddress> vAddrOk;
3901          const auto current_a_time{Now<NodeSeconds>()};
3902  
3903          // Update/increment addr rate limiting bucket.
3904          const auto current_time{GetTime<std::chrono::microseconds>()};
3905          if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
3906              // Don't increment bucket if it's already full
3907              const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us);
3908              const double increment = Ticks<SecondsDouble>(time_diff) * MAX_ADDR_RATE_PER_SECOND;
3909              peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET);
3910          }
3911          peer->m_addr_token_timestamp = current_time;
3912  
3913          const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr);
3914          uint64_t num_proc = 0;
3915          uint64_t num_rate_limit = 0;
3916          std::shuffle(vAddr.begin(), vAddr.end(), m_rng);
3917          for (CAddress& addr : vAddr)
3918          {
3919              if (interruptMsgProc)
3920                  return;
3921  
3922              // Apply rate limiting.
3923              if (peer->m_addr_token_bucket < 1.0) {
3924                  if (rate_limited) {
3925                      ++num_rate_limit;
3926                      continue;
3927                  }
3928              } else {
3929                  peer->m_addr_token_bucket -= 1.0;
3930              }
3931              // We only bother storing full nodes, though this may include
3932              // things which we would not make an outbound connection to, in
3933              // part because we may make feeler connections to them.
3934              if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices))
3935                  continue;
3936  
3937              if (addr.nTime <= NodeSeconds{100000000s} || addr.nTime > current_a_time + 10min) {
3938                  addr.nTime = current_a_time - 5 * 24h;
3939              }
3940              AddAddressKnown(*peer, addr);
3941              if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
3942                  // Do not process banned/discouraged addresses beyond remembering we received them
3943                  continue;
3944              }
3945              ++num_proc;
3946              const bool reachable{g_reachable_nets.Contains(addr)};
3947              if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) {
3948                  // Relay to a limited number of other nodes
3949                  RelayAddress(pfrom.GetId(), addr, reachable);
3950              }
3951              // Do not store addresses outside our network
3952              if (reachable) {
3953                  vAddrOk.push_back(addr);
3954              }
3955          }
3956          peer->m_addr_processed += num_proc;
3957          peer->m_addr_rate_limited += num_rate_limit;
3958          LogDebug(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n",
3959                   vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
3960  
3961          m_addrman.Add(vAddrOk, pfrom.addr, 2h);
3962          if (vAddr.size() < 1000) peer->m_getaddr_sent = false;
3963  
3964          // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements
3965          if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
3966              LogDebug(BCLog::NET, "addrfetch connection completed, %s\n", pfrom.DisconnectMsg(fLogIPs));
3967              pfrom.fDisconnect = true;
3968          }
3969          return;
3970      }
3971  
3972      if (msg_type == NetMsgType::INV) {
3973          unsigned int nCount = ReadCompactSize(vRecv);
3974          if (nCount > MAX_INV_SZ) {
3975              Misbehaving(*peer, strprintf("inv message size = %u", nCount));
3976              return;
3977          }
3978          std::vector<CInv> vInv;
3979          vInv.resize(nCount);
3980          for (unsigned int n = 0; n < nCount; n++) {
3981              vRecv >> vInv[n];
3982          }
3983  
3984          const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
3985  
3986          LOCK2(cs_main, m_tx_download_mutex);
3987  
3988          const auto current_time{GetTime<std::chrono::microseconds>()};
3989          uint256* best_block{nullptr};
3990  
3991          for (CInv& inv : vInv) {
3992              if (interruptMsgProc) return;
3993  
3994              // Ignore INVs that don't match wtxidrelay setting.
3995              // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting.
3996              // This is fine as no INV messages are involved in that process.
3997              if (peer->m_wtxid_relay) {
3998                  if (inv.IsMsgTx()) continue;
3999              } else {
4000                  if (inv.IsMsgWtx()) continue;
4001              }
4002  
4003              if (inv.IsMsgBlk()) {
4004                  const bool fAlreadyHave = AlreadyHaveBlock(inv.hash);
4005                  LogDebug(BCLog::NET, "got inv: %s  %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
4006  
4007                  UpdateBlockAvailability(pfrom.GetId(), inv.hash);
4008                  if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() && !IsBlockRequested(inv.hash)) {
4009                      // Headers-first is the primary method of announcement on
4010                      // the network. If a node fell back to sending blocks by
4011                      // inv, it may be for a re-org, or because we haven't
4012                      // completed initial headers sync. The final block hash
4013                      // provided should be the highest, so send a getheaders and
4014                      // then fetch the blocks we need to catch up.
4015                      best_block = &inv.hash;
4016                  }
4017              } else if (inv.IsGenTxMsg()) {
4018                  if (reject_tx_invs) {
4019                      LogDebug(BCLog::NET, "transaction (%s) inv sent in violation of protocol, %s\n", inv.hash.ToString(), pfrom.DisconnectMsg(fLogIPs));
4020                      pfrom.fDisconnect = true;
4021                      return;
4022                  }
4023                  const GenTxid gtxid = ToGenTxid(inv);
4024                  AddKnownTx(*peer, inv.hash);
4025  
4026                  if (!m_chainman.IsInitialBlockDownload()) {
4027                      const bool fAlreadyHave{m_txdownloadman.AddTxAnnouncement(pfrom.GetId(), gtxid, current_time)};
4028                      LogDebug(BCLog::NET, "got inv: %s  %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
4029                  }
4030              } else {
4031                  LogDebug(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId());
4032              }
4033          }
4034  
4035          if (best_block != nullptr) {
4036              // If we haven't started initial headers-sync with this peer, then
4037              // consider sending a getheaders now. On initial startup, there's a
4038              // reliability vs bandwidth tradeoff, where we are only trying to do
4039              // initial headers sync with one peer at a time, with a long
4040              // timeout (at which point, if the sync hasn't completed, we will
4041              // disconnect the peer and then choose another). In the meantime,
4042              // as new blocks are found, we are willing to add one new peer per
4043              // block to sync with as well, to sync quicker in the case where
4044              // our initial peer is unresponsive (but less bandwidth than we'd
4045              // use if we turned on sync with all peers).
4046              CNodeState& state{*Assert(State(pfrom.GetId()))};
4047              if (state.fSyncStarted || (!peer->m_inv_triggered_getheaders_before_sync && *best_block != m_last_block_inv_triggering_headers_sync)) {
4048                  if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer)) {
4049                      LogDebug(BCLog::NET, "getheaders (%d) %s to peer=%d\n",
4050                              m_chainman.m_best_header->nHeight, best_block->ToString(),
4051                              pfrom.GetId());
4052                  }
4053                  if (!state.fSyncStarted) {
4054                      peer->m_inv_triggered_getheaders_before_sync = true;
4055                      // Update the last block hash that triggered a new headers
4056                      // sync, so that we don't turn on headers sync with more
4057                      // than 1 new peer every new block.
4058                      m_last_block_inv_triggering_headers_sync = *best_block;
4059                  }
4060              }
4061          }
4062  
4063          return;
4064      }
4065  
4066      if (msg_type == NetMsgType::GETDATA) {
4067          unsigned int nCount = ReadCompactSize(vRecv);
4068          if (nCount > MAX_INV_SZ) {
4069              Misbehaving(*peer, strprintf("getdata message size = %u", nCount));
4070              return;
4071          }
4072          std::vector<CInv> vInv;
4073          vInv.resize(nCount);
4074          for (unsigned int n = 0; n < nCount; n++) {
4075              vRecv >> vInv[n];
4076          }
4077  
4078          LogDebug(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId());
4079  
4080          if (vInv.size() > 0) {
4081              LogDebug(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
4082          }
4083  
4084          {
4085              LOCK(peer->m_getdata_requests_mutex);
4086              peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end());
4087              ProcessGetData(pfrom, *peer, interruptMsgProc);
4088          }
4089  
4090          return;
4091      }
4092  
4093      if (msg_type == NetMsgType::GETBLOCKS) {
4094          CBlockLocator locator;
4095          uint256 hashStop;
4096          vRecv >> locator >> hashStop;
4097  
4098          if (locator.vHave.size() > MAX_LOCATOR_SZ) {
4099              LogDebug(BCLog::NET, "getblocks locator size %lld > %d, %s\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.DisconnectMsg(fLogIPs));
4100              pfrom.fDisconnect = true;
4101              return;
4102          }
4103  
4104          // We might have announced the currently-being-connected tip using a
4105          // compact block, which resulted in the peer sending a getblocks
4106          // request, which we would otherwise respond to without the new block.
4107          // To avoid this situation we simply verify that we are on our best
4108          // known chain now. This is super overkill, but we handle it better
4109          // for getheaders requests, and there are no known nodes which support
4110          // compact blocks but still use getblocks to request blocks.
4111          {
4112              std::shared_ptr<const CBlock> a_recent_block;
4113              {
4114                  LOCK(m_most_recent_block_mutex);
4115                  a_recent_block = m_most_recent_block;
4116              }
4117              BlockValidationState state;
4118              if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
4119                  LogDebug(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
4120              }
4121          }
4122  
4123          LOCK(cs_main);
4124  
4125          // Find the last block the caller has in the main chain
4126          const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
4127  
4128          // Send the rest of the chain
4129          if (pindex)
4130              pindex = m_chainman.ActiveChain().Next(pindex);
4131          int nLimit = 500;
4132          LogDebug(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom.GetId());
4133          for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
4134          {
4135              if (pindex->GetBlockHash() == hashStop)
4136              {
4137                  LogDebug(BCLog::NET, "  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4138                  break;
4139              }
4140              // If pruning, don't inv blocks unless we have on disk and are likely to still have
4141              // for some reasonable time window (1 hour) that block relay might require.
4142              const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
4143              if (m_chainman.m_blockman.IsPruneMode() && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave)) {
4144                  LogDebug(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4145                  break;
4146              }
4147              WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
4148              if (--nLimit <= 0) {
4149                  // When this block is requested, we'll send an inv that'll
4150                  // trigger the peer to getblocks the next batch of inventory.
4151                  LogDebug(BCLog::NET, "  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4152                  WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();});
4153                  break;
4154              }
4155          }
4156          return;
4157      }
4158  
4159      if (msg_type == NetMsgType::GETBLOCKTXN) {
4160          BlockTransactionsRequest req;
4161          vRecv >> req;
4162  
4163          std::shared_ptr<const CBlock> recent_block;
4164          {
4165              LOCK(m_most_recent_block_mutex);
4166              if (m_most_recent_block_hash == req.blockhash)
4167                  recent_block = m_most_recent_block;
4168              // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion
4169          }
4170          if (recent_block) {
4171              SendBlockTransactions(pfrom, *peer, *recent_block, req);
4172              return;
4173          }
4174  
4175          FlatFilePos block_pos{};
4176          {
4177              LOCK(cs_main);
4178  
4179              const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
4180              if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4181                  LogDebug(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId());
4182                  return;
4183              }
4184  
4185              if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
4186                  block_pos = pindex->GetBlockPos();
4187              }
4188          }
4189  
4190          if (!block_pos.IsNull()) {
4191              CBlock block;
4192              const bool ret{m_chainman.m_blockman.ReadBlock(block, block_pos, /*expected_hash=*/ req.blockhash, /*lowprio=*/true)};
4193              // If height is above MAX_BLOCKTXN_DEPTH then this block cannot get
4194              // pruned after we release cs_main above, so this read should never fail.
4195              assert(ret);
4196  
4197              SendBlockTransactions(pfrom, *peer, block, req);
4198              return;
4199          }
4200  
4201          // If an older block is requested (should never happen in practice,
4202          // but can happen in tests) send a block response instead of a
4203          // blocktxn response. Sending a full block response instead of a
4204          // small blocktxn response is preferable in the case where a peer
4205          // might maliciously send lots of getblocktxn requests to trigger
4206          // expensive disk reads, because it will require the peer to
4207          // actually receive all the data read from disk over the network.
4208          LogDebug(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
4209          CInv inv{MSG_WITNESS_BLOCK, req.blockhash};
4210          WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv));
4211          // The message processing loop will go around again (without pausing) and we'll respond then
4212          return;
4213      }
4214  
4215      if (msg_type == NetMsgType::GETHEADERS) {
4216          CBlockLocator locator;
4217          uint256 hashStop;
4218          vRecv >> locator >> hashStop;
4219  
4220          if (locator.vHave.size() > MAX_LOCATOR_SZ) {
4221              LogDebug(BCLog::NET, "getheaders locator size %lld > %d, %s\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.DisconnectMsg(fLogIPs));
4222              pfrom.fDisconnect = true;
4223              return;
4224          }
4225  
4226          if (m_chainman.m_blockman.LoadingBlocks()) {
4227              LogDebug(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId());
4228              return;
4229          }
4230  
4231          LOCK(cs_main);
4232  
4233          // Note that if we were to be on a chain that forks from the checkpointed
4234          // chain, then serving those headers to a peer that has seen the
4235          // checkpointed chain would cause that peer to disconnect us. Requiring
4236          // that our chainwork exceed the minimum chain work is a protection against
4237          // being fed a bogus chain when we started up for the first time and
4238          // getting partitioned off the honest network for serving that chain to
4239          // others.
4240          if (m_chainman.ActiveTip() == nullptr ||
4241                  (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && !pfrom.HasPermission(NetPermissionFlags::Download))) {
4242              LogDebug(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId());
4243              // Just respond with an empty headers message, to tell the peer to
4244              // go away but not treat us as unresponsive.
4245              MakeAndPushMessage(pfrom, NetMsgType::HEADERS, std::vector<CBlockHeader>());
4246              return;
4247          }
4248  
4249          CNodeState *nodestate = State(pfrom.GetId());
4250          const CBlockIndex* pindex = nullptr;
4251          if (locator.IsNull())
4252          {
4253              // If locator is null, return the hashStop block
4254              pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
4255              if (!pindex) {
4256                  return;
4257              }
4258  
4259              if (!BlockRequestAllowed(pindex)) {
4260                  LogDebug(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId());
4261                  return;
4262              }
4263          }
4264          else
4265          {
4266              // Find the last block the caller has in the main chain
4267              pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
4268              if (pindex)
4269                  pindex = m_chainman.ActiveChain().Next(pindex);
4270          }
4271  
4272          // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4273          std::vector<CBlock> vHeaders;
4274          int nLimit = m_opts.max_headers_result;
4275          LogDebug(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId());
4276          for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
4277          {
4278              vHeaders.emplace_back(pindex->GetBlockHeader());
4279              if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4280                  break;
4281          }
4282          // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR
4283          // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty
4284          // headers message). In both cases it's safe to update
4285          // pindexBestHeaderSent to be our tip.
4286          //
4287          // It is important that we simply reset the BestHeaderSent value here,
4288          // and not max(BestHeaderSent, newHeaderSent). We might have announced
4289          // the currently-being-connected tip using a compact block, which
4290          // resulted in the peer sending a headers request, which we respond to
4291          // without the new block. By resetting the BestHeaderSent, we ensure we
4292          // will re-announce the new block via headers (or compact blocks again)
4293          // in the SendMessages logic.
4294          nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip();
4295          MakeAndPushMessage(pfrom, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders));
4296          return;
4297      }
4298  
4299      if (msg_type == NetMsgType::TX) {
4300          if (RejectIncomingTxs(pfrom)) {
4301              LogDebug(BCLog::NET, "transaction sent in violation of protocol, %s", pfrom.DisconnectMsg(fLogIPs));
4302              pfrom.fDisconnect = true;
4303              return;
4304          }
4305  
4306          // Stop processing the transaction early if we are still in IBD since we don't
4307          // have enough information to validate it yet. Sending unsolicited transactions
4308          // is not considered a protocol violation, so don't punish the peer.
4309          if (m_chainman.IsInitialBlockDownload()) return;
4310  
4311          CTransactionRef ptx;
4312          vRecv >> TX_WITH_WITNESS(ptx);
4313          const CTransaction& tx = *ptx;
4314  
4315          const uint256& txid = ptx->GetHash();
4316          const uint256& wtxid = ptx->GetWitnessHash();
4317  
4318          const uint256& hash = peer->m_wtxid_relay ? wtxid : txid;
4319          AddKnownTx(*peer, hash);
4320  
4321          LOCK2(cs_main, m_tx_download_mutex);
4322  
4323          const auto& [should_validate, package_to_validate] = m_txdownloadman.ReceivedTx(pfrom.GetId(), ptx);
4324          if (!should_validate) {
4325              if (pfrom.HasPermission(NetPermissionFlags::ForceRelay)) {
4326                  // Always relay transactions received from peers with forcerelay
4327                  // permission, even if they were already in the mempool, allowing
4328                  // the node to function as a gateway for nodes hidden behind it.
4329                  if (!m_mempool.exists(GenTxid::Txid(tx.GetHash()))) {
4330                      LogPrintf("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n",
4331                                tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId());
4332                  } else {
4333                      LogPrintf("Force relaying tx %s (wtxid=%s) from peer=%d\n",
4334                                tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId());
4335                      RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
4336                  }
4337              }
4338  
4339              if (package_to_validate) {
4340                  const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)};
4341                  LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(),
4342                           package_result.m_state.IsValid() ? "package accepted" : "package rejected");
4343                  ProcessPackageResult(package_to_validate.value(), package_result);
4344              }
4345              return;
4346          }
4347  
4348          // ReceivedTx should not be telling us to validate the tx and a package.
4349          Assume(!package_to_validate.has_value());
4350  
4351          const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx);
4352          const TxValidationState& state = result.m_state;
4353  
4354          if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
4355              ProcessValidTx(pfrom.GetId(), ptx, result.m_replaced_transactions);
4356              pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
4357          }
4358          if (state.IsInvalid()) {
4359              if (auto package_to_validate{ProcessInvalidTx(pfrom.GetId(), ptx, state, /*first_time_failure=*/true)}) {
4360                  const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)};
4361                  LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(),
4362                           package_result.m_state.IsValid() ? "package accepted" : "package rejected");
4363                  ProcessPackageResult(package_to_validate.value(), package_result);
4364              }
4365          }
4366  
4367          return;
4368      }
4369  
4370      if (msg_type == NetMsgType::CMPCTBLOCK)
4371      {
4372          // Ignore cmpctblock received while importing
4373          if (m_chainman.m_blockman.LoadingBlocks()) {
4374              LogDebug(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId());
4375              return;
4376          }
4377  
4378          CBlockHeaderAndShortTxIDs cmpctblock;
4379          vRecv >> cmpctblock;
4380  
4381          bool received_new_header = false;
4382          const auto blockhash = cmpctblock.header.GetHash();
4383  
4384          {
4385          LOCK(cs_main);
4386  
4387          const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock);
4388          if (!prev_block) {
4389              // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
4390              if (!m_chainman.IsInitialBlockDownload()) {
4391                  MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer);
4392              }
4393              return;
4394          } else if (prev_block->nChainWork + CalculateClaimedHeadersWork({{cmpctblock.header}}) < GetAntiDoSWorkThreshold()) {
4395              // If we get a low-work header in a compact block, we can ignore it.
4396              LogDebug(BCLog::NET, "Ignoring low-work compact block from peer %d\n", pfrom.GetId());
4397              return;
4398          }
4399  
4400          if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) {
4401              received_new_header = true;
4402          }
4403          }
4404  
4405          const CBlockIndex *pindex = nullptr;
4406          BlockValidationState state;
4407          if (!m_chainman.ProcessNewBlockHeaders({{cmpctblock.header}}, /*min_pow_checked=*/true, state, &pindex)) {
4408              if (state.IsInvalid()) {
4409                  MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block=*/true, "invalid header via cmpctblock");
4410                  return;
4411              }
4412          }
4413  
4414          if (received_new_header) {
4415              LogInfo("Saw new cmpctblock header hash=%s peer=%d\n",
4416                  blockhash.ToString(), pfrom.GetId());
4417          }
4418  
4419          bool fProcessBLOCKTXN = false;
4420  
4421          // If we end up treating this as a plain headers message, call that as well
4422          // without cs_main.
4423          bool fRevertToHeaderProcessing = false;
4424  
4425          // Keep a CBlock for "optimistic" compactblock reconstructions (see
4426          // below)
4427          std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4428          bool fBlockReconstructed = false;
4429  
4430          {
4431          LOCK(cs_main);
4432          // If AcceptBlockHeader returned true, it set pindex
4433          assert(pindex);
4434          UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
4435  
4436          CNodeState *nodestate = State(pfrom.GetId());
4437  
4438          // If this was a new header with more work than our tip, update the
4439          // peer's last block announcement time
4440          if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
4441              nodestate->m_last_block_announcement = GetTime();
4442          }
4443  
4444          if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
4445              return;
4446  
4447          auto range_flight = mapBlocksInFlight.equal_range(pindex->GetBlockHash());
4448          size_t already_in_flight = std::distance(range_flight.first, range_flight.second);
4449          bool requested_block_from_this_peer{false};
4450  
4451          // Multimap ensures ordering of outstanding requests. It's either empty or first in line.
4452          bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId());
4453  
4454          while (range_flight.first != range_flight.second) {
4455              if (range_flight.first->second.first == pfrom.GetId()) {
4456                  requested_block_from_this_peer = true;
4457                  break;
4458              }
4459              range_flight.first++;
4460          }
4461  
4462          if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better
4463                  pindex->nTx != 0) { // We had this block at some point, but pruned it
4464              if (requested_block_from_this_peer) {
4465                  // We requested this block for some reason, but our mempool will probably be useless
4466                  // so we just grab the block via normal getdata
4467                  std::vector<CInv> vInv(1);
4468                  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash);
4469                  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4470              }
4471              return;
4472          }
4473  
4474          // If we're not close to tip yet, give up and let parallel block fetch work its magic
4475          if (!already_in_flight && !CanDirectFetch()) {
4476              return;
4477          }
4478  
4479          // We want to be a bit conservative just to be extra careful about DoS
4480          // possibilities in compact block processing...
4481          if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
4482              if ((already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK && nodestate->vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
4483                   requested_block_from_this_peer) {
4484                  std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
4485                  if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) {
4486                      if (!(*queuedBlockIt)->partialBlock)
4487                          (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool));
4488                      else {
4489                          // The block was already in flight using compact blocks from the same peer
4490                          LogDebug(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
4491                          return;
4492                      }
4493                  }
4494  
4495                  PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
4496                  ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
4497                  if (status == READ_STATUS_INVALID) {
4498                      RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect
4499                      Misbehaving(*peer, "invalid compact block");
4500                      return;
4501                  } else if (status == READ_STATUS_FAILED) {
4502                      if (first_in_flight)  {
4503                          // Duplicate txindexes, the block is now in-flight, so just request it
4504                          std::vector<CInv> vInv(1);
4505                          vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash);
4506                          MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4507                      } else {
4508                          // Give up for this peer and wait for other peer(s)
4509                          RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId());
4510                      }
4511                      return;
4512                  }
4513  
4514                  BlockTransactionsRequest req;
4515                  for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
4516                      if (!partialBlock.IsTxAvailable(i))
4517                          req.indexes.push_back(i);
4518                  }
4519                  if (req.indexes.empty()) {
4520                      fProcessBLOCKTXN = true;
4521                  } else if (first_in_flight) {
4522                      // We will try to round-trip any compact blocks we get on failure,
4523                      // as long as it's first...
4524                      req.blockhash = pindex->GetBlockHash();
4525                      MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
4526                  } else if (pfrom.m_bip152_highbandwidth_to &&
4527                      (!pfrom.IsInboundConn() ||
4528                      IsBlockRequestedFromOutbound(blockhash) ||
4529                      already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK - 1)) {
4530                      // ... or it's a hb relay peer and:
4531                      // - peer is outbound, or
4532                      // - we already have an outbound attempt in flight(so we'll take what we can get), or
4533                      // - it's not the final parallel download slot (which we may reserve for first outbound)
4534                      req.blockhash = pindex->GetBlockHash();
4535                      MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
4536                  } else {
4537                      // Give up for this peer and wait for other peer(s)
4538                      RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId());
4539                  }
4540              } else {
4541                  // This block is either already in flight from a different
4542                  // peer, or this peer has too many blocks outstanding to
4543                  // download from.
4544                  // Optimistically try to reconstruct anyway since we might be
4545                  // able to without any round trips.
4546                  PartiallyDownloadedBlock tempBlock(&m_mempool);
4547                  ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
4548                  if (status != READ_STATUS_OK) {
4549                      // TODO: don't ignore failures
4550                      return;
4551                  }
4552                  std::vector<CTransactionRef> dummy;
4553                  const CBlockIndex* prev_block{Assume(m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock))};
4554                  status = tempBlock.FillBlock(*pblock, dummy,
4555                                               /*segwit_active=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT));
4556                  if (status == READ_STATUS_OK) {
4557                      fBlockReconstructed = true;
4558                  }
4559              }
4560          } else {
4561              if (requested_block_from_this_peer) {
4562                  // We requested this block, but its far into the future, so our
4563                  // mempool will probably be useless - request the block normally
4564                  std::vector<CInv> vInv(1);
4565                  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash);
4566                  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4567                  return;
4568              } else {
4569                  // If this was an announce-cmpctblock, we want the same treatment as a header message
4570                  fRevertToHeaderProcessing = true;
4571              }
4572          }
4573          } // cs_main
4574  
4575          if (fProcessBLOCKTXN) {
4576              BlockTransactions txn;
4577              txn.blockhash = blockhash;
4578              return ProcessCompactBlockTxns(pfrom, *peer, txn);
4579          }
4580  
4581          if (fRevertToHeaderProcessing) {
4582              // Headers received from HB compact block peers are permitted to be
4583              // relayed before full validation (see BIP 152), so we don't want to disconnect
4584              // the peer if the header turns out to be for an invalid block.
4585              // Note that if a peer tries to build on an invalid chain, that
4586              // will be detected and the peer will be disconnected/discouraged.
4587              return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true);
4588          }
4589  
4590          if (fBlockReconstructed) {
4591              // If we got here, we were able to optimistically reconstruct a
4592              // block that is in flight from some other peer.
4593              {
4594                  LOCK(cs_main);
4595                  mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false));
4596              }
4597              // Setting force_processing to true means that we bypass some of
4598              // our anti-DoS protections in AcceptBlock, which filters
4599              // unrequested blocks that might be trying to waste our resources
4600              // (eg disk space). Because we only try to reconstruct blocks when
4601              // we're close to caught up (via the CanDirectFetch() requirement
4602              // above, combined with the behavior of not requesting blocks until
4603              // we have a chain with at least the minimum chain work), and we ignore
4604              // compact blocks with less work than our tip, it is safe to treat
4605              // reconstructed compact blocks as having been requested.
4606              ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
4607              LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
4608              if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
4609                  // Clear download state for this block, which is in
4610                  // process from some other peer.  We do this after calling
4611                  // ProcessNewBlock so that a malleated cmpctblock announcement
4612                  // can't be used to interfere with block relay.
4613                  RemoveBlockRequest(pblock->GetHash(), std::nullopt);
4614              }
4615          }
4616          return;
4617      }
4618  
4619      if (msg_type == NetMsgType::BLOCKTXN)
4620      {
4621          // Ignore blocktxn received while importing
4622          if (m_chainman.m_blockman.LoadingBlocks()) {
4623              LogDebug(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId());
4624              return;
4625          }
4626  
4627          BlockTransactions resp;
4628          vRecv >> resp;
4629  
4630          return ProcessCompactBlockTxns(pfrom, *peer, resp);
4631      }
4632  
4633      if (msg_type == NetMsgType::HEADERS)
4634      {
4635          // Ignore headers received while importing
4636          if (m_chainman.m_blockman.LoadingBlocks()) {
4637              LogDebug(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
4638              return;
4639          }
4640  
4641          std::vector<CBlockHeader> headers;
4642  
4643          // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4644          unsigned int nCount = ReadCompactSize(vRecv);
4645          if (nCount > m_opts.max_headers_result) {
4646              Misbehaving(*peer, strprintf("headers message size = %u", nCount));
4647              return;
4648          }
4649          headers.resize(nCount);
4650          for (unsigned int n = 0; n < nCount; n++) {
4651              vRecv >> headers[n];
4652              ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4653          }
4654  
4655          ProcessHeadersMessage(pfrom, *peer, std::move(headers), /*via_compact_block=*/false);
4656  
4657          // Check if the headers presync progress needs to be reported to validation.
4658          // This needs to be done without holding the m_headers_presync_mutex lock.
4659          if (m_headers_presync_should_signal.exchange(false)) {
4660              HeadersPresyncStats stats;
4661              {
4662                  LOCK(m_headers_presync_mutex);
4663                  auto it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
4664                  if (it != m_headers_presync_stats.end()) stats = it->second;
4665              }
4666              if (stats.second) {
4667                  m_chainman.ReportHeadersPresync(stats.first, stats.second->first, stats.second->second);
4668              }
4669          }
4670  
4671          return;
4672      }
4673  
4674      if (msg_type == NetMsgType::BLOCK)
4675      {
4676          // Ignore block received while importing
4677          if (m_chainman.m_blockman.LoadingBlocks()) {
4678              LogDebug(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId());
4679              return;
4680          }
4681  
4682          std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4683          vRecv >> TX_WITH_WITNESS(*pblock);
4684  
4685          LogDebug(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId());
4686  
4687          const CBlockIndex* prev_block{WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};
4688  
4689          // Check for possible mutation if it connects to something we know so we can check for DEPLOYMENT_SEGWIT being active.
4690          // The fork chain always expects the witness commitment (its blocks
4691          // carry witness data from the very first fork block, long before the
4692          // inherited mainnet SEGWIT height would be "active"), so the receipt
4693          // check must mirror ContextualCheckBlock's segwit_expected.
4694          const bool check_witness_root = DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT)
4695              || IsForkActive(prev_block, m_chainman.GetParams().GetConsensus());
4696          if (prev_block && IsBlockMutated(/*block=*/*pblock, check_witness_root)) {
4697              LogDebug(BCLog::NET, "Received mutated block from peer=%d\n", peer->m_id);
4698              Misbehaving(*peer, "mutated block");
4699              WITH_LOCK(cs_main, RemoveBlockRequest(pblock->GetHash(), peer->m_id));
4700              return;
4701          }
4702  
4703          bool forceProcessing = false;
4704          const uint256 hash(pblock->GetHash());
4705          bool min_pow_checked = false;
4706          {
4707              LOCK(cs_main);
4708              // Always process the block if we requested it, since we may
4709              // need it even when it's not a candidate for a new best tip.
4710              forceProcessing = IsBlockRequested(hash);
4711              RemoveBlockRequest(hash, pfrom.GetId());
4712              // mapBlockSource is only used for punishing peers and setting
4713              // which peers send us compact blocks, so the race between here and
4714              // cs_main in ProcessNewBlock is fine.
4715              mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
4716  
4717              // Check claimed work on this block against our anti-dos thresholds.
4718              if (prev_block && prev_block->nChainWork + CalculateClaimedHeadersWork({{pblock->GetBlockHeader()}}) >= GetAntiDoSWorkThreshold()) {
4719                  min_pow_checked = true;
4720              }
4721          }
4722          ProcessBlock(pfrom, pblock, forceProcessing, min_pow_checked);
4723          return;
4724      }
4725  
4726      if (msg_type == NetMsgType::GETADDR) {
4727          // This asymmetric behavior for inbound and outbound connections was introduced
4728          // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4729          // to users' AddrMan and later request them by sending getaddr messages.
4730          // Making nodes which are behind NAT and can only make outgoing connections ignore
4731          // the getaddr message mitigates the attack.
4732          if (!pfrom.IsInboundConn()) {
4733              LogDebug(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId());
4734              return;
4735          }
4736  
4737          // Since this must be an inbound connection, SetupAddressRelay will
4738          // never fail.
4739          Assume(SetupAddressRelay(pfrom, *peer));
4740  
4741          // Only send one GetAddr response per connection to reduce resource waste
4742          // and discourage addr stamping of INV announcements.
4743          if (peer->m_getaddr_recvd) {
4744              LogDebug(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId());
4745              return;
4746          }
4747          peer->m_getaddr_recvd = true;
4748  
4749          peer->m_addrs_to_send.clear();
4750          std::vector<CAddress> vAddr;
4751          if (pfrom.HasPermission(NetPermissionFlags::Addr)) {
4752              vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /*network=*/std::nullopt);
4753          } else {
4754              vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
4755          }
4756          for (const CAddress &addr : vAddr) {
4757              PushAddress(*peer, addr);
4758          }
4759          return;
4760      }
4761  
4762      if (msg_type == NetMsgType::MEMPOOL) {
4763          // Only process received mempool messages if we advertise NODE_BLOOM
4764          // or if the peer has mempool permissions.
4765          if (!(peer->m_our_services & NODE_BLOOM) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
4766          {
4767              if (!pfrom.HasPermission(NetPermissionFlags::NoBan))
4768              {
4769                  LogDebug(BCLog::NET, "mempool request with bloom filters disabled, %s\n", pfrom.DisconnectMsg(fLogIPs));
4770                  pfrom.fDisconnect = true;
4771              }
4772              return;
4773          }
4774  
4775          if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
4776          {
4777              if (!pfrom.HasPermission(NetPermissionFlags::NoBan))
4778              {
4779                  LogDebug(BCLog::NET, "mempool request with bandwidth limit reached, %s\n", pfrom.DisconnectMsg(fLogIPs));
4780                  pfrom.fDisconnect = true;
4781              }
4782              return;
4783          }
4784  
4785          if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4786              LOCK(tx_relay->m_tx_inventory_mutex);
4787              tx_relay->m_send_mempool = true;
4788          }
4789          return;
4790      }
4791  
4792      if (msg_type == NetMsgType::PING) {
4793          if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
4794              uint64_t nonce = 0;
4795              vRecv >> nonce;
4796              // Echo the message back with the nonce. This allows for two useful features:
4797              //
4798              // 1) A remote node can quickly check if the connection is operational
4799              // 2) Remote nodes can measure the latency of the network thread. If this node
4800              //    is overloaded it won't respond to pings quickly and the remote node can
4801              //    avoid sending us more work, like chain download requests.
4802              //
4803              // The nonce stops the remote getting confused between different pings: without
4804              // it, if the remote node sends a ping once per second and this node takes 5
4805              // seconds to respond to each, the 5th ping the remote sends would appear to
4806              // return very quickly.
4807              MakeAndPushMessage(pfrom, NetMsgType::PONG, nonce);
4808          }
4809          return;
4810      }
4811  
4812      if (msg_type == NetMsgType::PONG) {
4813          const auto ping_end = time_received;
4814          uint64_t nonce = 0;
4815          size_t nAvail = vRecv.in_avail();
4816          bool bPingFinished = false;
4817          std::string sProblem;
4818  
4819          if (nAvail >= sizeof(nonce)) {
4820              vRecv >> nonce;
4821  
4822              // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4823              if (peer->m_ping_nonce_sent != 0) {
4824                  if (nonce == peer->m_ping_nonce_sent) {
4825                      // Matching pong received, this ping is no longer outstanding
4826                      bPingFinished = true;
4827                      const auto ping_time = ping_end - peer->m_ping_start.load();
4828                      if (ping_time.count() >= 0) {
4829                          // Let connman know about this successful ping-pong
4830                          pfrom.PongReceived(ping_time);
4831                      } else {
4832                          // This should never happen
4833                          sProblem = "Timing mishap";
4834                      }
4835                  } else {
4836                      // Nonce mismatches are normal when pings are overlapping
4837                      sProblem = "Nonce mismatch";
4838                      if (nonce == 0) {
4839                          // This is most likely a bug in another implementation somewhere; cancel this ping
4840                          bPingFinished = true;
4841                          sProblem = "Nonce zero";
4842                      }
4843                  }
4844              } else {
4845                  sProblem = "Unsolicited pong without ping";
4846              }
4847          } else {
4848              // This is most likely a bug in another implementation somewhere; cancel this ping
4849              bPingFinished = true;
4850              sProblem = "Short payload";
4851          }
4852  
4853          if (!(sProblem.empty())) {
4854              LogDebug(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
4855                  pfrom.GetId(),
4856                  sProblem,
4857                  peer->m_ping_nonce_sent,
4858                  nonce,
4859                  nAvail);
4860          }
4861          if (bPingFinished) {
4862              peer->m_ping_nonce_sent = 0;
4863          }
4864          return;
4865      }
4866  
4867      if (msg_type == NetMsgType::FILTERLOAD) {
4868          if (!(peer->m_our_services & NODE_BLOOM)) {
4869              LogDebug(BCLog::NET, "filterload received despite not offering bloom services, %s\n", pfrom.DisconnectMsg(fLogIPs));
4870              pfrom.fDisconnect = true;
4871              return;
4872          }
4873          CBloomFilter filter;
4874          vRecv >> filter;
4875  
4876          if (!filter.IsWithinSizeConstraints())
4877          {
4878              // There is no excuse for sending a too-large filter
4879              Misbehaving(*peer, "too-large bloom filter");
4880          } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4881              {
4882                  LOCK(tx_relay->m_bloom_filter_mutex);
4883                  tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
4884                  tx_relay->m_relay_txs = true;
4885              }
4886              pfrom.m_bloom_filter_loaded = true;
4887              pfrom.m_relays_txs = true;
4888          }
4889          return;
4890      }
4891  
4892      if (msg_type == NetMsgType::FILTERADD) {
4893          if (!(peer->m_our_services & NODE_BLOOM)) {
4894              LogDebug(BCLog::NET, "filteradd received despite not offering bloom services, %s\n", pfrom.DisconnectMsg(fLogIPs));
4895              pfrom.fDisconnect = true;
4896              return;
4897          }
4898          std::vector<unsigned char> vData;
4899          vRecv >> vData;
4900  
4901          // Nodes must NEVER send a data item > MAX_SCRIPT_ELEMENT_SIZE bytes (the max size for a script data object,
4902          // and thus, the maximum size any matched object can have) in a filteradd message
4903          bool bad = false;
4904          if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
4905              bad = true;
4906          } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4907              LOCK(tx_relay->m_bloom_filter_mutex);
4908              if (tx_relay->m_bloom_filter) {
4909                  tx_relay->m_bloom_filter->insert(vData);
4910              } else {
4911                  bad = true;
4912              }
4913          }
4914          if (bad) {
4915              Misbehaving(*peer, "bad filteradd message");
4916          }
4917          return;
4918      }
4919  
4920      if (msg_type == NetMsgType::FILTERCLEAR) {
4921          if (!(peer->m_our_services & NODE_BLOOM)) {
4922              LogDebug(BCLog::NET, "filterclear received despite not offering bloom services, %s\n", pfrom.DisconnectMsg(fLogIPs));
4923              pfrom.fDisconnect = true;
4924              return;
4925          }
4926          auto tx_relay = peer->GetTxRelay();
4927          if (!tx_relay) return;
4928  
4929          {
4930              LOCK(tx_relay->m_bloom_filter_mutex);
4931              tx_relay->m_bloom_filter = nullptr;
4932              tx_relay->m_relay_txs = true;
4933          }
4934          pfrom.m_bloom_filter_loaded = false;
4935          pfrom.m_relays_txs = true;
4936          return;
4937      }
4938  
4939      if (msg_type == NetMsgType::FEEFILTER) {
4940          CAmount newFeeFilter = 0;
4941          vRecv >> newFeeFilter;
4942          if (MoneyRange(newFeeFilter)) {
4943              if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4944                  tx_relay->m_fee_filter_received = newFeeFilter;
4945              }
4946              LogDebug(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
4947          }
4948          return;
4949      }
4950  
4951      if (msg_type == NetMsgType::GETCFILTERS) {
4952          ProcessGetCFilters(pfrom, *peer, vRecv);
4953          return;
4954      }
4955  
4956      if (msg_type == NetMsgType::GETCFHEADERS) {
4957          ProcessGetCFHeaders(pfrom, *peer, vRecv);
4958          return;
4959      }
4960  
4961      if (msg_type == NetMsgType::GETCFCHECKPT) {
4962          ProcessGetCFCheckPt(pfrom, *peer, vRecv);
4963          return;
4964      }
4965  
4966      if (msg_type == NetMsgType::NOTFOUND) {
4967          unsigned int nCount = ReadCompactSize(vRecv);
4968          static constexpr unsigned int MAX_NOTFOUND_SZ = node::MAX_PEER_TX_ANNOUNCEMENTS + MAX_BLOCKS_IN_TRANSIT_PER_PEER;
4969          if (nCount > MAX_NOTFOUND_SZ) {
4970              Misbehaving(*peer, strprintf("notfound message size = %u", nCount));
4971              return;
4972          }
4973          std::vector<CInv> vInv;
4974          vInv.resize(nCount);
4975          for (unsigned int n = 0; n < nCount; n++) {
4976              vRecv >> vInv[n];
4977          }
4978          std::vector<uint256> tx_invs;
4979          for (CInv &inv : vInv) {
4980              if (inv.IsGenTxMsg()) {
4981                  tx_invs.emplace_back(inv.hash);
4982              }
4983          }
4984          LOCK(m_tx_download_mutex);
4985          m_txdownloadman.ReceivedNotFound(pfrom.GetId(), tx_invs);
4986          return;
4987      }
4988  
4989      // Ignore unknown commands for extensibility
4990      LogDebug(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
4991      return;
4992  }
4993  
4994  bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer)
4995  {
4996      {
4997          LOCK(peer.m_misbehavior_mutex);
4998  
4999          // There's nothing to do if the m_should_discourage flag isn't set
5000          if (!peer.m_should_discourage) return false;
5001  
5002          peer.m_should_discourage = false;
5003      } // peer.m_misbehavior_mutex
5004  
5005      if (pnode.HasPermission(NetPermissionFlags::NoBan)) {
5006          // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission
5007          LogWarning("Not punishing noban peer %d!", peer.m_id);
5008          return false;
5009      }
5010  
5011      if (pnode.IsManualConn()) {
5012          // We never disconnect or discourage manual peers for bad behavior
5013          LogWarning("Not punishing manually connected peer %d!", peer.m_id);
5014          return false;
5015      }
5016  
5017      if (pnode.addr.IsLocal()) {
5018          // We disconnect local peers for bad behavior but don't discourage (since that would discourage
5019          // all peers on the same local address)
5020          LogDebug(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n",
5021                   pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
5022          pnode.fDisconnect = true;
5023          return true;
5024      }
5025  
5026      // Normal case: Disconnect the peer and discourage all nodes sharing the address
5027      LogDebug(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id);
5028      if (m_banman) m_banman->Discourage(pnode.addr);
5029      m_connman.DisconnectNode(pnode.addr);
5030      return true;
5031  }
5032  
5033  bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
5034  {
5035      AssertLockNotHeld(m_tx_download_mutex);
5036      AssertLockHeld(g_msgproc_mutex);
5037  
5038      PeerRef peer = GetPeerRef(pfrom->GetId());
5039      if (peer == nullptr) return false;
5040  
5041      // For outbound connections, ensure that the initial VERSION message
5042      // has been sent first before processing any incoming messages
5043      if (!pfrom->IsInboundConn() && !peer->m_outbound_version_message_sent) return false;
5044  
5045      {
5046          LOCK(peer->m_getdata_requests_mutex);
5047          if (!peer->m_getdata_requests.empty()) {
5048              ProcessGetData(*pfrom, *peer, interruptMsgProc);
5049          }
5050      }
5051  
5052      const bool processed_orphan = ProcessOrphanTx(*peer);
5053  
5054      if (pfrom->fDisconnect)
5055          return false;
5056  
5057      if (processed_orphan) return true;
5058  
5059      // this maintains the order of responses
5060      // and prevents m_getdata_requests to grow unbounded
5061      {
5062          LOCK(peer->m_getdata_requests_mutex);
5063          if (!peer->m_getdata_requests.empty()) return true;
5064      }
5065  
5066      // Don't bother if send buffer is too full to respond anyway
5067      if (pfrom->fPauseSend) return false;
5068  
5069      auto poll_result{pfrom->PollMessage()};
5070      if (!poll_result) {
5071          // No message to process
5072          return false;
5073      }
5074  
5075      CNetMessage& msg{poll_result->first};
5076      bool fMoreWork = poll_result->second;
5077  
5078      TRACEPOINT(net, inbound_message,
5079          pfrom->GetId(),
5080          pfrom->m_addr_name.c_str(),
5081          pfrom->ConnectionTypeAsString().c_str(),
5082          msg.m_type.c_str(),
5083          msg.m_recv.size(),
5084          msg.m_recv.data()
5085      );
5086  
5087      if (m_opts.capture_messages) {
5088          CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true);
5089      }
5090  
5091      try {
5092          ProcessMessage(*pfrom, msg.m_type, msg.m_recv, msg.m_time, interruptMsgProc);
5093          if (interruptMsgProc) return false;
5094          {
5095              LOCK(peer->m_getdata_requests_mutex);
5096              if (!peer->m_getdata_requests.empty()) fMoreWork = true;
5097          }
5098          // Does this peer has an orphan ready to reconsider?
5099          // (Note: we may have provided a parent for an orphan provided
5100          //  by another peer that was already processed; in that case,
5101          //  the extra work may not be noticed, possibly resulting in an
5102          //  unnecessary 100ms delay)
5103          LOCK(m_tx_download_mutex);
5104          if (m_txdownloadman.HaveMoreWork(peer->m_id)) fMoreWork = true;
5105          peer->m_deserialization_failures = 0;
5106      } catch (const std::exception& e) {
5107          LogDebug(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size, e.what(), typeid(e).name());
5108          peer->m_deserialization_failures++;
5109          if (peer->m_deserialization_failures >= 5) {
5110              LogWarning("disconnecting peer=%d after %u deserialization failures\n", pfrom->GetId(), peer->m_deserialization_failures);
5111              pfrom->fDisconnect = true;
5112          }
5113      } catch (...) {
5114          LogDebug(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size);
5115          peer->m_deserialization_failures++;
5116          if (peer->m_deserialization_failures >= 5) {
5117              LogWarning("disconnecting peer=%d after %u deserialization failures\n", pfrom->GetId(), peer->m_deserialization_failures);
5118              pfrom->fDisconnect = true;
5119          }
5120      }
5121  
5122      return fMoreWork;
5123  }
5124  
5125  void PeerManagerImpl::ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds)
5126  {
5127      AssertLockHeld(cs_main);
5128  
5129      CNodeState &state = *State(pto.GetId());
5130  
5131      if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) {
5132          // This is an outbound peer subject to disconnection if they don't
5133          // announce a block with as much work as the current tip within
5134          // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
5135          // their chain has more work than ours, we should sync to it,
5136          // unless it's invalid, in which case we should find that out and
5137          // disconnect from them elsewhere).
5138          if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
5139              // The outbound peer has sent us a block with at least as much work as our current tip, so reset the timeout if it was set
5140              if (state.m_chain_sync.m_timeout != 0s) {
5141                  state.m_chain_sync.m_timeout = 0s;
5142                  state.m_chain_sync.m_work_header = nullptr;
5143                  state.m_chain_sync.m_sent_getheaders = false;
5144              }
5145          } else if (state.m_chain_sync.m_timeout == 0s || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
5146              // At this point we know that the outbound peer has either never sent us a block/header or they have, but its tip is behind ours
5147              // AND
5148              // we are noticing this for the first time (m_timeout is 0)
5149              // OR we noticed this at some point within the last CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds and set a timeout
5150              // for them, they caught up to our tip at the time of setting the timer but not to our current one (we've also advanced).
5151              // Either way, set a new timeout based on our current tip.
5152              state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
5153              state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
5154              state.m_chain_sync.m_sent_getheaders = false;
5155          } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) {
5156              // No evidence yet that our peer has synced to a chain with work equal to that
5157              // of our tip, when we first detected it was behind. Send a single getheaders
5158              // message to give the peer a chance to update us.
5159              if (state.m_chain_sync.m_sent_getheaders) {
5160                  // They've run out of time to catch up!
5161                  LogInfo("Outbound peer has old chain, best known block = %s, %s\n", state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", pto.DisconnectMsg(fLogIPs));
5162                  pto.fDisconnect = true;
5163              } else {
5164                  assert(state.m_chain_sync.m_work_header);
5165                  // Here, we assume that the getheaders message goes out,
5166                  // because it'll either go out or be skipped because of a
5167                  // getheaders in-flight already, in which case the peer should
5168                  // still respond to us with a sufficiently high work chain tip.
5169                  MaybeSendGetHeaders(pto,
5170                          GetLocator(state.m_chain_sync.m_work_header->pprev),
5171                          peer);
5172                  LogDebug(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString());
5173                  state.m_chain_sync.m_sent_getheaders = true;
5174                  // Bump the timeout to allow a response, which could clear the timeout
5175                  // (if the response shows the peer has synced), reset the timeout (if
5176                  // the peer syncs to the required work but not to our tip), or result
5177                  // in disconnect (if we advance to the timeout and pindexBestKnownBlock
5178                  // has not sufficiently progressed)
5179                  state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
5180              }
5181          }
5182      }
5183  }
5184  
5185  void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now)
5186  {
5187      // If we have any extra block-relay-only peers, disconnect the youngest unless
5188      // it's given us a block -- in which case, compare with the second-youngest, and
5189      // out of those two, disconnect the peer who least recently gave us a block.
5190      // The youngest block-relay-only peer would be the extra peer we connected
5191      // to temporarily in order to sync our tip; see net.cpp.
5192      // Note that we use higher nodeid as a measure for most recent connection.
5193      if (m_connman.GetExtraBlockRelayCount() > 0) {
5194          std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0};
5195  
5196          m_connman.ForEachNode([&](CNode* pnode) {
5197              if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return;
5198              if (pnode->GetId() > youngest_peer.first) {
5199                  next_youngest_peer = youngest_peer;
5200                  youngest_peer.first = pnode->GetId();
5201                  youngest_peer.second = pnode->m_last_block_time;
5202              }
5203          });
5204          NodeId to_disconnect = youngest_peer.first;
5205          if (youngest_peer.second > next_youngest_peer.second) {
5206              // Our newest block-relay-only peer gave us a block more recently;
5207              // disconnect our second youngest.
5208              to_disconnect = next_youngest_peer.first;
5209          }
5210          m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5211              AssertLockHeld(::cs_main);
5212              // Make sure we're not getting a block right now, and that
5213              // we've been connected long enough for this eviction to happen
5214              // at all.
5215              // Note that we only request blocks from a peer if we learn of a
5216              // valid headers chain with at least as much work as our tip.
5217              CNodeState *node_state = State(pnode->GetId());
5218              if (node_state == nullptr ||
5219                  (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->vBlocksInFlight.empty())) {
5220                  pnode->fDisconnect = true;
5221                  LogDebug(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n",
5222                           pnode->GetId(), count_seconds(pnode->m_last_block_time));
5223                  return true;
5224              } else {
5225                  LogDebug(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
5226                           pnode->GetId(), count_seconds(pnode->m_connected), node_state->vBlocksInFlight.size());
5227              }
5228              return false;
5229          });
5230      }
5231  
5232      // Check whether we have too many outbound-full-relay peers
5233      if (m_connman.GetExtraFullOutboundCount() > 0) {
5234          // If we have more outbound-full-relay peers than we target, disconnect one.
5235          // Pick the outbound-full-relay peer that least recently announced
5236          // us a new block, with ties broken by choosing the more recent
5237          // connection (higher node id)
5238          // Protect peers from eviction if we don't have another connection
5239          // to their network, counting both outbound-full-relay and manual peers.
5240          NodeId worst_peer = -1;
5241          int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
5242  
5243          m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_connman.GetNodesMutex()) {
5244              AssertLockHeld(::cs_main);
5245  
5246              // Only consider outbound-full-relay peers that are not already
5247              // marked for disconnection
5248              if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return;
5249              CNodeState *state = State(pnode->GetId());
5250              if (state == nullptr) return; // shouldn't be possible, but just in case
5251              // Don't evict our protected peers
5252              if (state->m_chain_sync.m_protect) return;
5253              // If this is the only connection on a particular network that is
5254              // OUTBOUND_FULL_RELAY or MANUAL, protect it.
5255              if (!m_connman.MultipleManualOrFullOutboundConns(pnode->addr.GetNetwork())) return;
5256              if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
5257                  worst_peer = pnode->GetId();
5258                  oldest_block_announcement = state->m_last_block_announcement;
5259              }
5260          });
5261          if (worst_peer != -1) {
5262              bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5263                  AssertLockHeld(::cs_main);
5264  
5265                  // Only disconnect a peer that has been connected to us for
5266                  // some reasonable fraction of our check-frequency, to give
5267                  // it time for new information to have arrived.
5268                  // Also don't disconnect any peer we're trying to download a
5269                  // block from.
5270                  CNodeState &state = *State(pnode->GetId());
5271                  if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.vBlocksInFlight.empty()) {
5272                      LogDebug(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
5273                      pnode->fDisconnect = true;
5274                      return true;
5275                  } else {
5276                      LogDebug(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
5277                               pnode->GetId(), count_seconds(pnode->m_connected), state.vBlocksInFlight.size());
5278                      return false;
5279                  }
5280              });
5281              if (disconnected) {
5282                  // If we disconnected an extra peer, that means we successfully
5283                  // connected to at least one peer after the last time we
5284                  // detected a stale tip. Don't try any more extra peers until
5285                  // we next detect a stale tip, to limit the load we put on the
5286                  // network from these extra connections.
5287                  m_connman.SetTryNewOutboundPeer(false);
5288              }
5289          }
5290      }
5291  }
5292  
5293  void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
5294  {
5295      LOCK(cs_main);
5296  
5297      auto now{GetTime<std::chrono::seconds>()};
5298  
5299      EvictExtraOutboundPeers(now);
5300  
5301      if (now > m_stale_tip_check_time) {
5302          // Check whether our tip is stale, and if so, allow using an extra
5303          // outbound peer
5304          if (!m_chainman.m_blockman.LoadingBlocks() && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
5305              LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
5306                        count_seconds(now - m_last_tip_update.load()));
5307              m_connman.SetTryNewOutboundPeer(true);
5308          } else if (m_connman.GetTryNewOutboundPeer()) {
5309              m_connman.SetTryNewOutboundPeer(false);
5310          }
5311          m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
5312      }
5313  
5314      if (!m_initial_sync_finished && CanDirectFetch()) {
5315          m_connman.StartExtraBlockRelayPeers();
5316          m_initial_sync_finished = true;
5317      }
5318  }
5319  
5320  void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now)
5321  {
5322      if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
5323          peer.m_ping_nonce_sent &&
5324          now > peer.m_ping_start.load() + TIMEOUT_INTERVAL)
5325      {
5326          // The ping timeout is using mocktime. To disable the check during
5327          // testing, increase -peertimeout.
5328          LogDebug(BCLog::NET, "ping timeout: %fs, %s", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), node_to.DisconnectMsg(fLogIPs));
5329          node_to.fDisconnect = true;
5330          return;
5331      }
5332  
5333      bool pingSend = false;
5334  
5335      if (peer.m_ping_queued) {
5336          // RPC ping request by user
5337          pingSend = true;
5338      }
5339  
5340      if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) {
5341          // Ping automatically sent as a latency probe & keepalive.
5342          pingSend = true;
5343      }
5344  
5345      if (pingSend) {
5346          uint64_t nonce;
5347          do {
5348              nonce = FastRandomContext().rand64();
5349          } while (nonce == 0);
5350          peer.m_ping_queued = false;
5351          peer.m_ping_start = now;
5352          if (node_to.GetCommonVersion() > BIP0031_VERSION) {
5353              peer.m_ping_nonce_sent = nonce;
5354              MakeAndPushMessage(node_to, NetMsgType::PING, nonce);
5355          } else {
5356              // Peer is too old to support ping command with nonce, pong will never arrive.
5357              peer.m_ping_nonce_sent = 0;
5358              MakeAndPushMessage(node_to, NetMsgType::PING);
5359          }
5360      }
5361  }
5362  
5363  void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time)
5364  {
5365      // Nothing to do for non-address-relay peers
5366      if (!peer.m_addr_relay_enabled) return;
5367  
5368      LOCK(peer.m_addr_send_times_mutex);
5369      // Periodically advertise our local address to the peer.
5370      if (fListen && !m_chainman.IsInitialBlockDownload() &&
5371          peer.m_next_local_addr_send < current_time) {
5372          // If we've sent before, clear the bloom filter for the peer, so that our
5373          // self-announcement will actually go out.
5374          // This might be unnecessary if the bloom filter has already rolled
5375          // over since our last self-announcement, but there is only a small
5376          // bandwidth cost that we can incur by doing this (which happens
5377          // once a day on average).
5378          if (peer.m_next_local_addr_send != 0us) {
5379              peer.m_addr_known->reset();
5380          }
5381          if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
5382              CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()};
5383              PushAddress(peer, local_addr);
5384          }
5385          peer.m_next_local_addr_send = current_time + m_rng.rand_exp_duration(AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
5386      }
5387  
5388      // We sent an `addr` message to this peer recently. Nothing more to do.
5389      if (current_time <= peer.m_next_addr_send) return;
5390  
5391      peer.m_next_addr_send = current_time + m_rng.rand_exp_duration(AVG_ADDRESS_BROADCAST_INTERVAL);
5392  
5393      if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) {
5394          // Should be impossible since we always check size before adding to
5395          // m_addrs_to_send. Recover by trimming the vector.
5396          peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND);
5397      }
5398  
5399      // Remove addr records that the peer already knows about, and add new
5400      // addrs to the m_addr_known filter on the same pass.
5401      auto addr_already_known = [&peer](const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) {
5402          bool ret = peer.m_addr_known->contains(addr.GetKey());
5403          if (!ret) peer.m_addr_known->insert(addr.GetKey());
5404          return ret;
5405      };
5406      peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known),
5407                             peer.m_addrs_to_send.end());
5408  
5409      // No addr messages to send
5410      if (peer.m_addrs_to_send.empty()) return;
5411  
5412      if (peer.m_wants_addrv2) {
5413          MakeAndPushMessage(node, NetMsgType::ADDRV2, CAddress::V2_NETWORK(peer.m_addrs_to_send));
5414      } else {
5415          MakeAndPushMessage(node, NetMsgType::ADDR, CAddress::V1_NETWORK(peer.m_addrs_to_send));
5416      }
5417      peer.m_addrs_to_send.clear();
5418  
5419      // we only send the big addr message once
5420      if (peer.m_addrs_to_send.capacity() > 40) {
5421          peer.m_addrs_to_send.shrink_to_fit();
5422      }
5423  }
5424  
5425  void PeerManagerImpl::MaybeSendSendHeaders(CNode& node, Peer& peer)
5426  {
5427      // Delay sending SENDHEADERS (BIP 130) until we're done with an
5428      // initial-headers-sync with this peer. Receiving headers announcements for
5429      // new blocks while trying to sync their headers chain is problematic,
5430      // because of the state tracking done.
5431      if (!peer.m_sent_sendheaders && node.GetCommonVersion() >= SENDHEADERS_VERSION) {
5432          LOCK(cs_main);
5433          CNodeState &state = *State(node.GetId());
5434          if (state.pindexBestKnownBlock != nullptr &&
5435                  state.pindexBestKnownBlock->nChainWork > m_chainman.MinimumChainWork()) {
5436              // Tell our peer we prefer to receive headers rather than inv's
5437              // We send this to non-NODE NETWORK peers as well, because even
5438              // non-NODE NETWORK peers can announce blocks (such as pruning
5439              // nodes)
5440              MakeAndPushMessage(node, NetMsgType::SENDHEADERS);
5441              peer.m_sent_sendheaders = true;
5442          }
5443      }
5444  }
5445  
5446  void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time)
5447  {
5448      if (m_opts.ignore_incoming_txs) return;
5449      if (pto.GetCommonVersion() < FEEFILTER_VERSION) return;
5450      if (!gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER)) return;
5451      // peers with the forcerelay permission should not filter txs to us
5452      if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return;
5453      // Don't send feefilter messages to outbound block-relay-only peers since they should never announce
5454      // transactions to us, regardless of feefilter state.
5455      if (pto.IsBlockOnlyConn()) return;
5456  
5457      CAmount currentFilter = m_mempool.GetMinFee().GetFeePerK();
5458  
5459      if (m_chainman.IsInitialBlockDownload()) {
5460          // Received tx-inv messages are discarded when the active
5461          // chainstate is in IBD, so tell the peer to not send them.
5462          currentFilter = MAX_MONEY;
5463      } else {
5464          static const CAmount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)};
5465          if (peer.m_fee_filter_sent == MAX_FILTER) {
5466              // Send the current filter if we sent MAX_FILTER previously
5467              // and made it out of IBD.
5468              peer.m_next_send_feefilter = 0us;
5469          }
5470      }
5471      if (current_time > peer.m_next_send_feefilter) {
5472          CAmount filterToSend = m_fee_filter_rounder.round(currentFilter);
5473          // We always have a fee filter of at least the min relay fee
5474          filterToSend = std::max(filterToSend, m_mempool.m_opts.min_relay_feerate.GetFeePerK());
5475          if (filterToSend != peer.m_fee_filter_sent) {
5476              MakeAndPushMessage(pto, NetMsgType::FEEFILTER, filterToSend);
5477              peer.m_fee_filter_sent = filterToSend;
5478          }
5479          peer.m_next_send_feefilter = current_time + m_rng.rand_exp_duration(AVG_FEEFILTER_BROADCAST_INTERVAL);
5480      }
5481      // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
5482      // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
5483      else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter &&
5484                  (currentFilter < 3 * peer.m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
5485          peer.m_next_send_feefilter = current_time + m_rng.randrange<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
5486      }
5487  }
5488  
5489  namespace {
5490  class CompareInvMempoolOrder
5491  {
5492      CTxMemPool* mp;
5493      bool m_wtxid_relay;
5494  public:
5495      explicit CompareInvMempoolOrder(CTxMemPool *_mempool, bool use_wtxid)
5496      {
5497          mp = _mempool;
5498          m_wtxid_relay = use_wtxid;
5499      }
5500  
5501      bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
5502      {
5503          /* As std::make_heap produces a max-heap, we want the entries with the
5504           * fewest ancestors/highest fee to sort later. */
5505          return mp->CompareDepthAndScore(*b, *a, m_wtxid_relay);
5506      }
5507  };
5508  } // namespace
5509  
5510  bool PeerManagerImpl::RejectIncomingTxs(const CNode& peer) const
5511  {
5512      // block-relay-only peers may never send txs to us
5513      if (peer.IsBlockOnlyConn()) return true;
5514      if (peer.IsFeelerConn()) return true;
5515      // In -blocksonly mode, peers need the 'relay' permission to send txs to us
5516      if (m_opts.ignore_incoming_txs && !peer.HasPermission(NetPermissionFlags::Relay)) return true;
5517      return false;
5518  }
5519  
5520  bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer)
5521  {
5522      // We don't participate in addr relay with outbound block-relay-only
5523      // connections to prevent providing adversaries with the additional
5524      // information of addr traffic to infer the link.
5525      if (node.IsBlockOnlyConn()) return false;
5526  
5527      if (!peer.m_addr_relay_enabled.exchange(true)) {
5528          // During version message processing (non-block-relay-only outbound peers)
5529          // or on first addr-related message we have received (inbound peers), initialize
5530          // m_addr_known.
5531          peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
5532      }
5533  
5534      return true;
5535  }
5536  
5537  bool PeerManagerImpl::SendMessages(CNode* pto)
5538  {
5539      AssertLockNotHeld(m_tx_download_mutex);
5540      AssertLockHeld(g_msgproc_mutex);
5541  
5542      PeerRef peer = GetPeerRef(pto->GetId());
5543      if (!peer) return false;
5544      const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
5545  
5546      // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
5547      // disconnect misbehaving peers even before the version handshake is complete.
5548      if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true;
5549  
5550      // Initiate version handshake for outbound connections
5551      if (!pto->IsInboundConn() && !peer->m_outbound_version_message_sent) {
5552          PushNodeVersion(*pto, *peer);
5553          peer->m_outbound_version_message_sent = true;
5554      }
5555  
5556      // Don't send anything until the version handshake is complete
5557      if (!pto->fSuccessfullyConnected || pto->fDisconnect)
5558          return true;
5559  
5560      const auto current_time{GetTime<std::chrono::microseconds>()};
5561  
5562      if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
5563          LogDebug(BCLog::NET, "addrfetch connection timeout, %s\n", pto->DisconnectMsg(fLogIPs));
5564          pto->fDisconnect = true;
5565          return true;
5566      }
5567  
5568      MaybeSendPing(*pto, *peer, current_time);
5569  
5570      // MaybeSendPing may have marked peer for disconnection
5571      if (pto->fDisconnect) return true;
5572  
5573      MaybeSendAddr(*pto, *peer, current_time);
5574  
5575      MaybeSendSendHeaders(*pto, *peer);
5576  
5577      {
5578          LOCK(cs_main);
5579  
5580          CNodeState &state = *State(pto->GetId());
5581  
5582          // Start block sync
5583          if (m_chainman.m_best_header == nullptr) {
5584              m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
5585          }
5586  
5587          // Determine whether we might try initial headers sync or parallel
5588          // block download from this peer -- this mostly affects behavior while
5589          // in IBD (once out of IBD, we sync from all peers).
5590          bool sync_blocks_and_headers_from_peer = false;
5591          if (state.fPreferredDownload) {
5592              sync_blocks_and_headers_from_peer = true;
5593          } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) {
5594              // Typically this is an inbound peer. If we don't have any outbound
5595              // peers, or if we aren't downloading any blocks from such peers,
5596              // then allow block downloads from this peer, too.
5597              // We prefer downloading blocks from outbound peers to avoid
5598              // putting undue load on (say) some home user who is just making
5599              // outbound connections to the network, but if our only source of
5600              // the latest blocks is from an inbound peer, we have to be sure to
5601              // eventually download it (and not just wait indefinitely for an
5602              // outbound peer to have it).
5603              if (m_num_preferred_download_peers == 0 || mapBlocksInFlight.empty()) {
5604                  sync_blocks_and_headers_from_peer = true;
5605              }
5606          }
5607  
5608          if (!state.fSyncStarted && CanServeBlocks(*peer) && !m_chainman.m_blockman.LoadingBlocks()) {
5609              // Only actively request headers from a single peer, unless we're close to today.
5610              if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->Time() > NodeClock::now() - 24h) {
5611                  const CBlockIndex* pindexStart = m_chainman.m_best_header;
5612                  /* If possible, start at the block preceding the currently
5613                     best known header.  This ensures that we always get a
5614                     non-empty list of headers back as long as the peer
5615                     is up-to-date.  With a non-empty response, we can initialise
5616                     the peer's known best block.  This wouldn't be possible
5617                     if we requested starting at m_chainman.m_best_header and
5618                     got back an empty response.  */
5619                  if (pindexStart->pprev)
5620                      pindexStart = pindexStart->pprev;
5621                  if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) {
5622                      LogDebug(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height);
5623  
5624                      state.fSyncStarted = true;
5625                      peer->m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
5626                          (
5627                           // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
5628                           // to maintain precision
5629                           std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
5630                           Ticks<std::chrono::seconds>(NodeClock::now() - m_chainman.m_best_header->Time()) / consensusParams.nPowTargetSpacing
5631                          );
5632                      nSyncStarted++;
5633                  }
5634              }
5635          }
5636  
5637          //
5638          // Try sending block announcements via headers
5639          //
5640          {
5641              // If we have no more than MAX_BLOCKS_TO_ANNOUNCE in our
5642              // list of block hashes we're relaying, and our peer wants
5643              // headers announcements, then find the first header
5644              // not yet known to our peer but would connect, and send.
5645              // If no header would connect, or if we have too many
5646              // blocks, or if the peer doesn't want headers, just
5647              // add all to the inv queue.
5648              LOCK(peer->m_block_inv_mutex);
5649              std::vector<CBlock> vHeaders;
5650              bool fRevertToInv = ((!peer->m_prefers_headers &&
5651                                   (!state.m_requested_hb_cmpctblocks || peer->m_blocks_for_headers_relay.size() > 1)) ||
5652                                   peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE);
5653              const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
5654              ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
5655  
5656              if (!fRevertToInv) {
5657                  bool fFoundStartingHeader = false;
5658                  // Try to find first header that our peer doesn't have, and
5659                  // then send all headers past that one.  If we come across any
5660                  // headers that aren't on m_chainman.ActiveChain(), give up.
5661                  for (const uint256& hash : peer->m_blocks_for_headers_relay) {
5662                      const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
5663                      assert(pindex);
5664                      if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
5665                          // Bail out if we reorged away from this block
5666                          fRevertToInv = true;
5667                          break;
5668                      }
5669                      if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
5670                          // This means that the list of blocks to announce don't
5671                          // connect to each other.
5672                          // This shouldn't really be possible to hit during
5673                          // regular operation (because reorgs should take us to
5674                          // a chain that has some block not on the prior chain,
5675                          // which should be caught by the prior check), but one
5676                          // way this could happen is by using invalidateblock /
5677                          // reconsiderblock repeatedly on the tip, causing it to
5678                          // be added multiple times to m_blocks_for_headers_relay.
5679                          // Robustly deal with this rare situation by reverting
5680                          // to an inv.
5681                          fRevertToInv = true;
5682                          break;
5683                      }
5684                      pBestIndex = pindex;
5685                      if (fFoundStartingHeader) {
5686                          // add this to the headers message
5687                          vHeaders.emplace_back(pindex->GetBlockHeader());
5688                      } else if (PeerHasHeader(&state, pindex)) {
5689                          continue; // keep looking for the first new block
5690                      } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
5691                          // Peer doesn't have this header but they do have the prior one.
5692                          // Start sending headers.
5693                          fFoundStartingHeader = true;
5694                          vHeaders.emplace_back(pindex->GetBlockHeader());
5695                      } else {
5696                          // Peer doesn't have this header or the prior one -- nothing will
5697                          // connect, so bail out.
5698                          fRevertToInv = true;
5699                          break;
5700                      }
5701                  }
5702              }
5703              if (!fRevertToInv && !vHeaders.empty()) {
5704                  if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
5705                      // We only send up to 1 block as header-and-ids, as otherwise
5706                      // probably means we're doing an initial-ish-sync or they're slow
5707                      LogDebug(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
5708                              vHeaders.front().GetHash().ToString(), pto->GetId());
5709  
5710                      std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
5711                      {
5712                          LOCK(m_most_recent_block_mutex);
5713                          if (m_most_recent_block_hash == pBestIndex->GetBlockHash()) {
5714                              cached_cmpctblock_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, *m_most_recent_compact_block);
5715                          }
5716                      }
5717                      if (cached_cmpctblock_msg.has_value()) {
5718                          PushMessage(*pto, std::move(cached_cmpctblock_msg.value()));
5719                      } else {
5720                          CBlock block;
5721                          const bool ret{m_chainman.m_blockman.ReadBlock(block, *pBestIndex, /*lowprio=*/true)};
5722                          assert(ret);
5723                          CBlockHeaderAndShortTxIDs cmpctblock{block, m_rng.rand64()};
5724                          MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK, cmpctblock);
5725                      }
5726                      state.pindexBestHeaderSent = pBestIndex;
5727                  } else if (peer->m_prefers_headers) {
5728                      if (vHeaders.size() > 1) {
5729                          LogDebug(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
5730                                  vHeaders.size(),
5731                                  vHeaders.front().GetHash().ToString(),
5732                                  vHeaders.back().GetHash().ToString(), pto->GetId());
5733                      } else {
5734                          LogDebug(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
5735                                  vHeaders.front().GetHash().ToString(), pto->GetId());
5736                      }
5737                      MakeAndPushMessage(*pto, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders));
5738                      state.pindexBestHeaderSent = pBestIndex;
5739                  } else
5740                      fRevertToInv = true;
5741              }
5742              if (fRevertToInv) {
5743                  // If falling back to using an inv, just try to inv the tip.
5744                  // The last entry in m_blocks_for_headers_relay was our tip at some point
5745                  // in the past.
5746                  if (!peer->m_blocks_for_headers_relay.empty()) {
5747                      const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back();
5748                      const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
5749                      assert(pindex);
5750  
5751                      // Warn if we're announcing a block that is not on the main chain.
5752                      // This should be very rare and could be optimized out.
5753                      // Just log for now.
5754                      if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
5755                          LogDebug(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
5756                              hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString());
5757                      }
5758  
5759                      // If the peer's chain has this block, don't inv it back.
5760                      if (!PeerHasHeader(&state, pindex)) {
5761                          peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
5762                          LogDebug(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
5763                              pto->GetId(), hashToAnnounce.ToString());
5764                      }
5765                  }
5766              }
5767              peer->m_blocks_for_headers_relay.clear();
5768          }
5769  
5770          //
5771          // Message: inventory
5772          //
5773          std::vector<CInv> vInv;
5774          {
5775              LOCK(peer->m_block_inv_mutex);
5776              vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_TARGET));
5777  
5778              // Add blocks
5779              for (const uint256& hash : peer->m_blocks_for_inv_relay) {
5780                  vInv.emplace_back(MSG_BLOCK, hash);
5781                  if (vInv.size() == MAX_INV_SZ) {
5782                      MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5783                      vInv.clear();
5784                  }
5785              }
5786              peer->m_blocks_for_inv_relay.clear();
5787          }
5788  
5789          if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
5790                  LOCK(tx_relay->m_tx_inventory_mutex);
5791                  // Check whether periodic sends should happen
5792                  bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
5793                  if (tx_relay->m_next_inv_send_time < current_time) {
5794                      fSendTrickle = true;
5795                      if (pto->IsInboundConn()) {
5796                          tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL, pto->m_network_key);
5797                      } else {
5798                          tx_relay->m_next_inv_send_time = current_time + m_rng.rand_exp_duration(OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
5799                      }
5800                  }
5801  
5802                  // Time to send but the peer has requested we not relay transactions.
5803                  if (fSendTrickle) {
5804                      LOCK(tx_relay->m_bloom_filter_mutex);
5805                      if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear();
5806                  }
5807  
5808                  // Respond to BIP35 mempool requests
5809                  if (fSendTrickle && tx_relay->m_send_mempool) {
5810                      auto vtxinfo = m_mempool.infoAll();
5811                      tx_relay->m_send_mempool = false;
5812                      const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
5813  
5814                      LOCK(tx_relay->m_bloom_filter_mutex);
5815  
5816                      for (const auto& txinfo : vtxinfo) {
5817                          CInv inv{
5818                              peer->m_wtxid_relay ? MSG_WTX : MSG_TX,
5819                              peer->m_wtxid_relay ?
5820                                  txinfo.tx->GetWitnessHash().ToUint256() :
5821                                  txinfo.tx->GetHash().ToUint256(),
5822                          };
5823                          tx_relay->m_tx_inventory_to_send.erase(inv.hash);
5824  
5825                          // Don't send transactions that peers will not put into their mempool
5826                          if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
5827                              continue;
5828                          }
5829                          if (tx_relay->m_bloom_filter) {
5830                              if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
5831                          }
5832                          tx_relay->m_tx_inventory_known_filter.insert(inv.hash);
5833                          vInv.push_back(inv);
5834                          if (vInv.size() == MAX_INV_SZ) {
5835                              MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5836                              vInv.clear();
5837                          }
5838                      }
5839                  }
5840  
5841                  // Determine transactions to relay
5842                  if (fSendTrickle) {
5843                      // Produce a vector with all candidates for sending
5844                      std::vector<std::set<uint256>::iterator> vInvTx;
5845                      vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
5846                      for (std::set<uint256>::iterator it = tx_relay->m_tx_inventory_to_send.begin(); it != tx_relay->m_tx_inventory_to_send.end(); it++) {
5847                          vInvTx.push_back(it);
5848                      }
5849                      const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
5850                      // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
5851                      // A heap is used so that not all items need sorting if only a few are being sent.
5852                      CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, peer->m_wtxid_relay);
5853                      std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
5854                      // No reason to drain out at many times the network's capacity,
5855                      // especially since we have many peers and some will draw much shorter delays.
5856                      unsigned int nRelayedTransactions = 0;
5857                      LOCK(tx_relay->m_bloom_filter_mutex);
5858                      size_t broadcast_max{INVENTORY_BROADCAST_TARGET + (tx_relay->m_tx_inventory_to_send.size()/1000)*5};
5859                      broadcast_max = std::min<size_t>(INVENTORY_BROADCAST_MAX, broadcast_max);
5860                      while (!vInvTx.empty() && nRelayedTransactions < broadcast_max) {
5861                          // Fetch the top element from the heap
5862                          std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
5863                          std::set<uint256>::iterator it = vInvTx.back();
5864                          vInvTx.pop_back();
5865                          uint256 hash = *it;
5866                          CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
5867                          // Remove it from the to-be-sent set
5868                          tx_relay->m_tx_inventory_to_send.erase(it);
5869                          // Check if not in the filter already
5870                          if (tx_relay->m_tx_inventory_known_filter.contains(hash)) {
5871                              continue;
5872                          }
5873                          // Not in the mempool anymore? don't bother sending it.
5874                          auto txinfo = m_mempool.info(ToGenTxid(inv));
5875                          if (!txinfo.tx) {
5876                              continue;
5877                          }
5878                          // Peer told you to not send transactions at that feerate? Don't bother sending it.
5879                          if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
5880                              continue;
5881                          }
5882                          if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
5883                          // Send
5884                          vInv.push_back(inv);
5885                          nRelayedTransactions++;
5886                          if (vInv.size() == MAX_INV_SZ) {
5887                              MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5888                              vInv.clear();
5889                          }
5890                          tx_relay->m_tx_inventory_known_filter.insert(hash);
5891                      }
5892  
5893                      // Ensure we'll respond to GETDATA requests for anything we've just announced
5894                      LOCK(m_mempool.cs);
5895                      tx_relay->m_last_inv_sequence = m_mempool.GetSequence();
5896                  }
5897          }
5898          if (!vInv.empty())
5899              MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5900  
5901          // Detect whether we're stalling
5902          auto stalling_timeout = m_block_stalling_timeout.load();
5903          if (state.m_stalling_since.count() && state.m_stalling_since < current_time - stalling_timeout) {
5904              // Stalling only triggers when the block download window cannot move. During normal steady state,
5905              // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5906              // should only happen during initial block download.
5907              LogInfo("Peer is stalling block download, %s\n", pto->DisconnectMsg(fLogIPs));
5908              pto->fDisconnect = true;
5909              // Increase timeout for the next peer so that we don't disconnect multiple peers if our own
5910              // bandwidth is insufficient.
5911              const auto new_timeout = std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX);
5912              if (stalling_timeout != new_timeout && m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) {
5913                  LogDebug(BCLog::NET, "Increased stalling timeout temporarily to %d seconds\n", count_seconds(new_timeout));
5914              }
5915              return true;
5916          }
5917          // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N)
5918          // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
5919          // We compensate for other peers to prevent killing off peers due to our own downstream link
5920          // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5921          // to unreasonably increase our timeout.
5922          if (state.vBlocksInFlight.size() > 0) {
5923              QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5924              int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1;
5925              if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
5926                  LogInfo("Timeout downloading block %s, %s\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->DisconnectMsg(fLogIPs));
5927                  pto->fDisconnect = true;
5928                  return true;
5929              }
5930          }
5931          // Check for headers sync timeouts
5932          if (state.fSyncStarted && peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
5933              // Detect whether this is a stalling initial-headers-sync peer
5934              if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {
5935                  if (current_time > peer->m_headers_sync_timeout && nSyncStarted == 1 && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)) {
5936                      // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
5937                      // and we have others we could be using instead.
5938                      // Note: If all our peers are inbound, then we won't
5939                      // disconnect our sync peer for stalling; we have bigger
5940                      // problems if we can't get any outbound peers.
5941                      if (!pto->HasPermission(NetPermissionFlags::NoBan)) {
5942                          LogInfo("Timeout downloading headers, %s\n", pto->DisconnectMsg(fLogIPs));
5943                          pto->fDisconnect = true;
5944                          return true;
5945                      } else {
5946                          LogInfo("Timeout downloading headers from noban peer, not %s\n", pto->DisconnectMsg(fLogIPs));
5947                          // Reset the headers sync state so that we have a
5948                          // chance to try downloading from a different peer.
5949                          // Note: this will also result in at least one more
5950                          // getheaders message to be sent to
5951                          // this peer (eventually).
5952                          state.fSyncStarted = false;
5953                          nSyncStarted--;
5954                          peer->m_headers_sync_timeout = 0us;
5955                      }
5956                  }
5957              } else {
5958                  // After we've caught up once, reset the timeout so we can't trigger
5959                  // disconnect later.
5960                  peer->m_headers_sync_timeout = std::chrono::microseconds::max();
5961              }
5962          }
5963  
5964          // Check that outbound peers have reasonable chains
5965          // GetTime() is used by this anti-DoS logic so we can test this using mocktime
5966          ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
5967  
5968          //
5969          // Message: getdata (blocks)
5970          //
5971          std::vector<CInv> vGetData;
5972          if (CanServeBlocks(*peer) && ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) || !m_chainman.IsInitialBlockDownload()) && state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5973              std::vector<const CBlockIndex*> vToDownload;
5974              NodeId staller = -1;
5975              auto get_inflight_budget = [&state]() {
5976                  return std::max(0, MAX_BLOCKS_IN_TRANSIT_PER_PEER - static_cast<int>(state.vBlocksInFlight.size()));
5977              };
5978  
5979              // If a snapshot chainstate is in use, we want to find its next blocks
5980              // before the background chainstate to prioritize getting to network tip.
5981              FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload, staller);
5982              if (m_chainman.BackgroundSyncInProgress() && !IsLimitedPeer(*peer)) {
5983                  // If the background tip is not an ancestor of the snapshot block,
5984                  // we need to start requesting blocks from their last common ancestor.
5985                  const CBlockIndex *from_tip = LastCommonAncestor(m_chainman.GetBackgroundSyncTip(), m_chainman.GetSnapshotBaseBlock());
5986                  TryDownloadingHistoricalBlocks(
5987                      *peer,
5988                      get_inflight_budget(),
5989                      vToDownload, from_tip,
5990                      Assert(m_chainman.GetSnapshotBaseBlock()));
5991              }
5992              for (const CBlockIndex *pindex : vToDownload) {
5993                  uint32_t nFetchFlags = GetFetchFlags(*peer);
5994                  vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash());
5995                  BlockRequested(pto->GetId(), *pindex);
5996                  LogDebug(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5997                      pindex->nHeight, pto->GetId());
5998              }
5999              if (state.vBlocksInFlight.empty() && staller != -1) {
6000                  if (State(staller)->m_stalling_since == 0us) {
6001                      State(staller)->m_stalling_since = current_time;
6002                      LogDebug(BCLog::NET, "Stall started peer=%d\n", staller);
6003                  }
6004              }
6005          }
6006  
6007          //
6008          // Message: getdata (transactions)
6009          //
6010          {
6011              LOCK(m_tx_download_mutex);
6012              for (const GenTxid& gtxid : m_txdownloadman.GetRequestsToSend(pto->GetId(), current_time)) {
6013                  vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*peer)), gtxid.GetHash());
6014                  if (vGetData.size() >= MAX_GETDATA_SZ) {
6015                      MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData);
6016                      vGetData.clear();
6017                  }
6018              }
6019          }
6020  
6021          if (!vGetData.empty())
6022              MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData);
6023      } // release cs_main
6024      MaybeSendFeefilter(*pto, *peer, current_time);
6025      return true;
6026  }
6027