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