fuzz coverage

Coverage Report

Created: 2025-08-28 15:26

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