LCOV - code coverage report
Current view: top level - src - net_processing.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 70.0 % 3042 2129
Test Date: 2024-09-01 05:20:30 Functions: 71.7 % 173 124
Branches: 41.2 % 5594 2305

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

Generated by: LCOV version 2.0-1