fuzz coverage

Coverage Report

Created: 2025-10-29 15:27

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