Coverage Report

Created: 2026-06-16 16:41

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