Coverage Report

Created: 2026-07-08 14:14

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