Coverage Report

Created: 2026-09-14 20:36

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