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