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 : 0 : 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 : 2 : TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
326 : : {
327 : 2 : LOCK(m_tx_relay_mutex);
328 [ + - ]: 2 : Assume(!m_tx_relay);
329 [ + - ]: 2 : m_tx_relay = std::make_unique<Peer::TxRelay>();
330 [ + - ]: 2 : return m_tx_relay.get();
331 : 2 : };
332 : :
333 : 9 : TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
334 : : {
335 [ + - + - ]: 10 : 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 : 27 : explicit Peer(NodeId id, ServiceFlags our_services, bool is_inbound)
419 : 27 : : m_id{id}
420 : 27 : , m_our_services{our_services}
421 [ + - ]: 27 : , m_is_inbound{is_inbound}
422 : 27 : {}
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 : 27 : 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 : 334 : InvToSendBucket(unsigned int rate, double mult)
529 : 334 : : count_floor{-1.0 * rate * count_seconds(INBOUND_INVENTORY_BROADCAST_INTERVAL)},
530 : 334 : size_bucket(/*rate=*/SIZE_REFILL * mult, /*value=*/SIZE_INIT, /*cap=*/SIZE_CAP),
531 : 334 : count_bucket(/*rate=*/rate * mult, /*value=*/rate * INBOUND_COUNT_SECONDS, /*cap=*/rate * INBOUND_COUNT_SECONDS)
532 : : {
533 : 334 : }
534 : :
535 : 10 : bool avail() const
536 : : {
537 [ - + - - : 10 : return !backlog.empty() && size_bucket.value() > 0 && count_bucket.value() > 0;
- - ]
538 : : }
539 : :
540 : 10 : void increment(NodeClock::time_point now)
541 : : {
542 : 10 : size_bucket.increment(now);
543 : 10 : count_bucket.increment(now);
544 : 10 : }
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 : 6 : PeerManagerInfo::InvBucketInfo info() const
556 : : {
557 : 6 : return {
558 : 9 : .backlog_count = backlog.size(),
559 : 6 : .count_bucket = count_bucket.value(),
560 : 6 : .size_bucket = size_bucket.value(),
561 [ - + + - ]: 3 : };
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 : 5 : void SetBestBlock(int height, std::chrono::seconds time) override
609 : : {
610 : 5 : m_best_height = height;
611 : 5 : m_best_block_time = time;
612 : 5 : };
613 [ + - + - ]: 12 : 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 : 0 : 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 : 23 : void MakeAndPushMessage(CNode& node, std::string msg_type, Args&&... args) const
803 : : {
804 [ + - + - ]: 46 : m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...));
805 : 23 : }
806 : : template <typename... Args>
807 : : [[maybe_unused]] 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 : 111 : const CNodeState* PeerManagerImpl::State(NodeId pnode) const
1197 : : {
1198 : 111 : std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
1199 [ + - ]: 111 : if (it == m_node_states.end())
1200 : : return nullptr;
1201 : 111 : return &it->second;
1202 : : }
1203 : :
1204 : 110 : CNodeState* PeerManagerImpl::State(NodeId pnode)
1205 : : {
1206 : 110 : 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 : 1 : static bool IsAddrCompatible(const Peer& peer, const CAddress& addr)
1215 : : {
1216 [ + - + - ]: 1 : return peer.m_wants_addrv2 || addr.IsAddrV1Compatible();
1217 : : }
1218 : :
1219 : 0 : void PeerManagerImpl::AddAddressKnown(Peer& peer, const CAddress& addr)
1220 : : {
1221 [ # # ]: 0 : assert(peer.m_addr_known);
1222 [ # # # # ]: 0 : peer.m_addr_known->insert(addr.GetKey());
1223 : 0 : }
1224 : :
1225 : 0 : 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 [ # # ]: 0 : assert(peer.m_addr_known);
1231 [ # # # # : 0 : if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) {
# # # # #
# # # #
# ]
1232 [ # # # # ]: 0 : 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 : 0 : peer.m_addrs_to_send.push_back(addr);
1236 : : }
1237 : : }
1238 : 0 : }
1239 : :
1240 : 0 : static void AddKnownTx(Peer& peer, const uint256& hash)
1241 : : {
1242 : 0 : auto tx_relay = peer.GetTxRelay();
1243 [ # # ]: 0 : if (!tx_relay) return;
1244 : :
1245 : 0 : LOCK(tx_relay->m_tx_inventory_mutex);
1246 [ # # ]: 0 : tx_relay->m_tx_inventory_known_filter.insert(hash);
1247 : 0 : }
1248 : :
1249 : : /** Whether this peer can serve us blocks. */
1250 : 12 : static bool CanServeBlocks(const Peer& peer)
1251 : : {
1252 : 12 : 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 : 5 : static bool IsLimitedPeer(const Peer& peer)
1258 : : {
1259 [ - + - - ]: 5 : return (!(peer.m_their_services & NODE_NETWORK) &&
1260 [ # # ]: 0 : (peer.m_their_services & NODE_NETWORK_LIMITED));
1261 : : }
1262 : :
1263 : : /** Whether this peer can serve us witness data */
1264 : 0 : static bool CanServeWitnesses(const Peer& peer)
1265 : : {
1266 : 0 : return peer.m_their_services & NODE_WITNESS;
1267 : : }
1268 : :
1269 : 0 : std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
1270 : : std::chrono::seconds average_interval,
1271 : : uint64_t network_key)
1272 : : {
1273 [ # # ]: 0 : auto [it, inserted] = m_next_inv_to_inbounds_per_network_key.try_emplace(network_key, 0us);
1274 [ # # ]: 0 : auto& timer{it->second};
1275 [ # # ]: 0 : if (timer < now) {
1276 : 0 : timer = now + m_rng.rand_exp_duration(average_interval);
1277 : : }
1278 : 0 : return timer;
1279 : : }
1280 : :
1281 : 0 : bool PeerManagerImpl::IsBlockRequested(const uint256& hash)
1282 : : {
1283 : 0 : 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 : 0 : void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer)
1298 : : {
1299 : 0 : auto range = mapBlocksInFlight.equal_range(hash);
1300 [ # # ]: 0 : 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 : 0 : Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK);
1307 : :
1308 [ # # ]: 0 : while (range.first != range.second) {
1309 [ # # ]: 0 : const auto& [node_id, list_it]{range.first->second};
1310 : :
1311 [ # # # # ]: 0 : if (from_peer && *from_peer != node_id) {
1312 : 0 : range.first++;
1313 : 0 : continue;
1314 : : }
1315 : :
1316 [ # # ]: 0 : CNodeState& state = *Assert(State(node_id));
1317 : :
1318 [ # # ]: 0 : if (state.vBlocksInFlight.begin() == list_it) {
1319 : : // First block on the queue was received, update the start download time for the next one
1320 : 0 : state.m_downloading_since = std::max(state.m_downloading_since, GetTime<std::chrono::microseconds>());
1321 : : }
1322 : 0 : state.vBlocksInFlight.erase(list_it);
1323 : :
1324 [ # # ]: 0 : if (state.vBlocksInFlight.empty()) {
1325 : : // Last validated block on the queue for this peer was received.
1326 : 0 : m_peers_downloading_from--;
1327 : : }
1328 : 0 : state.m_stalling_since = 0us;
1329 : :
1330 : 0 : range.first = mapBlocksInFlight.erase(range.first);
1331 : : }
1332 : : }
1333 : :
1334 : 0 : bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit)
1335 : : {
1336 : 0 : const uint256& hash{block.GetBlockHash()};
1337 : :
1338 : 0 : CNodeState *state = State(nodeid);
1339 [ # # ]: 0 : assert(state != nullptr);
1340 : :
1341 : 0 : Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK);
1342 : :
1343 : : // Short-circuit most stuff in case it is from the same node
1344 [ # # ]: 0 : for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) {
1345 [ # # ]: 0 : if (range.first->second.first == nodeid) {
1346 [ # # ]: 0 : if (pit) {
1347 : 0 : *pit = &range.first->second.second;
1348 : : }
1349 : 0 : return false;
1350 : : }
1351 : : }
1352 : :
1353 : : // Make sure it's not being fetched already from same peer.
1354 : 0 : RemoveBlockRequest(hash, nodeid);
1355 : :
1356 : 0 : 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 [ # # ]: 0 : if (state->vBlocksInFlight.size() == 1) {
1359 : : // We're starting a block download (batch) from this peer.
1360 : 0 : state->m_downloading_since = GetTime<std::chrono::microseconds>();
1361 : 0 : m_peers_downloading_from++;
1362 : : }
1363 : 0 : auto itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it)));
1364 [ # # ]: 0 : if (pit) {
1365 : 0 : *pit = &itInFlight->second.second;
1366 : : }
1367 : : return true;
1368 [ # # # # ]: 0 : }
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 : 3 : bool PeerManagerImpl::TipMayBeStale()
1430 : : {
1431 : 3 : AssertLockHeld(cs_main);
1432 : 3 : const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
1433 [ + + ]: 3 : if (m_last_tip_update.load() == 0s) {
1434 : 2 : m_last_tip_update = GetTime<std::chrono::seconds>();
1435 : : }
1436 [ + + - + ]: 3 : return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty();
1437 : : }
1438 : :
1439 : 7 : int64_t PeerManagerImpl::ApproximateBestBlockDepth() const
1440 : : {
1441 : 7 : return (GetTime<std::chrono::seconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing;
1442 : : }
1443 : :
1444 : 10 : bool PeerManagerImpl::CanDirectFetch()
1445 : : {
1446 [ - + ]: 20 : 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 : 11 : void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) {
1459 : 11 : CNodeState *state = State(nodeid);
1460 [ - + ]: 11 : assert(state != nullptr);
1461 : :
1462 [ - + ]: 22 : if (!state->hashLastUnknownBlock.IsNull()) {
1463 : 0 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
1464 [ # # # # ]: 0 : if (pindex && pindex->nChainWork > 0) {
1465 [ # # # # ]: 0 : if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1466 : 0 : state->pindexBestKnownBlock = pindex;
1467 : : }
1468 : 0 : state->hashLastUnknownBlock.SetNull();
1469 : : }
1470 : : }
1471 : 11 : }
1472 : :
1473 : 0 : void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
1474 : 0 : CNodeState *state = State(nodeid);
1475 [ # # ]: 0 : assert(state != nullptr);
1476 : :
1477 : 0 : ProcessBlockAvailability(nodeid);
1478 : :
1479 : 0 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
1480 [ # # # # ]: 0 : if (pindex && pindex->nChainWork > 0) {
1481 : : // An actually better block was announced.
1482 [ # # # # ]: 0 : if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1483 : 0 : state->pindexBestKnownBlock = pindex;
1484 : : }
1485 : : } else {
1486 : : // An unknown block was announced; just assume that the latest one is the best one.
1487 : 0 : state->hashLastUnknownBlock = hash;
1488 : : }
1489 : 0 : }
1490 : :
1491 : : // Logic for calculating which blocks to download from a given peer, given our current tip.
1492 : 5 : void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller)
1493 : : {
1494 [ + - ]: 5 : if (count == 0)
1495 : : return;
1496 : :
1497 [ - + ]: 5 : vBlocks.reserve(vBlocks.size() + count);
1498 : 5 : CNodeState *state = State(peer.m_id);
1499 [ - + ]: 5 : assert(state != nullptr);
1500 : :
1501 : : // Make sure pindexBestKnownBlock is up to date, we'll need it.
1502 : 5 : ProcessBlockAvailability(peer.m_id);
1503 : :
1504 [ - + - - : 5 : 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 : 5 : 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 : 0 : const CBlockIndex* snap_base{m_chainman.CurrentChainstate().SnapshotBase()};
1514 [ # # # # : 0 : 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 : 0 : auto fork_point = LastCommonAncestor(state->pindexBestKnownBlock, m_chainman.ActiveTip());
1525 [ # # ]: 0 : if (state->pindexLastCommonBlock == nullptr ||
1526 [ # # ]: 0 : fork_point->nChainWork > state->pindexLastCommonBlock->nChainWork ||
1527 [ # # ]: 0 : state->pindexBestKnownBlock->GetAncestor(state->pindexLastCommonBlock->nHeight) != state->pindexLastCommonBlock) {
1528 : 0 : state->pindexLastCommonBlock = fork_point;
1529 : : }
1530 [ # # ]: 0 : if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
1531 : : return;
1532 : :
1533 : 0 : 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 : 0 : int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1538 : :
1539 : 0 : 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 : 0 : 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 : 0 : std::vector<const CBlockIndex*> vToFetch;
1574 [ # # ]: 0 : int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1575 : 0 : bool is_limited_peer = IsLimitedPeer(peer);
1576 : 0 : NodeId waitingfor = -1;
1577 [ # # ]: 0 : 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 [ # # # # : 0 : int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
# # ]
1582 [ # # ]: 0 : vToFetch.resize(nToFetch);
1583 [ # # ]: 0 : pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
1584 : 0 : vToFetch[nToFetch - 1] = pindexWalk;
1585 [ # # ]: 0 : for (unsigned int i = nToFetch - 1; i > 0; i--) {
1586 : 0 : 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 [ # # ]: 0 : for (const CBlockIndex* pindex : vToFetch) {
1594 [ # # # # ]: 0 : if (!pindex->IsValid(BLOCK_VALID_TREE)) {
1595 : : // We consider the chain that this peer is on invalid.
1596 : : return;
1597 : : }
1598 : :
1599 [ # # # # ]: 0 : 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 [ # # # # : 0 : 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 [ # # ]: 0 : if (IsBlockRequested(pindex->GetBlockHash())) {
1613 [ # # ]: 0 : if (waitingfor == -1) {
1614 : : // This is the first already-in-flight block.
1615 : 0 : waitingfor = mapBlocksInFlight.lower_bound(pindex->GetBlockHash())->second.first;
1616 : : }
1617 : 0 : continue;
1618 : : }
1619 : :
1620 : : // The block is not already downloaded, and not yet in flight.
1621 [ # # ]: 0 : 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 [ # # # # ]: 0 : 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 [ # # ]: 0 : vBlocks.push_back(pindex);
1636 [ # # # # ]: 0 : if (vBlocks.size() == count) {
1637 : : return;
1638 : : }
1639 : : }
1640 : : }
1641 : 0 : }
1642 : :
1643 : : } // namespace
1644 : :
1645 : 3 : void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer)
1646 : : {
1647 : 3 : uint64_t my_services;
1648 : 3 : int64_t my_time;
1649 : 3 : uint64_t your_services;
1650 : 3 : CService your_addr;
1651 [ + + ]: 3 : std::string my_user_agent;
1652 : 3 : int my_height;
1653 : 3 : bool my_tx_relay;
1654 [ + + ]: 3 : if (pnode.IsPrivateBroadcastConn()) {
1655 : 1 : my_services = NODE_NONE;
1656 : 1 : my_time = 0;
1657 : 1 : your_services = NODE_NONE;
1658 [ + - ]: 2 : your_addr = CService{};
1659 [ + - ]: 1 : 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 : 1 : my_height = 0;
1661 : 1 : my_tx_relay = false;
1662 : : } else {
1663 : 2 : const CAddress& addr{pnode.addr};
1664 : 2 : my_services = peer.m_our_services;
1665 : 2 : my_time = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
1666 : 2 : your_services = addr.nServices;
1667 [ + - + - : 4 : your_addr = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? CService{addr} : CService{};
+ - + - +
- + - -
- ]
1668 [ + - ]: 2 : my_user_agent = strSubVersion;
1669 : 2 : my_height = m_best_height;
1670 : 2 : my_tx_relay = !RejectIncomingTxs(pnode);
1671 : : }
1672 : :
1673 [ + - + - ]: 6 : MakeAndPushMessage(
1674 : : pnode,
1675 : 3 : NetMsgType::VERSION,
1676 [ + - ]: 3 : 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 : 3 : your_services, CNetAddr::V1(your_addr),
1681 : : // same, for a dummy address
1682 [ + + ]: 3 : my_services, CNetAddr::V1(CService{}),
1683 [ + - ]: 3 : pnode.GetLocalNonce(),
1684 : : my_user_agent,
1685 : : my_height,
1686 : : my_tx_relay);
1687 : :
1688 [ + - + - : 6 : 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 : 3 : }
1694 : :
1695 : 1 : void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
1696 : : {
1697 : 1 : LOCK(cs_main);
1698 : 1 : CNodeState *state = State(node);
1699 [ + - ]: 1 : if (state) state->m_last_block_announcement = time_in_seconds;
1700 : 1 : }
1701 : :
1702 : 27 : void PeerManagerImpl::InitializeNode(const CNode& node, ServiceFlags our_services)
1703 : : {
1704 : 27 : NodeId nodeid = node.GetId();
1705 : 27 : {
1706 : 27 : LOCK(cs_main); // For m_node_states
1707 [ + - ]: 27 : m_node_states.try_emplace(m_node_states.end(), nodeid);
1708 : 0 : }
1709 [ + - ]: 81 : WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty(nodeid));
1710 : :
1711 [ - + ]: 27 : if (NetPermissions::HasFlag(node.m_permission_flags, NetPermissionFlags::BloomFilter)) {
1712 : 0 : our_services = static_cast<ServiceFlags>(our_services | NODE_BLOOM);
1713 : : }
1714 : :
1715 : 27 : PeerRef peer = std::make_shared<Peer>(nodeid, our_services, node.IsInboundConn());
1716 : 27 : {
1717 [ + - ]: 27 : LOCK(m_peer_mutex);
1718 [ + - + - ]: 27 : m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
1719 [ + - ]: 27 : }
1720 : 27 : }
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 : 26 : void PeerManagerImpl::FinalizeNode(const CNode& node)
1775 : : {
1776 : 26 : NodeId nodeid = node.GetId();
1777 : 26 : {
1778 : 26 : LOCK(cs_main);
1779 : 26 : {
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 [ + - ]: 26 : PeerRef peer = RemovePeer(nodeid);
1786 [ - + ]: 26 : assert(peer != nullptr);
1787 [ - + ]: 26 : m_wtxid_relay_peers -= peer->m_wtxid_relay;
1788 [ - + ]: 26 : assert(m_wtxid_relay_peers >= 0);
1789 : 26 : }
1790 : 26 : CNodeState *state = State(nodeid);
1791 [ - + ]: 26 : assert(state != nullptr);
1792 : :
1793 [ + + ]: 26 : if (state->fSyncStarted)
1794 : 1 : nSyncStarted--;
1795 : :
1796 [ - + ]: 26 : for (const QueuedBlock& entry : state->vBlocksInFlight) {
1797 : 0 : auto range = mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash());
1798 [ # # ]: 0 : while (range.first != range.second) {
1799 [ # # ]: 0 : auto [node_id, list_it] = range.first->second;
1800 [ # # ]: 0 : if (node_id != nodeid) {
1801 : 0 : range.first++;
1802 : : } else {
1803 : 0 : range.first = mapBlocksInFlight.erase(range.first);
1804 : : }
1805 : : }
1806 : : }
1807 : 26 : {
1808 [ + - ]: 26 : LOCK(m_tx_download_mutex);
1809 [ + - ]: 26 : m_txdownloadman.DisconnectedPeer(nodeid);
1810 : 0 : }
1811 [ - + - - ]: 26 : if (m_txreconciliation) m_txreconciliation->ForgetPeer(nodeid);
1812 : 26 : m_num_preferred_download_peers -= state->fPreferredDownload;
1813 [ - + ]: 26 : m_peers_downloading_from -= (!state->vBlocksInFlight.empty());
1814 [ - + ]: 26 : assert(m_peers_downloading_from >= 0);
1815 : 26 : m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
1816 [ - + ]: 26 : assert(m_outbound_peers_with_protect_from_disconnect >= 0);
1817 : :
1818 : 26 : m_node_states.erase(nodeid);
1819 : :
1820 [ + + ]: 26 : if (m_node_states.empty()) {
1821 : : // Do a consistency check after the last peer is removed.
1822 [ - + ]: 7 : assert(mapBlocksInFlight.empty());
1823 [ - + ]: 7 : assert(m_num_preferred_download_peers == 0);
1824 [ - + ]: 7 : assert(m_peers_downloading_from == 0);
1825 [ - + ]: 7 : assert(m_outbound_peers_with_protect_from_disconnect == 0);
1826 [ - + ]: 7 : assert(m_wtxid_relay_peers == 0);
1827 [ + - + - ]: 21 : WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty());
1828 : : }
1829 : 26 : } // cs_main
1830 [ + + ]: 26 : if (node.fSuccessfullyConnected &&
1831 [ + + + + : 26 : !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 : 16 : m_addrman.Connected(node.addr);
1837 : : }
1838 : 26 : {
1839 : 26 : LOCK(m_headers_presync_mutex);
1840 [ + - ]: 26 : m_headers_presync_stats.erase(nodeid);
1841 : 26 : }
1842 [ + + + - ]: 27 : if (node.IsPrivateBroadcastConn() &&
1843 [ + + - + ]: 27 : !m_tx_for_private_broadcast.DidNodeConfirmReception(nodeid) &&
1844 : 1 : m_tx_for_private_broadcast.HavePendingTransactions()) {
1845 : :
1846 : 0 : m_connman.m_private_broadcast.NumToOpenAdd(1);
1847 : : }
1848 [ + - ]: 26 : LogDebug(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
1849 : 26 : }
1850 : :
1851 : 5 : bool PeerManagerImpl::HasAllDesirableServiceFlags(ServiceFlags services) const
1852 : : {
1853 : : // Shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services)
1854 : 5 : return !(GetDesirableServiceFlags(services) & (~services));
1855 : : }
1856 : :
1857 : 13 : ServiceFlags PeerManagerImpl::GetDesirableServiceFlags(ServiceFlags services) const
1858 : : {
1859 [ + + ]: 13 : if (services & NODE_NETWORK_LIMITED) {
1860 : : // Limited peers are desirable when we are close to the tip.
1861 [ + + ]: 7 : if (ApproximateBestBlockDepth() < NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS) {
1862 : 3 : return ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS);
1863 : : }
1864 : : }
1865 : : return ServiceFlags(NODE_NETWORK | NODE_WITNESS);
1866 : : }
1867 : :
1868 : 26 : PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const
1869 : : {
1870 : 26 : LOCK(m_peer_mutex);
1871 : 26 : auto it = m_peer_map.find(id);
1872 [ + - + - : 52 : return it != m_peer_map.end() ? it->second : nullptr;
+ - ]
1873 : 26 : }
1874 : :
1875 : 26 : PeerRef PeerManagerImpl::RemovePeer(NodeId id)
1876 : : {
1877 : 26 : PeerRef ret;
1878 [ + - ]: 26 : LOCK(m_peer_mutex);
1879 : 26 : auto it = m_peer_map.find(id);
1880 [ + - ]: 26 : if (it != m_peer_map.end()) {
1881 : 26 : ret = std::move(it->second);
1882 : 26 : m_peer_map.erase(it);
1883 : : }
1884 [ + - ]: 26 : return ret;
1885 : 26 : }
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 : 1 : bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const
1899 : : {
1900 : 1 : {
1901 : 1 : LOCK(cs_main);
1902 : 1 : const CNodeState* state = State(nodeid);
1903 [ - + ]: 1 : if (state == nullptr)
1904 [ # # ]: 0 : return false;
1905 [ - + ]: 1 : stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
1906 [ - + ]: 1 : stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
1907 [ - + ]: 1 : 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 : 1 : PeerRef peer = GetPeerRef(nodeid);
1914 [ + - ]: 1 : if (peer == nullptr) return false;
1915 [ - + ]: 1 : 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 : 1 : NodeClock::duration ping_wait{0us};
1923 [ - + - - ]: 1 : 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 [ + - + - ]: 1 : if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
1928 [ + - + - ]: 2 : stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs);
1929 [ + - ]: 1 : stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load();
1930 [ + - ]: 1 : LOCK(tx_relay->m_tx_inventory_mutex);
1931 : 1 : stats.m_last_inv_seq = tx_relay->m_last_inv_sequence;
1932 [ - + + - ]: 1 : stats.m_inv_to_send = tx_relay->m_tx_inventory_to_send.size();
1933 : 1 : } else {
1934 : 0 : stats.m_relay_txs = false;
1935 : 0 : stats.m_fee_filter_received = 0;
1936 : 0 : stats.m_inv_to_send = 0;
1937 : : }
1938 : :
1939 : 1 : stats.m_ping_wait = ping_wait;
1940 [ + - ]: 1 : stats.m_addr_processed = peer->m_addr_processed.load();
1941 : 1 : stats.m_addr_rate_limited = peer->m_addr_rate_limited.load();
1942 [ + - ]: 1 : stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load();
1943 : 1 : {
1944 [ + - ]: 1 : LOCK(peer->m_headers_sync_mutex);
1945 [ - + ]: 1 : if (peer->m_headers_sync) {
1946 : 0 : stats.presync_height = peer->m_headers_sync->GetPresyncHeight();
1947 : : }
1948 : 1 : }
1949 : 1 : stats.time_offset = peer->m_time_offset;
1950 : :
1951 : 1 : return true;
1952 : 1 : }
1953 : :
1954 : 0 : std::vector<node::TxOrphanage::OrphanInfo> PeerManagerImpl::GetOrphanTransactions()
1955 : : {
1956 : 0 : LOCK(m_tx_download_mutex);
1957 [ # # ]: 0 : return m_txdownloadman.GetOrphanTransactions();
1958 : 0 : }
1959 : :
1960 : 3 : PeerManagerInfo PeerManagerImpl::GetInfo() const
1961 : : {
1962 : 3 : LOCK(m_inv_to_send_mutex);
1963 : 3 : return PeerManagerInfo{
1964 : 3 : .median_outbound_time_offset = m_outbound_time_offsets.Median(),
1965 : 3 : .ignores_incoming_txs = m_opts.ignore_incoming_txs,
1966 : 3 : .private_broadcast = m_opts.private_broadcast,
1967 : 3 : .tx_send_rate = m_opts.tx_send_rate,
1968 : 6 : .inbound_bucket = m_inbound_inv_bucket.info(),
1969 [ - + + - ]: 3 : .outbound_bucket = m_outbound_inv_bucket.info(),
1970 [ + - - + ]: 3 : };
1971 : 3 : }
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 : 4 : void PeerManagerImpl::Misbehaving(Peer& peer, const std::string& message)
2012 : : {
2013 : 4 : LOCK(peer.m_misbehavior_mutex);
2014 : :
2015 [ + - + - : 4 : const std::string message_prefixed = message.empty() ? "" : (": " + message);
- - ]
2016 : 4 : peer.m_should_discourage = true;
2017 [ + - + - : 4 : 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 : 4 : );
2022 [ + - ]: 8 : }
2023 : :
2024 : 0 : void PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
2025 : : bool via_compact_block, const std::string& message)
2026 : : {
2027 : 0 : PeerRef peer{GetPeerRef(nodeid)};
2028 [ # # # # : 0 : 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 : 0 : case BlockValidationResult::BLOCK_CONSENSUS:
2037 : 0 : case BlockValidationResult::BLOCK_MUTATED:
2038 [ # # ]: 0 : if (!via_compact_block) {
2039 [ # # # # ]: 0 : if (peer) Misbehaving(*peer, message);
2040 : 0 : 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 : 0 : case BlockValidationResult::BLOCK_INVALID_HEADER:
2054 : 0 : case BlockValidationResult::BLOCK_INVALID_PREV:
2055 [ # # # # ]: 0 : if (peer) Misbehaving(*peer, message);
2056 : : return;
2057 : : // Conflicting (but not necessarily invalid) data or different policy:
2058 : 0 : case BlockValidationResult::BLOCK_MISSING_PREV:
2059 [ # # # # ]: 0 : if (peer) Misbehaving(*peer, message);
2060 : : return;
2061 : : case BlockValidationResult::BLOCK_TIME_FUTURE:
2062 : : break;
2063 : : }
2064 [ # # ]: 0 : if (message != "") {
2065 [ # # # # : 0 : LogDebug(BCLog::NET, "peer=%d: %s\n", nodeid, message);
# # # # ]
2066 : : }
2067 : 0 : }
2068 : :
2069 : 0 : bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex& block_index)
2070 : : {
2071 : 0 : AssertLockHeld(cs_main);
2072 [ # # ]: 0 : 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 : 167 : 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 [ - + ]: 167 : return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman, pool, warnings, opts);
2123 : : }
2124 : :
2125 : 167 : PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman,
2126 : : BanMan* banman, ChainstateManager& chainman,
2127 : 167 : CTxMemPool& pool, node::Warnings& warnings, Options opts)
2128 : 167 : : m_rng{opts.deterministic_rng},
2129 [ + - ]: 167 : m_fee_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}, m_rng},
2130 : 167 : m_chainparams(chainman.GetParams()),
2131 : 167 : m_connman(connman),
2132 : 167 : m_addrman(addrman),
2133 : 167 : m_banman(banman),
2134 : 167 : m_chainman(chainman),
2135 : 167 : m_mempool(pool),
2136 [ + - ]: 167 : m_txdownloadman(node::TxDownloadOptions{pool, m_rng, opts.deterministic_rng}),
2137 [ + - ]: 167 : m_warnings{warnings},
2138 : 167 : m_opts{opts},
2139 : 167 : m_inbound_inv_bucket(/*rate=*/m_opts.tx_send_rate, /*mult=*/1.0),
2140 [ + - + - : 334 : 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 [ - + ]: 167 : if (opts.reconcile_txs) {
2145 [ # # ]: 0 : m_txreconciliation = std::make_unique<TxReconciliationTracker>(TXRECONCILIATION_VERSION);
2146 : : }
2147 [ - - - - ]: 167 : }
2148 : :
2149 : 1 : 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 : 1 : static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
2156 [ + - ]: 1 : 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 : 1 : const auto delta = 10min + FastRandomContext().randrange<std::chrono::milliseconds>(5min);
2160 [ + - ]: 1 : scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
2161 : :
2162 [ - + ]: 1 : if (m_opts.private_broadcast) {
2163 [ # # ]: 0 : scheduler.scheduleFromNow([&] { ReattemptPrivateBroadcast(scheduler); }, 0min);
2164 : : }
2165 : 1 : }
2166 : :
2167 : 3 : 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 : 3 : AssertLockNotHeld(m_mempool.cs);
2172 : 3 : AssertLockNotHeld(m_tx_download_mutex);
2173 : :
2174 [ + + ]: 3 : if (!is_ibd) {
2175 : 1 : 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 [ + - ]: 1 : m_txdownloadman.ActiveTipChange();
2180 : 1 : }
2181 : 3 : }
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 : 2 : 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 : 2 : 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 [ - + ]: 2 : auto stalling_timeout = m_block_stalling_timeout.load();
2200 [ - + ]: 2 : Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT);
2201 [ - + ]: 2 : 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 [ + - + + ]: 2 : if (!role.historical && !m_chainman.IsInitialBlockDownload()) {
2212 : 1 : LOCK(m_tx_download_mutex);
2213 [ + - ]: 1 : m_txdownloadman.BlockConnected(pblock);
2214 : 1 : }
2215 : 2 : }
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 : 3 : void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
2283 : : {
2284 : 3 : SetBestBlock(pindexNew->nHeight, std::chrono::seconds{pindexNew->GetBlockTime()});
2285 : :
2286 : : // Don't relay inventory during initial block download.
2287 [ + + ]: 3 : if (fInitialDownload) return;
2288 : :
2289 : : // Find the hashes of all blocks that weren't previously in the best chain.
2290 : 1 : std::vector<uint256> vHashes;
2291 : 1 : const CBlockIndex *pindexToAnnounce = pindexNew;
2292 [ + + ]: 2 : while (pindexToAnnounce != pindexFork) {
2293 [ + - ]: 1 : vHashes.push_back(pindexToAnnounce->GetBlockHash());
2294 : 1 : pindexToAnnounce = pindexToAnnounce->pprev;
2295 [ - + + - ]: 1 : 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 : 1 : {
2303 [ + - ]: 1 : LOCK(m_peer_mutex);
2304 [ - + ]: 1 : 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 [ + - ]: 1 : m_connman.WakeMessageHandler();
2314 : 1 : }
2315 : :
2316 : : /**
2317 : : * Handle invalid block rejection and consequent peer discouragement, maintain which
2318 : : * peers announce compact blocks.
2319 : : */
2320 : 3 : void PeerManagerImpl::BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state)
2321 : : {
2322 : 3 : LOCK(cs_main);
2323 : :
2324 [ + - ]: 3 : const uint256 hash(block->GetHash());
2325 : 3 : 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 [ - + - - ]: 3 : if (state.IsInvalid() &&
2330 [ - + - - : 3 : it != mapBlockSource.end() &&
- - ]
2331 : 0 : State(it->second.first)) {
2332 [ # # # # ]: 0 : 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 [ - + ]: 3 : else if (state.IsValid() &&
2341 [ + - - - ]: 3 : !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 [ - + ]: 3 : if (it != mapBlockSource.end())
2348 : 0 : mapBlockSource.erase(it);
2349 : 3 : }
2350 : :
2351 : : //////////////////////////////////////////////////////////////////////////////
2352 : : //
2353 : : // Messages
2354 : : //
2355 : :
2356 : 0 : bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash)
2357 : : {
2358 : 0 : return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
2359 : : }
2360 : :
2361 : 0 : void PeerManagerImpl::SendPings()
2362 : : {
2363 : 0 : LOCK(m_peer_mutex);
2364 [ # # ]: 0 : for(auto& it : m_peer_map) it.second->m_ping_queued = true;
2365 : 0 : }
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 : 6 : 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 [ + - + + ]: 6 : if (!backlog_bumped && now <= m_next_inv_bucket_check.load()) return;
2404 : 5 : m_next_inv_bucket_check = now + INVENTORY_BUCKET_CHECK_DELAY;
2405 : :
2406 : 5 : LOCK(m_inv_to_send_mutex);
2407 : 5 : m_inbound_inv_bucket.increment(now);
2408 : 5 : m_outbound_inv_bucket.increment(now);
2409 : :
2410 : : // Regular heartbeat logging when there's a backlog
2411 [ + - ]: 5 : if (!m_next_inv_bucket_heartbeat.has_value()) {
2412 [ - + + - : 5 : 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 [ - + - - ]: 5 : 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 : 5 : bool in_avail = m_inbound_inv_bucket.avail();
2433 : 5 : bool out_avail = m_outbound_inv_bucket.avail();
2434 [ + - + - ]: 5 : 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 [ - - ]: 5 : }
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 : 0 : 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 [ # # # # ]: 0 : 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 : 0 : const uint64_t hash_addr{CServiceHash(0, 0)(addr)};
2523 : 0 : const auto current_time{GetTime<std::chrono::seconds>()};
2524 : : // Adding address hash makes exact rotation time different per address, while preserving periodicity.
2525 : 0 : const uint64_t time_addr{(static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) / count_seconds(ROTATE_ADDR_RELAY_DEST_INTERVAL)};
2526 : 0 : const CSipHasher hasher{m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY)
2527 : 0 : .Write(hash_addr)
2528 : 0 : .Write(time_addr)};
2529 : :
2530 : : // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers.
2531 [ # # # # ]: 0 : unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
2532 : :
2533 : 0 : std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}};
2534 [ # # ]: 0 : assert(nRelayNodes <= best.size());
2535 : :
2536 : 0 : LOCK(m_peer_mutex);
2537 : :
2538 [ # # # # ]: 0 : for (auto& [id, peer] : m_peer_map) {
2539 [ # # # # : 0 : if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) {
# # # # ]
2540 [ # # # # ]: 0 : uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
2541 [ # # ]: 0 : for (unsigned int i = 0; i < nRelayNodes; i++) {
2542 [ # # ]: 0 : if (hashKey > best[i].first) {
2543 : 0 : std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
2544 : 0 : best[i] = std::make_pair(hashKey, peer.get());
2545 : 0 : break;
2546 : : }
2547 : : }
2548 : : }
2549 : : };
2550 : :
2551 [ # # # # ]: 0 : for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
2552 [ # # ]: 0 : PushAddress(*best[i].second, addr);
2553 : : }
2554 : 0 : }
2555 : :
2556 : 0 : void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
2557 : : {
2558 : : // First perform the stateless checks:
2559 : : // A filtered-block can only ever be requested if we offer NODE_BLOOM
2560 [ # # # # ]: 0 : if (inv.IsMsgFilteredBlk() && !(peer.m_our_services & NODE_BLOOM)) {
2561 [ # # # # ]: 0 : LogDebug(BCLog::NET, "filtered block request received when NODE_BLOOM service disabled, %s", pfrom.DisconnectMsg());
2562 : 0 : pfrom.fDisconnect = true;
2563 : 0 : return;
2564 : : }
2565 : :
2566 : 0 : std::shared_ptr<const CBlock> a_recent_block;
2567 : 0 : std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
2568 : 0 : {
2569 [ # # ]: 0 : LOCK(m_most_recent_block_mutex);
2570 : 0 : a_recent_block = m_most_recent_block;
2571 [ # # ]: 0 : a_recent_compact_block = m_most_recent_compact_block;
2572 : 0 : }
2573 : :
2574 : 0 : bool need_activate_chain = false;
2575 : 0 : {
2576 [ # # ]: 0 : LOCK(cs_main);
2577 [ # # ]: 0 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
2578 [ # # ]: 0 : if (pindex) {
2579 [ # # # # : 0 : if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
# # ]
2580 [ # # # # ]: 0 : pindex->IsValid(BLOCK_VALID_TREE)) {
2581 : : // If we have the block and all of its parents, but have not yet validated it,
2582 : : // we might be in the middle of connecting it (ie in the unlock of cs_main
2583 : : // before ActivateBestChain but after AcceptBlock).
2584 : : // In this case, we need to run ActivateBestChain prior to checking the relay
2585 : : // conditions below.
2586 : : need_activate_chain = true;
2587 : : }
2588 : : }
2589 : 0 : } // release cs_main before calling ActivateBestChain
2590 [ # # ]: 0 : if (need_activate_chain) {
2591 [ # # ]: 0 : BlockValidationState state;
2592 [ # # # # : 0 : if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
# # # # #
# ]
2593 [ # # # # : 0 : LogDebug(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
# # # # ]
2594 : : }
2595 : 0 : }
2596 : :
2597 : 0 : const CBlockIndex* pindex{nullptr};
2598 : 0 : const CBlockIndex* tip{nullptr};
2599 : 0 : bool can_direct_fetch{false};
2600 : 0 : FlatFilePos block_pos{};
2601 : 0 : {
2602 [ # # ]: 0 : LOCK(cs_main);
2603 [ # # ]: 0 : pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
2604 [ # # ]: 0 : if (!pindex) {
2605 : : return;
2606 : : }
2607 [ # # # # ]: 0 : if (!BlockRequestAllowed(*pindex)) {
2608 [ # # # # : 0 : LogDebug(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId());
# # ]
2609 : 0 : return;
2610 : : }
2611 : : // disconnect node in case we have reached the outbound limit for serving historical blocks
2612 [ # # ]: 0 : if (m_connman.OutboundTargetReached(true) &&
2613 [ # # # # : 0 : (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&
# # # # ]
2614 [ # # ]: 0 : !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target
2615 : : ) {
2616 [ # # # # : 0 : LogDebug(BCLog::NET, "historical block serving limit reached, %s", pfrom.DisconnectMsg());
# # # # ]
2617 : 0 : pfrom.fDisconnect = true;
2618 : 0 : return;
2619 : : }
2620 [ # # # # ]: 0 : tip = m_chainman.ActiveChain().Tip();
2621 : : // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
2622 [ # # ]: 0 : if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && (
2623 [ # # # # : 0 : (((peer.m_our_services & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) && (tip->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
# # ]
2624 : : )) {
2625 [ # # # # : 0 : LogDebug(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, %s", pfrom.DisconnectMsg());
# # # # ]
2626 : : //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
2627 : 0 : pfrom.fDisconnect = true;
2628 : 0 : return;
2629 : : }
2630 : : // Pruned nodes may have deleted the block, so check whether
2631 : : // it's available before trying to send.
2632 [ # # ]: 0 : if (!(pindex->nStatus & BLOCK_HAVE_DATA)) {
2633 : : return;
2634 : : }
2635 [ # # ]: 0 : can_direct_fetch = CanDirectFetch();
2636 [ # # ]: 0 : block_pos = pindex->GetBlockPos();
2637 : 0 : }
2638 : :
2639 : 0 : std::shared_ptr<const CBlock> pblock;
2640 [ # # # # : 0 : if (a_recent_block && a_recent_block->GetHash() == inv.hash) {
# # ]
2641 : 0 : pblock = a_recent_block;
2642 [ # # ]: 0 : } else if (inv.IsMsgWitnessBlk()) {
2643 : : // Fast-path: in this case it is possible to serve the block directly from disk,
2644 : : // as the network format matches the format on disk
2645 [ # # # # ]: 0 : if (const auto block_data{m_chainman.m_blockman.ReadRawBlock(block_pos)}) {
2646 [ # # # # : 0 : MakeAndPushMessage(pfrom, NetMsgType::BLOCK, std::span{*block_data});
# # ]
2647 : : } else {
2648 [ # # # # : 0 : if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) {
# # # # ]
2649 [ # # # # : 0 : LogDebug(BCLog::NET, "Block was pruned before it could be read, %s", pfrom.DisconnectMsg());
# # # # ]
2650 : : } else {
2651 [ # # # # ]: 0 : LogError("Cannot load block from disk, %s", pfrom.DisconnectMsg());
2652 : : }
2653 : 0 : pfrom.fDisconnect = true;
2654 : 0 : return;
2655 : 0 : }
2656 : : // Don't set pblock as we've sent the block
2657 : : } else {
2658 : : // Send block from disk
2659 [ # # ]: 0 : std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
2660 [ # # # # ]: 0 : if (!m_chainman.m_blockman.ReadBlock(*pblockRead, block_pos, inv.hash)) {
2661 [ # # # # : 0 : if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) {
# # # # ]
2662 [ # # # # : 0 : LogDebug(BCLog::NET, "Block was pruned before it could be read, %s", pfrom.DisconnectMsg());
# # # # ]
2663 : : } else {
2664 [ # # # # ]: 0 : LogError("Cannot load block from disk, %s", pfrom.DisconnectMsg());
2665 : : }
2666 [ # # ]: 0 : pfrom.fDisconnect = true;
2667 [ # # ]: 0 : return;
2668 : : }
2669 [ # # ]: 0 : pblock = pblockRead;
2670 : 0 : }
2671 [ # # ]: 0 : if (pblock) {
2672 [ # # ]: 0 : if (inv.IsMsgBlk()) {
2673 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_NO_WITNESS(*pblock));
2674 [ # # ]: 0 : } else if (inv.IsMsgWitnessBlk()) {
2675 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock));
2676 [ # # ]: 0 : } else if (inv.IsMsgFilteredBlk()) {
2677 : 0 : bool sendMerkleBlock = false;
2678 [ # # ]: 0 : CMerkleBlock merkleBlock;
2679 [ # # # # ]: 0 : if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
2680 [ # # ]: 0 : LOCK(tx_relay->m_bloom_filter_mutex);
2681 [ # # ]: 0 : if (tx_relay->m_bloom_filter) {
2682 : 0 : sendMerkleBlock = true;
2683 [ # # ]: 0 : merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
2684 : : }
2685 : 0 : }
2686 [ # # ]: 0 : if (sendMerkleBlock) {
2687 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::MERKLEBLOCK, merkleBlock);
2688 : : // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
2689 : : // This avoids hurting performance by pointlessly requiring a round-trip
2690 : : // Note that there is currently no way for a node to request any single transactions we didn't send here -
2691 : : // they must either disconnect and retry or request the full block.
2692 : : // Thus, the protocol spec specified allows for us to provide duplicate txn here,
2693 : : // however we MUST always provide at least what the remote peer needs
2694 [ # # # # ]: 0 : for (const auto& [tx_idx, _] : merkleBlock.vMatchedTxn)
2695 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::TX, TX_NO_WITNESS(*pblock->vtx[tx_idx]));
2696 : : }
2697 : : // else
2698 : : // no response
2699 [ # # ]: 0 : } else if (inv.IsMsgCmpctBlk()) {
2700 : : // If a peer is asking for old blocks, we're almost guaranteed
2701 : : // they won't have a useful mempool to match against a compact block,
2702 : : // and we don't feel like constructing the object for them, so
2703 : : // instead we respond with the full, non-compact block.
2704 [ # # # # ]: 0 : if (can_direct_fetch && pindex->nHeight >= tip->nHeight - MAX_CMPCTBLOCK_DEPTH) {
2705 [ # # # # : 0 : if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == inv.hash) {
# # ]
2706 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, *a_recent_compact_block);
2707 : : } else {
2708 [ # # ]: 0 : CBlockHeaderAndShortTxIDs cmpctblock{*pblock, m_rng.rand64()};
2709 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, cmpctblock);
2710 : 0 : }
2711 : : } else {
2712 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock));
2713 : : }
2714 : : }
2715 : : }
2716 : :
2717 : 0 : {
2718 [ # # ]: 0 : LOCK(peer.m_block_inv_mutex);
2719 : : // Trigger the peer node to send a getblocks request for the next batch of inventory
2720 [ # # ]: 0 : if (inv.hash == peer.m_continuation_block) {
2721 : : // Send immediately. This must send even if redundant,
2722 : : // and we want it right after the last block so they don't
2723 : : // wait for other stuff first.
2724 : 0 : std::vector<CInv> vInv;
2725 [ # # ]: 0 : vInv.emplace_back(MSG_BLOCK, tip->GetBlockHash());
2726 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::INV, vInv);
2727 : 0 : peer.m_continuation_block.SetNull();
2728 : 0 : }
2729 [ # # ]: 0 : }
2730 [ # # # # : 0 : }
# # ]
2731 : :
2732 : 0 : CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid)
2733 : : {
2734 : : // If a tx was in the mempool prior to the last INV for this peer, permit the request.
2735 : 0 : auto txinfo{std::visit(
2736 : 0 : [&](const auto& id) {
2737 [ # # ]: 0 : return m_mempool.info_for_relay(id, WITH_LOCK(tx_relay.m_tx_inventory_mutex, return tx_relay.m_last_inv_sequence));
2738 : : },
2739 : 0 : gtxid)};
2740 [ # # ]: 0 : if (txinfo.tx) {
2741 : 0 : return std::move(txinfo.tx);
2742 : : }
2743 : :
2744 : : // Or it might be from the most recent block
2745 : 0 : {
2746 [ # # ]: 0 : LOCK(m_most_recent_block_mutex);
2747 [ # # ]: 0 : if (m_most_recent_block_txs != nullptr) {
2748 : 0 : auto it = m_most_recent_block_txs->find(gtxid);
2749 [ # # # # : 0 : if (it != m_most_recent_block_txs->end()) return it->second;
# # ]
2750 : : }
2751 : 0 : }
2752 : :
2753 : 0 : return {};
2754 : 0 : }
2755 : :
2756 : 0 : void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
2757 : : {
2758 : 0 : AssertLockNotHeld(cs_main);
2759 : :
2760 : 0 : auto tx_relay = peer.GetTxRelay();
2761 : :
2762 : 0 : std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
2763 : 0 : std::vector<CInv> vNotFound;
2764 : :
2765 : : // Process as many TX items from the front of the getdata queue as
2766 : : // possible, since they're common and it's efficient to batch process
2767 : : // them.
2768 [ # # # # ]: 0 : while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) {
2769 [ # # ]: 0 : if (interruptMsgProc) return;
2770 : : // The send buffer provides backpressure. If there's no space in
2771 : : // the buffer, pause processing until the next call.
2772 [ # # ]: 0 : if (pfrom.fPauseSend) break;
2773 : :
2774 : 0 : const CInv &inv = *it++;
2775 : :
2776 [ # # ]: 0 : if (tx_relay == nullptr) {
2777 : : // Ignore GETDATA requests for transactions from block-relay-only
2778 : : // peers and peers that asked us not to announce transactions.
2779 : 0 : continue;
2780 : : }
2781 : :
2782 [ # # # # : 0 : if (auto tx{FindTxForGetData(*tx_relay, ToGenTxid(inv))}) {
# # ]
2783 : : // WTX and WITNESS_TX imply we serialize with witness
2784 [ # # ]: 0 : const auto maybe_with_witness = (inv.IsMsgTx() ? TX_NO_WITNESS : TX_WITH_WITNESS);
2785 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::TX, maybe_with_witness(*tx));
2786 [ # # ]: 0 : m_mempool.RemoveUnbroadcastTx(tx->GetHash());
2787 : : } else {
2788 [ # # ]: 0 : vNotFound.push_back(inv);
2789 : 0 : }
2790 : : }
2791 : :
2792 : : // Only process one BLOCK item per call, since they're uncommon and can be
2793 : : // expensive to process.
2794 [ # # # # ]: 0 : if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
2795 : 0 : const CInv &inv = *it++;
2796 [ # # ]: 0 : if (inv.IsGenBlkMsg()) {
2797 [ # # ]: 0 : ProcessGetBlockData(pfrom, peer, inv);
2798 : : }
2799 : : // else: If the first item on the queue is an unknown type, we erase it
2800 : : // and continue processing the queue on the next call.
2801 : : // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could
2802 : : // result in never making progress and this thread using 100% allocated CPU. See
2803 : : // https://bitcoincore.org/en/2024/07/03/disclose-getdata-cpu.
2804 : : }
2805 : :
2806 : 0 : peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
2807 : :
2808 [ # # ]: 0 : if (!vNotFound.empty()) {
2809 : : // Let the peer know that we didn't find what it asked for, so it doesn't
2810 : : // have to wait around forever.
2811 : : // SPV clients care about this message: it's needed when they are
2812 : : // recursively walking the dependencies of relevant unconfirmed
2813 : : // transactions. SPV clients want to do that because they want to know
2814 : : // about (and store and rebroadcast and risk analyze) the dependencies
2815 : : // of transactions relevant to them, without having to download the
2816 : : // entire memory pool.
2817 : : // Also, other nodes can use these messages to automatically request a
2818 : : // transaction from some other peer that announced it, and stop
2819 : : // waiting for us to respond.
2820 : : // In normal operation, we often send NOTFOUND messages for parents of
2821 : : // transactions that we relay; if a peer is missing a parent, they may
2822 : : // assume we have them and request the parents from us.
2823 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound);
2824 : : }
2825 : 0 : }
2826 : :
2827 : 0 : uint32_t PeerManagerImpl::GetFetchFlags(const Peer& peer) const
2828 : : {
2829 : 0 : uint32_t nFetchFlags = 0;
2830 [ # # ]: 0 : if (CanServeWitnesses(peer)) {
2831 : 0 : nFetchFlags |= MSG_WITNESS_FLAG;
2832 : : }
2833 : 0 : return nFetchFlags;
2834 : : }
2835 : :
2836 : 0 : void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req)
2837 : : {
2838 : 0 : BlockTransactions resp(req);
2839 [ # # # # ]: 0 : for (size_t i = 0; i < req.indexes.size(); i++) {
2840 [ # # # # ]: 0 : if (req.indexes[i] >= block.vtx.size()) {
2841 [ # # # # ]: 0 : Misbehaving(peer, "getblocktxn with out-of-bounds tx indices");
2842 : 0 : return;
2843 : : }
2844 : 0 : resp.txn[i] = block.vtx[req.indexes[i]];
2845 : : }
2846 : :
2847 [ # # # # ]: 0 : if (util::log::ShouldDebugLog(BCLog::CMPCTBLOCK)) {
2848 : 0 : uint32_t tx_requested_size{0};
2849 [ # # # # ]: 0 : for (const auto& tx : resp.txn) tx_requested_size += tx->ComputeTotalSize();
2850 [ # # # # : 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);
# # # # #
# # # #
# ]
2851 : : }
2852 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::BLOCKTXN, resp);
2853 : 0 : }
2854 : :
2855 : 0 : bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader>& headers, Peer& peer)
2856 : : {
2857 : : // Do these headers have proof-of-work matching what's claimed?
2858 [ # # # # ]: 0 : if (!HasValidProofOfWork(headers, m_chainparams.GetConsensus())) {
2859 [ # # ]: 0 : Misbehaving(peer, "header with invalid proof of work");
2860 : 0 : return false;
2861 : : }
2862 : :
2863 : : // Are these headers connected to each other?
2864 [ # # ]: 0 : if (!CheckHeadersAreContinuous(headers)) {
2865 [ # # ]: 0 : Misbehaving(peer, "non-continuous headers sequence");
2866 : 0 : return false;
2867 : : }
2868 : : return true;
2869 : : }
2870 : :
2871 : 0 : arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold()
2872 : : {
2873 : 0 : arith_uint256 near_chaintip_work = 0;
2874 : 0 : LOCK(cs_main);
2875 [ # # # # : 0 : if (m_chainman.ActiveChain().Tip() != nullptr) {
# # ]
2876 [ # # # # ]: 0 : const CBlockIndex *tip = m_chainman.ActiveChain().Tip();
2877 : : // Use a 144 block buffer, so that we'll accept headers that fork from
2878 : : // near our tip.
2879 [ # # # # : 0 : near_chaintip_work = tip->nChainWork - std::min<arith_uint256>(144*GetBlockProof(*tip), tip->nChainWork);
# # ]
2880 : : }
2881 [ # # # # : 0 : return std::max(near_chaintip_work, m_chainman.MinimumChainWork());
# # ]
2882 : 0 : }
2883 : :
2884 : : /**
2885 : : * Special handling for unconnecting headers that might be part of a block
2886 : : * announcement.
2887 : : *
2888 : : * We'll send a getheaders message in response to try to connect the chain.
2889 : : */
2890 : 0 : void PeerManagerImpl::HandleUnconnectingHeaders(CNode& pfrom, Peer& peer,
2891 : : const std::vector<CBlockHeader>& headers)
2892 : : {
2893 : : // Try to fill in the missing headers.
2894 [ # # ]: 0 : const CBlockIndex* best_header{WITH_LOCK(cs_main, return m_chainman.m_best_header)};
2895 [ # # # # ]: 0 : if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) {
2896 [ # # # # : 0 : LogDebug(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d)\n",
# # # # ]
2897 : : headers[0].GetHash().ToString(),
2898 : : headers[0].hashPrevBlock.ToString(),
2899 : : best_header->nHeight,
2900 : : pfrom.GetId());
2901 : : }
2902 : :
2903 : : // Set hashLastUnknownBlock for this peer, so that if we
2904 : : // eventually get the headers - even from a different peer -
2905 : : // we can use this peer to download.
2906 [ # # # # ]: 0 : WITH_LOCK(cs_main, UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash()));
2907 : 0 : }
2908 : :
2909 : 0 : bool PeerManagerImpl::CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const
2910 : : {
2911 : 0 : uint256 hashLastBlock;
2912 [ # # ]: 0 : for (const CBlockHeader& header : headers) {
2913 [ # # # # ]: 0 : if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2914 : : return false;
2915 : : }
2916 : 0 : hashLastBlock = header.GetHash();
2917 : : }
2918 : : return true;
2919 : : }
2920 : :
2921 : 0 : bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers)
2922 : : {
2923 [ # # ]: 0 : if (peer.m_headers_sync) {
2924 [ # # ]: 0 : auto result = peer.m_headers_sync->ProcessNextHeaders(headers, headers.size() == m_opts.max_headers_result);
2925 : : // If it is a valid continuation, we should treat the existing getheaders request as responded to.
2926 [ # # ]: 0 : if (result.success) peer.m_last_getheaders_timestamp = {};
2927 [ # # ]: 0 : if (result.request_more) {
2928 [ # # ]: 0 : auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
2929 : : // If we were instructed to ask for a locator, it should not be empty.
2930 [ # # ]: 0 : Assume(!locator.vHave.empty());
2931 : : // We can only be instructed to request more if processing was successful.
2932 : 0 : Assume(result.success);
2933 [ # # ]: 0 : if (!locator.vHave.empty()) {
2934 : : // It should be impossible for the getheaders request to fail,
2935 : : // because we just cleared the last getheaders timestamp.
2936 [ # # ]: 0 : bool sent_getheaders = MaybeSendGetHeaders(pfrom, locator, peer);
2937 [ # # ]: 0 : Assume(sent_getheaders);
2938 [ # # # # : 0 : LogDebug(BCLog::NET, "more getheaders (from %s) to peer=%d\n",
# # # # ]
2939 : : locator.vHave.front().ToString(), pfrom.GetId());
2940 : : }
2941 : 0 : }
2942 : :
2943 [ # # ]: 0 : if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) {
2944 [ # # ]: 0 : peer.m_headers_sync.reset(nullptr);
2945 : :
2946 : : // Delete this peer's entry in m_headers_presync_stats.
2947 : : // If this is m_headers_presync_bestpeer, it will be replaced later
2948 : : // by the next peer that triggers the else{} branch below.
2949 [ # # ]: 0 : LOCK(m_headers_presync_mutex);
2950 [ # # ]: 0 : m_headers_presync_stats.erase(pfrom.GetId());
2951 : 0 : } else {
2952 : : // Build statistics for this peer's sync.
2953 : 0 : HeadersPresyncStats stats;
2954 [ # # ]: 0 : stats.first = peer.m_headers_sync->GetPresyncWork();
2955 [ # # ]: 0 : if (peer.m_headers_sync->GetState() == HeadersSyncState::State::PRESYNC) {
2956 : 0 : stats.second = {peer.m_headers_sync->GetPresyncHeight(),
2957 : 0 : peer.m_headers_sync->GetPresyncTime()};
2958 : : }
2959 : :
2960 : : // Update statistics in stats.
2961 [ # # ]: 0 : LOCK(m_headers_presync_mutex);
2962 [ # # ]: 0 : m_headers_presync_stats[pfrom.GetId()] = stats;
2963 : 0 : auto best_it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
2964 : 0 : bool best_updated = false;
2965 [ # # ]: 0 : if (best_it == m_headers_presync_stats.end()) {
2966 : : // If the cached best peer is outdated, iterate over all remaining ones (including
2967 : : // newly updated one) to find the best one.
2968 : 0 : NodeId peer_best{-1};
2969 : 0 : const HeadersPresyncStats* stat_best{nullptr};
2970 [ # # # # ]: 0 : for (const auto& [peer, stat] : m_headers_presync_stats) {
2971 [ # # # # : 0 : if (!stat_best || stat > *stat_best) {
# # ]
2972 : 0 : peer_best = peer;
2973 : 0 : stat_best = &stat;
2974 : : }
2975 : : }
2976 : 0 : m_headers_presync_bestpeer = peer_best;
2977 [ # # ]: 0 : best_updated = (peer_best == pfrom.GetId());
2978 [ # # # # : 0 : } else if (best_it->first == pfrom.GetId() || stats > best_it->second) {
# # ]
2979 : : // pfrom was and remains the best peer, or pfrom just became best.
2980 : 0 : m_headers_presync_bestpeer = pfrom.GetId();
2981 : 0 : best_updated = true;
2982 : : }
2983 [ # # # # ]: 0 : if (best_updated && stats.second.has_value()) {
2984 : : // If the best peer updated, and it is in its first phase, signal.
2985 : 0 : m_headers_presync_should_signal = true;
2986 : : }
2987 : 0 : }
2988 : :
2989 [ # # ]: 0 : if (result.success) {
2990 : : // We only overwrite the headers passed in if processing was
2991 : : // successful.
2992 : 0 : headers.swap(result.pow_validated_headers);
2993 : : }
2994 : :
2995 : 0 : return result.success;
2996 : 0 : }
2997 : : // Either we didn't have a sync in progress, or something went wrong
2998 : : // processing these headers, or we are returning headers to the caller to
2999 : : // process.
3000 : : return false;
3001 : : }
3002 : :
3003 : 0 : bool PeerManagerImpl::TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex& chain_start_header, std::vector<CBlockHeader>& headers)
3004 : : {
3005 : : // Calculate the claimed total work on this chain.
3006 [ # # ]: 0 : arith_uint256 total_work = chain_start_header.nChainWork + CalculateClaimedHeadersWork(headers);
3007 : :
3008 : : // Our dynamic anti-DoS threshold (minimum work required on a headers chain
3009 : : // before we'll store it)
3010 : 0 : arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
3011 : :
3012 : : // Avoid DoS via low-difficulty-headers by only processing if the headers
3013 : : // are part of a chain with sufficient work.
3014 [ # # ]: 0 : if (total_work < minimum_chain_work) {
3015 : : // Only try to sync with this peer if their headers message was full;
3016 : : // otherwise they don't have more headers after this so no point in
3017 : : // trying to sync their too-little-work chain.
3018 [ # # # # ]: 0 : if (headers.size() == m_opts.max_headers_result) {
3019 : : // Note: we could advance to the last header in this set that is
3020 : : // known to us, rather than starting at the first header (which we
3021 : : // may already have); however this is unlikely to matter much since
3022 : : // ProcessHeadersMessage() already handles the case where all
3023 : : // headers in a received message are already known and are
3024 : : // ancestors of m_best_header or chainActive.Tip(), by skipping
3025 : : // this logic in that case. So even if the first header in this set
3026 : : // of headers is known, some header in this set must be new, so
3027 : : // advancing to the first unknown header would be a small effect.
3028 : 0 : LOCK(peer.m_headers_sync_mutex);
3029 [ # # # # ]: 0 : peer.m_headers_sync.reset(new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(),
3030 [ # # # # ]: 0 : m_chainparams.HeadersSync(), chain_start_header, minimum_chain_work));
3031 : :
3032 : : // Now a HeadersSyncState object for tracking this synchronization
3033 : : // is created, process the headers using it as normal. Failures are
3034 : : // handled inside of IsContinuationOfLowWorkHeadersSync.
3035 [ # # ]: 0 : (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3036 : 0 : } else {
3037 [ # # # # ]: 0 : LogDebug(BCLog::NET, "Ignoring low-work chain (height=%u) from peer=%d\n", chain_start_header.nHeight + headers.size(), pfrom.GetId());
3038 : : }
3039 : :
3040 : : // The peer has not yet given us a chain that meets our work threshold,
3041 : : // so we want to prevent further processing of the headers in any case.
3042 : 0 : headers = {};
3043 : 0 : return true;
3044 : : }
3045 : :
3046 : : return false;
3047 : : }
3048 : :
3049 : 0 : bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex* header)
3050 : : {
3051 [ # # ]: 0 : if (header == nullptr) {
3052 : : return false;
3053 [ # # # # ]: 0 : } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) {
3054 : : return true;
3055 [ # # ]: 0 : } else if (m_chainman.ActiveChain().Contains(*header)) {
3056 : 0 : return true;
3057 : : }
3058 : : return false;
3059 : : }
3060 : :
3061 : 3 : bool PeerManagerImpl::MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer)
3062 : : {
3063 : 3 : const auto current_time = NodeClock::now();
3064 : :
3065 : : // Only allow a new getheaders message to go out if we don't have a recent
3066 : : // one already in-flight
3067 [ + - ]: 3 : if (current_time - peer.m_last_getheaders_timestamp > HEADERS_RESPONSE_TIME) {
3068 [ + - ]: 3 : MakeAndPushMessage(pfrom, NetMsgType::GETHEADERS, locator, uint256());
3069 : 3 : peer.m_last_getheaders_timestamp = current_time;
3070 : 3 : return true;
3071 : : }
3072 : : return false;
3073 : : }
3074 : :
3075 : : /*
3076 : : * Given a new headers tip ending in last_header, potentially request blocks towards that tip.
3077 : : * We require that the given tip have at least as much work as our tip, and for
3078 : : * our current tip to be "close to synced" (see CanDirectFetch()).
3079 : : */
3080 : 0 : void PeerManagerImpl::HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header)
3081 : : {
3082 : 0 : LOCK(cs_main);
3083 : 0 : CNodeState *nodestate = State(pfrom.GetId());
3084 : :
3085 [ # # # # : 0 : if (CanDirectFetch() && last_header.IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork) {
# # # # #
# # # # #
# # ]
3086 : 0 : std::vector<const CBlockIndex*> vToFetch;
3087 : 0 : const CBlockIndex* pindexWalk{&last_header};
3088 : : // Calculate all the blocks we'd need to switch to last_header, up to a limit.
3089 [ # # # # : 0 : while (pindexWalk && !m_chainman.ActiveChain().Contains(*pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
# # # # ]
3090 [ # # ]: 0 : if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
3091 [ # # # # ]: 0 : !IsBlockRequested(pindexWalk->GetBlockHash()) &&
3092 [ # # ]: 0 : (!DeploymentActiveAt(*pindexWalk, m_chainman, Consensus::DEPLOYMENT_SEGWIT) || CanServeWitnesses(peer))) {
3093 : : // We don't have this block, and it's not yet in flight.
3094 [ # # ]: 0 : vToFetch.push_back(pindexWalk);
3095 : : }
3096 : 0 : pindexWalk = pindexWalk->pprev;
3097 : : }
3098 : : // If pindexWalk still isn't on our main chain, we're looking at a
3099 : : // very large reorg at a time we think we're close to caught up to
3100 : : // the main chain -- this shouldn't really happen. Bail out on the
3101 : : // direct fetch and rely on parallel download instead.
3102 : : // Common ancestor must exist (genesis).
3103 [ # # # # : 0 : if (!m_chainman.ActiveChain().Contains(*Assert(pindexWalk))) {
# # ]
3104 [ # # # # : 0 : LogDebug(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
# # # # ]
3105 : : last_header.GetBlockHash().ToString(),
3106 : : last_header.nHeight);
3107 : : } else {
3108 : 0 : std::vector<CInv> vGetData;
3109 : : // Download as much as possible, from earliest to latest.
3110 [ # # ]: 0 : for (const CBlockIndex* pindex : vToFetch | std::views::reverse) {
3111 [ # # ]: 0 : if (nodestate->vBlocksInFlight.size() >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3112 : : // Can't download any more from this peer
3113 : : break;
3114 : : }
3115 : 0 : uint32_t nFetchFlags = GetFetchFlags(peer);
3116 [ # # ]: 0 : vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash());
3117 [ # # ]: 0 : BlockRequested(pfrom.GetId(), *pindex);
3118 [ # # # # : 0 : LogDebug(BCLog::NET, "Requesting block %s from peer=%d",
# # # # ]
3119 : : pindex->GetBlockHash().ToString(), pfrom.GetId());
3120 : : }
3121 [ # # # # ]: 0 : if (vGetData.size() > 1) {
3122 [ # # # # : 0 : LogDebug(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
# # # # ]
3123 : : last_header.GetBlockHash().ToString(),
3124 : : last_header.nHeight);
3125 : : }
3126 [ # # # # ]: 0 : if (vGetData.size() > 0) {
3127 : 0 : if (!m_opts.ignore_incoming_txs &&
3128 [ # # ]: 0 : nodestate->m_provides_cmpctblocks &&
3129 [ # # # # ]: 0 : vGetData.size() == 1 &&
3130 [ # # # # ]: 0 : mapBlocksInFlight.size() == 1 &&
3131 [ # # # # ]: 0 : last_header.pprev->IsValid(BLOCK_VALID_CHAIN)) {
3132 : : // In any case, we want to download using a compact block, not a regular one
3133 [ # # ]: 0 : vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
3134 : : }
3135 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vGetData);
3136 : : }
3137 : 0 : }
3138 : 0 : }
3139 : 0 : }
3140 : :
3141 : : /**
3142 : : * Given receipt of headers from a peer ending in last_header, along with
3143 : : * whether that header was new and whether the headers message was full,
3144 : : * update the state we keep for the peer.
3145 : : */
3146 : 0 : void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer,
3147 : : const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers)
3148 : : {
3149 : 0 : LOCK(cs_main);
3150 : 0 : CNodeState *nodestate = State(pfrom.GetId());
3151 : :
3152 [ # # ]: 0 : UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash());
3153 : :
3154 : : // From here, pindexBestKnownBlock should be guaranteed to be non-null,
3155 : : // because it is set in UpdateBlockAvailability. Some nullptr checks
3156 : : // are still present, however, as belt-and-suspenders.
3157 : :
3158 [ # # # # : 0 : if (received_new_header && last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
# # # # #
# ]
3159 [ # # ]: 0 : nodestate->m_last_block_announcement = GetTime();
3160 : : }
3161 : :
3162 : : // If we're in IBD, we want outbound peers that will serve us a useful
3163 : : // chain. Disconnect peers that are on chains with insufficient work.
3164 [ # # # # ]: 0 : if (m_chainman.IsInitialBlockDownload() && !may_have_more_headers) {
3165 : : // If the peer has no more headers to give us, then we know we have
3166 : : // their tip.
3167 [ # # # # : 0 : if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) {
# # # # ]
3168 : : // This peer has too little work on their headers chain to help
3169 : : // us sync -- disconnect if it is an outbound disconnection
3170 : : // candidate.
3171 : : // Note: We compare their tip to the minimum chain work (rather than
3172 : : // m_chainman.ActiveChain().Tip()) because we won't start block download
3173 : : // until we have a headers chain that has at least
3174 : : // the minimum chain work, even if a peer has a chain past our tip,
3175 : : // as an anti-DoS measure.
3176 [ # # ]: 0 : if (pfrom.IsOutboundOrBlockRelayConn()) {
3177 [ # # # # ]: 0 : LogInfo("outbound peer headers chain has insufficient work, %s", pfrom.DisconnectMsg());
3178 : 0 : pfrom.fDisconnect = true;
3179 : : }
3180 : : }
3181 : : }
3182 : :
3183 : : // If this is an outbound full-relay peer, check to see if we should protect
3184 : : // it from the bad/lagging chain logic.
3185 : : // Note that outbound block-relay peers are excluded from this protection, and
3186 : : // thus always subject to eviction under the bad/lagging chain logic.
3187 : : // See ChainSyncTimeoutState.
3188 [ # # # # : 0 : if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) {
# # ]
3189 [ # # # # : 0 : 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) {
# # # # #
# # # ]
3190 [ # # # # : 0 : LogDebug(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId());
# # ]
3191 : 0 : nodestate->m_chain_sync.m_protect = true;
3192 : 0 : ++m_outbound_peers_with_protect_from_disconnect;
3193 : : }
3194 : : }
3195 : 0 : }
3196 : :
3197 : 0 : void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, Peer& peer,
3198 : : std::vector<CBlockHeader>&& headers,
3199 : : bool via_compact_block)
3200 : : {
3201 [ # # ]: 0 : size_t nCount = headers.size();
3202 : :
3203 [ # # ]: 0 : if (nCount == 0) {
3204 : : // Nothing interesting. Stop asking this peers for more headers.
3205 : : // If we were in the middle of headers sync, receiving an empty headers
3206 : : // message suggests that the peer suddenly has nothing to give us
3207 : : // (perhaps it reorged to our chain). Clear download state for this peer.
3208 : 0 : LOCK(peer.m_headers_sync_mutex);
3209 [ # # ]: 0 : if (peer.m_headers_sync) {
3210 : 0 : peer.m_headers_sync.reset(nullptr);
3211 [ # # ]: 0 : LOCK(m_headers_presync_mutex);
3212 [ # # ]: 0 : m_headers_presync_stats.erase(pfrom.GetId());
3213 : 0 : }
3214 : : // A headers message with no headers cannot be an announcement, so assume
3215 : : // it is a response to our last getheaders request, if there is one.
3216 : 0 : peer.m_last_getheaders_timestamp = {};
3217 [ # # ]: 0 : return;
3218 : 0 : }
3219 : :
3220 : : // Before we do any processing, make sure these pass basic sanity checks.
3221 : : // We'll rely on headers having valid proof-of-work further down, as an
3222 : : // anti-DoS criteria (note: this check is required before passing any
3223 : : // headers into HeadersSyncState).
3224 [ # # ]: 0 : if (!CheckHeadersPoW(headers, peer)) {
3225 : : // Misbehaving() calls are handled within CheckHeadersPoW(), so we can
3226 : : // just return. (Note that even if a header is announced via compact
3227 : : // block, the header itself should be valid, so this type of error can
3228 : : // always be punished.)
3229 : : return;
3230 : : }
3231 : :
3232 : 0 : const CBlockIndex *pindexLast = nullptr;
3233 : :
3234 : : // We'll set already_validated_work to true if these headers are
3235 : : // successfully processed as part of a low-work headers sync in progress
3236 : : // (either in PRESYNC or REDOWNLOAD phase).
3237 : : // If true, this will mean that any headers returned to us (ie during
3238 : : // REDOWNLOAD) can be validated without further anti-DoS checks.
3239 : 0 : bool already_validated_work = false;
3240 : :
3241 : : // If we're in the middle of headers sync, let it do its magic.
3242 : 0 : bool have_headers_sync = false;
3243 : 0 : {
3244 : 0 : LOCK(peer.m_headers_sync_mutex);
3245 : :
3246 [ # # ]: 0 : already_validated_work = IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3247 : :
3248 : : // The headers we passed in may have been:
3249 : : // - untouched, perhaps if no headers-sync was in progress, or some
3250 : : // failure occurred
3251 : : // - erased, such as if the headers were successfully processed and no
3252 : : // additional headers processing needs to take place (such as if we
3253 : : // are still in PRESYNC)
3254 : : // - replaced with headers that are now ready for validation, such as
3255 : : // during the REDOWNLOAD phase of a low-work headers sync.
3256 : : // So just check whether we still have headers that we need to process,
3257 : : // or not.
3258 [ # # ]: 0 : if (headers.empty()) {
3259 [ # # ]: 0 : return;
3260 : : }
3261 : :
3262 [ # # ]: 0 : have_headers_sync = !!peer.m_headers_sync;
3263 : 0 : }
3264 : :
3265 : : // Do these headers connect to something in our block index?
3266 [ # # # # ]: 0 : const CBlockIndex *chain_start_header{WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock))};
3267 : 0 : bool headers_connect_blockindex{chain_start_header != nullptr};
3268 : :
3269 [ # # ]: 0 : if (!headers_connect_blockindex) {
3270 : : // This could be a BIP 130 block announcement, use
3271 : : // special logic for handling headers that don't connect, as this
3272 : : // could be benign.
3273 : 0 : HandleUnconnectingHeaders(pfrom, peer, headers);
3274 : 0 : return;
3275 : : }
3276 : :
3277 : : // If headers connect, assume that this is in response to any outstanding getheaders
3278 : : // request we may have sent, and clear out the time of our last request. Non-connecting
3279 : : // headers cannot be a response to a getheaders request.
3280 : 0 : peer.m_last_getheaders_timestamp = {};
3281 : :
3282 : : // If the headers we received are already in memory and an ancestor of
3283 : : // m_best_header or our tip, skip anti-DoS checks. These headers will not
3284 : : // use any more memory (and we are not leaking information that could be
3285 : : // used to fingerprint us).
3286 : 0 : const CBlockIndex *last_received_header{nullptr};
3287 : 0 : {
3288 : 0 : LOCK(cs_main);
3289 [ # # # # ]: 0 : last_received_header = m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash());
3290 [ # # # # : 0 : already_validated_work = already_validated_work || IsAncestorOfBestHeaderOrTip(last_received_header);
# # # # ]
3291 : 0 : }
3292 : :
3293 : : // If our peer has NetPermissionFlags::NoBan privileges, then bypass our
3294 : : // anti-DoS logic (this saves bandwidth when we connect to a trusted peer
3295 : : // on startup).
3296 [ # # ]: 0 : if (pfrom.HasPermission(NetPermissionFlags::NoBan)) {
3297 : : already_validated_work = true;
3298 : : }
3299 : :
3300 : : // At this point, the headers connect to something in our block index.
3301 : : // Do anti-DoS checks to determine if we should process or store for later
3302 : : // processing.
3303 [ # # # # ]: 0 : if (!already_validated_work && TryLowWorkHeadersSync(peer, pfrom,
3304 : : *chain_start_header, headers)) {
3305 : : // If we successfully started a low-work headers sync, then there
3306 : : // should be no headers to process any further.
3307 : 0 : Assume(headers.empty());
3308 : 0 : return;
3309 : : }
3310 : :
3311 : : // At this point, we have a set of headers with sufficient work on them
3312 : : // which can be processed.
3313 : :
3314 : : // If we don't have the last header, then this peer will have given us
3315 : : // something new (if these headers are valid).
3316 : 0 : bool received_new_header{last_received_header == nullptr};
3317 : :
3318 : : // Now process all the headers.
3319 [ # # ]: 0 : BlockValidationState state;
3320 [ # # # # ]: 0 : const bool processed{m_chainman.ProcessNewBlockHeaders(headers,
3321 : : /*min_pow_checked=*/true,
3322 : : state, &pindexLast)};
3323 [ # # ]: 0 : if (!processed) {
3324 [ # # ]: 0 : if (state.IsInvalid()) {
3325 [ # # # # ]: 0 : if (!pfrom.IsInboundConn() && state.GetResult() == BlockValidationResult::BLOCK_CACHED_INVALID) {
3326 : : // Warn user if outgoing peers send us headers of blocks that we previously marked as invalid.
3327 [ # # # # ]: 0 : LogWarning("%s (received from peer=%i). "
3328 : : "If this happens with all peers, consider database corruption (that -reindex may fix) "
3329 : : "or a potential consensus incompatibility.",
3330 : : state.GetDebugMessage(), pfrom.GetId());
3331 : : }
3332 [ # # # # ]: 0 : MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received");
3333 : 0 : return;
3334 : : }
3335 : : }
3336 [ # # ]: 0 : assert(pindexLast);
3337 : :
3338 [ # # ]: 0 : if (processed && received_new_header) {
3339 [ # # ]: 0 : LogBlockHeader(*pindexLast, pfrom, /*via_compact_block=*/false);
3340 : : }
3341 : :
3342 : : // Consider fetching more headers if we are not using our headers-sync mechanism.
3343 [ # # # # ]: 0 : if (nCount == m_opts.max_headers_result && !have_headers_sync) {
3344 : : // Headers message had its maximum size; the peer may have more headers.
3345 [ # # # # : 0 : if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) {
# # ]
3346 [ # # # # : 0 : LogDebug(BCLog::NET, "more getheaders (%d) to end to peer=%d", pindexLast->nHeight, pfrom.GetId());
# # ]
3347 : : }
3348 : : }
3349 : :
3350 [ # # ]: 0 : UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast, received_new_header, nCount == m_opts.max_headers_result);
3351 : :
3352 : : // Consider immediately downloading blocks.
3353 [ # # ]: 0 : HeadersDirectFetchBlocks(pfrom, peer, *pindexLast);
3354 : :
3355 : : return;
3356 : 0 : }
3357 : :
3358 : 0 : std::optional<node::PackageToValidate> PeerManagerImpl::ProcessInvalidTx(NodeId nodeid, const CTransactionRef& ptx, const TxValidationState& state,
3359 : : bool first_time_failure)
3360 : : {
3361 : 0 : AssertLockNotHeld(m_peer_mutex);
3362 : 0 : AssertLockHeld(g_msgproc_mutex);
3363 : 0 : AssertLockHeld(m_tx_download_mutex);
3364 : :
3365 : 0 : PeerRef peer{GetPeerRef(nodeid)};
3366 : :
3367 [ # # # # : 0 : LogDebug(BCLog::MEMPOOLREJ, "%s (wtxid=%s) from peer=%d was not accepted: %s\n",
# # # # #
# # # ]
3368 : : ptx->GetHash().ToString(),
3369 : : ptx->GetWitnessHash().ToString(),
3370 : : nodeid,
3371 : : state.ToString());
3372 : :
3373 [ # # ]: 0 : const auto& [add_extra_compact_tx, unique_parents, package_to_validate] = m_txdownloadman.MempoolRejectedTx(ptx, state, nodeid, first_time_failure);
3374 : :
3375 [ # # # # ]: 0 : if (add_extra_compact_tx && RecursiveDynamicUsage(*ptx) < 100000) {
3376 [ # # ]: 0 : AddToCompactExtraTransactions(ptx);
3377 : : }
3378 [ # # ]: 0 : for (const Txid& parent_txid : unique_parents) {
3379 [ # # # # ]: 0 : if (peer) AddKnownTx(*peer, parent_txid.ToUint256());
3380 : : }
3381 : :
3382 [ # # ]: 0 : return package_to_validate;
3383 [ # # ]: 0 : }
3384 : :
3385 : 0 : void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions)
3386 : : {
3387 : 0 : AssertLockNotHeld(m_peer_mutex);
3388 : 0 : AssertLockHeld(g_msgproc_mutex);
3389 : 0 : AssertLockHeld(m_tx_download_mutex);
3390 : :
3391 : 0 : m_txdownloadman.MempoolAcceptedTx(tx);
3392 : :
3393 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (wtxid=%s) (poolsz %u txn, %u kB)\n",
# # ]
3394 : : nodeid,
3395 : : tx->GetHash().ToString(),
3396 : : tx->GetWitnessHash().ToString(),
3397 : : m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000);
3398 : :
3399 : 0 : InitiateTxBroadcastToAll(tx->GetWitnessHash());
3400 : :
3401 [ # # ]: 0 : for (const CTransactionRef& removedTx : replaced_transactions) {
3402 : 0 : AddToCompactExtraTransactions(removedTx);
3403 : : }
3404 : 0 : }
3405 : :
3406 : 0 : void PeerManagerImpl::ProcessPackageResult(const node::PackageToValidate& package_to_validate, const PackageMempoolAcceptResult& package_result)
3407 : : {
3408 : 0 : AssertLockNotHeld(m_peer_mutex);
3409 : 0 : AssertLockHeld(g_msgproc_mutex);
3410 : 0 : AssertLockHeld(m_tx_download_mutex);
3411 : :
3412 : 0 : const auto& package = package_to_validate.m_txns;
3413 : 0 : const auto& senders = package_to_validate.m_senders;
3414 : :
3415 [ # # ]: 0 : if (package_result.m_state.IsInvalid()) {
3416 : 0 : m_txdownloadman.MempoolRejectedPackage(package);
3417 : : }
3418 : : // We currently only expect to process 1-parent-1-child packages. Remove if this changes.
3419 [ # # # # ]: 0 : if (!Assume(package.size() == 2)) return;
3420 : :
3421 : : // Iterate backwards to erase in-package descendants from the orphanage before they become
3422 : : // relevant in AddChildrenToWorkSet.
3423 : 0 : auto package_iter = package.rbegin();
3424 : 0 : auto senders_iter = senders.rbegin();
3425 [ # # ]: 0 : while (package_iter != package.rend()) {
3426 : 0 : const auto& tx = *package_iter;
3427 : 0 : const NodeId nodeid = *senders_iter;
3428 : 0 : const auto it_result{package_result.m_tx_results.find(tx->GetWitnessHash())};
3429 : :
3430 : : // It is not guaranteed that a result exists for every transaction.
3431 [ # # ]: 0 : if (it_result != package_result.m_tx_results.end()) {
3432 [ # # # # ]: 0 : const auto& tx_result = it_result->second;
3433 [ # # # # ]: 0 : switch (tx_result.m_result_type) {
3434 : 0 : case MempoolAcceptResult::ResultType::VALID:
3435 : 0 : {
3436 : 0 : ProcessValidTx(nodeid, tx, tx_result.m_replaced_transactions);
3437 : 0 : break;
3438 : : }
3439 : 0 : case MempoolAcceptResult::ResultType::INVALID:
3440 : 0 : case MempoolAcceptResult::ResultType::DIFFERENT_WITNESS:
3441 : 0 : {
3442 : : // Don't add to vExtraTxnForCompact, as these transactions should have already been
3443 : : // added there when added to the orphanage or rejected for TX_RECONSIDERABLE.
3444 : : // This should be updated if package submission is ever used for transactions
3445 : : // that haven't already been validated before.
3446 [ # # ]: 0 : ProcessInvalidTx(nodeid, tx, tx_result.m_state, /*first_time_failure=*/false);
3447 : 0 : break;
3448 : : }
3449 : 0 : case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY:
3450 : 0 : {
3451 : : // AlreadyHaveTx() should be catching transactions that are already in mempool.
3452 : 0 : Assume(false);
3453 : 0 : break;
3454 : : }
3455 : : }
3456 : : }
3457 : 0 : package_iter++;
3458 : 0 : senders_iter++;
3459 : : }
3460 : : }
3461 : :
3462 : : // NOTE: the orphan processing used to be uninterruptible and quadratic, which could allow a peer to stall the node for
3463 : : // hours with specially crafted transactions. See https://bitcoincore.org/en/2024/07/03/disclose-orphan-dos.
3464 : 5 : bool PeerManagerImpl::ProcessOrphanTx(Peer& peer)
3465 : : {
3466 : 5 : AssertLockHeld(g_msgproc_mutex);
3467 [ + - ]: 5 : LOCK2(::cs_main, m_tx_download_mutex);
3468 : :
3469 : 5 : CTransactionRef porphanTx = nullptr;
3470 : :
3471 [ + - - + : 5 : while (CTransactionRef porphanTx = m_txdownloadman.GetTxToReconsider(peer.m_id)) {
- - ]
3472 [ # # ]: 0 : const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx);
3473 : 0 : const TxValidationState& state = result.m_state;
3474 [ # # ]: 0 : const Txid& orphanHash = porphanTx->GetHash();
3475 [ # # ]: 0 : const Wtxid& orphan_wtxid = porphanTx->GetWitnessHash();
3476 : :
3477 [ # # ]: 0 : if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
3478 [ # # # # : 0 : LogDebug(BCLog::TXPACKAGES, " accepted orphan tx %s (wtxid=%s)\n", orphanHash.ToString(), orphan_wtxid.ToString());
# # # # #
# ]
3479 [ # # ]: 0 : ProcessValidTx(peer.m_id, porphanTx, result.m_replaced_transactions);
3480 : : return true;
3481 [ # # ]: 0 : } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) {
3482 [ # # # # : 0 : LogDebug(BCLog::TXPACKAGES, " invalid orphan tx %s (wtxid=%s) from peer=%d. %s\n",
# # # # #
# # # ]
3483 : : orphanHash.ToString(),
3484 : : orphan_wtxid.ToString(),
3485 : : peer.m_id,
3486 : : state.ToString());
3487 : :
3488 [ # # # # : 0 : if (Assume(state.IsInvalid() &&
# # # # #
# ]
3489 : : state.GetResult() != TxValidationResult::TX_UNKNOWN &&
3490 : : state.GetResult() != TxValidationResult::TX_NO_MEMPOOL &&
3491 : : state.GetResult() != TxValidationResult::TX_RESULT_UNSET)) {
3492 [ # # ]: 0 : ProcessInvalidTx(peer.m_id, porphanTx, state, /*first_time_failure=*/false);
3493 : : }
3494 : 0 : return true;
3495 : : }
3496 [ # # ]: 0 : }
3497 : :
3498 : 5 : return false;
3499 [ + - + - : 15 : }
- - ]
3500 : :
3501 : 0 : bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& node, Peer& peer,
3502 : : BlockFilterType filter_type, uint32_t start_height,
3503 : : const uint256& stop_hash, uint32_t max_height_diff,
3504 : : const CBlockIndex*& stop_index,
3505 : : BlockFilterIndex*& filter_index)
3506 : : {
3507 : 0 : const bool supported_filter_type =
3508 [ # # ]: 0 : (filter_type == BlockFilterType::BASIC &&
3509 [ # # ]: 0 : (peer.m_our_services & NODE_COMPACT_FILTERS));
3510 : 0 : if (!supported_filter_type) {
3511 [ # # # # ]: 0 : LogDebug(BCLog::NET, "peer requested unsupported block filter type: %d, %s",
3512 : : static_cast<uint8_t>(filter_type), node.DisconnectMsg());
3513 : 0 : node.fDisconnect = true;
3514 : 0 : return false;
3515 : : }
3516 : :
3517 : 0 : {
3518 : 0 : LOCK(cs_main);
3519 [ # # ]: 0 : stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
3520 : :
3521 : : // Check that the stop block exists and the peer would be allowed to fetch it.
3522 [ # # # # : 0 : if (!stop_index || !BlockRequestAllowed(*stop_index)) {
# # ]
3523 [ # # # # : 0 : LogDebug(BCLog::NET, "peer requested invalid block hash: %s, %s",
# # # # #
# ]
3524 : : stop_hash.ToString(), node.DisconnectMsg());
3525 [ # # ]: 0 : node.fDisconnect = true;
3526 [ # # ]: 0 : return false;
3527 : : }
3528 : 0 : }
3529 : :
3530 : 0 : uint32_t stop_height = stop_index->nHeight;
3531 [ # # ]: 0 : if (start_height > stop_height) {
3532 [ # # # # ]: 0 : LogDebug(BCLog::NET, "peer sent invalid getcfilters/getcfheaders with "
3533 : : "start height %d and stop height %d, %s",
3534 : : start_height, stop_height, node.DisconnectMsg());
3535 : 0 : node.fDisconnect = true;
3536 : 0 : return false;
3537 : : }
3538 [ # # ]: 0 : if (stop_height - start_height >= max_height_diff) {
3539 [ # # # # ]: 0 : LogDebug(BCLog::NET, "peer requested too many cfilters/cfheaders: %d / %d, %s",
3540 : : stop_height - start_height + 1, max_height_diff, node.DisconnectMsg());
3541 : 0 : node.fDisconnect = true;
3542 : 0 : return false;
3543 : : }
3544 : :
3545 : 0 : filter_index = GetBlockFilterIndex(filter_type);
3546 [ # # ]: 0 : if (!filter_index) {
3547 [ # # ]: 0 : LogDebug(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type));
3548 : 0 : return false;
3549 : : }
3550 : :
3551 : : return true;
3552 : : }
3553 : :
3554 : 0 : void PeerManagerImpl::ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv)
3555 : : {
3556 : 0 : uint8_t filter_type_ser;
3557 : 0 : uint32_t start_height;
3558 : 0 : uint256 stop_hash;
3559 : :
3560 : 0 : vRecv >> filter_type_ser >> start_height >> stop_hash;
3561 : :
3562 : 0 : const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3563 : :
3564 : 0 : const CBlockIndex* stop_index;
3565 : 0 : BlockFilterIndex* filter_index;
3566 [ # # ]: 0 : if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
3567 : : MAX_GETCFILTERS_SIZE, stop_index, filter_index)) {
3568 : : return;
3569 : : }
3570 : :
3571 : 0 : std::vector<BlockFilter> filters;
3572 [ # # # # ]: 0 : if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
3573 [ # # # # : 0 : LogDebug(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
# # # # #
# ]
3574 : : BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
3575 : 0 : return;
3576 : : }
3577 : :
3578 [ # # ]: 0 : for (const auto& filter : filters) {
3579 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::CFILTER, filter);
3580 : : }
3581 : 0 : }
3582 : :
3583 : 0 : void PeerManagerImpl::ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv)
3584 : : {
3585 : 0 : uint8_t filter_type_ser;
3586 : 0 : uint32_t start_height;
3587 : 0 : uint256 stop_hash;
3588 : :
3589 : 0 : vRecv >> filter_type_ser >> start_height >> stop_hash;
3590 : :
3591 : 0 : const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3592 : :
3593 : 0 : const CBlockIndex* stop_index;
3594 : 0 : BlockFilterIndex* filter_index;
3595 [ # # ]: 0 : if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
3596 : : MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) {
3597 : : return;
3598 : : }
3599 : :
3600 : 0 : uint256 prev_header;
3601 [ # # ]: 0 : if (start_height > 0) {
3602 : 0 : const CBlockIndex* const prev_block =
3603 : 0 : stop_index->GetAncestor(static_cast<int>(start_height - 1));
3604 [ # # ]: 0 : if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
3605 [ # # # # : 0 : LogDebug(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
# # ]
3606 : : BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString());
3607 : 0 : return;
3608 : : }
3609 : : }
3610 : :
3611 : 0 : std::vector<uint256> filter_hashes;
3612 [ # # # # ]: 0 : if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) {
3613 [ # # # # : 0 : LogDebug(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
# # # # #
# ]
3614 : : BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
3615 : 0 : return;
3616 : : }
3617 : :
3618 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::CFHEADERS,
3619 : : filter_type_ser,
3620 : 0 : stop_index->GetBlockHash(),
3621 : : prev_header,
3622 : : filter_hashes);
3623 : 0 : }
3624 : :
3625 : 0 : void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv)
3626 : : {
3627 : 0 : uint8_t filter_type_ser;
3628 : 0 : uint256 stop_hash;
3629 : :
3630 : 0 : vRecv >> filter_type_ser >> stop_hash;
3631 : :
3632 : 0 : const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3633 : :
3634 : 0 : const CBlockIndex* stop_index;
3635 : 0 : BlockFilterIndex* filter_index;
3636 [ # # ]: 0 : if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash,
3637 : : /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
3638 : : stop_index, filter_index)) {
3639 : : return;
3640 : : }
3641 : :
3642 : 0 : std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
3643 : :
3644 : : // Populate headers.
3645 : 0 : const CBlockIndex* block_index = stop_index;
3646 [ # # # # ]: 0 : for (int i = headers.size() - 1; i >= 0; i--) {
3647 : 0 : int height = (i + 1) * CFCHECKPT_INTERVAL;
3648 [ # # ]: 0 : block_index = block_index->GetAncestor(height);
3649 : :
3650 [ # # # # ]: 0 : if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
3651 [ # # # # : 0 : LogDebug(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
# # # # #
# ]
3652 : : BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());
3653 : 0 : return;
3654 : : }
3655 : : }
3656 : :
3657 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::CFCHECKPT,
3658 : : filter_type_ser,
3659 : 0 : stop_index->GetBlockHash(),
3660 : : headers);
3661 : 0 : }
3662 : :
3663 : 0 : void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)
3664 : : {
3665 : 0 : bool new_block{false};
3666 : 0 : m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block);
3667 [ # # ]: 0 : if (new_block) {
3668 : 0 : node.m_last_block_time = GetTime<std::chrono::seconds>();
3669 : : // In case this block came from a different peer than we requested
3670 : : // from, we can erase the block request now anyway (as we just stored
3671 : : // this block to disk).
3672 : 0 : LOCK(cs_main);
3673 [ # # # # ]: 0 : RemoveBlockRequest(block->GetHash(), std::nullopt);
3674 : 0 : } else {
3675 : 0 : LOCK(cs_main);
3676 [ # # # # ]: 0 : mapBlockSource.erase(block->GetHash());
3677 : 0 : }
3678 : 0 : }
3679 : :
3680 : 0 : void PeerManagerImpl::ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions)
3681 : : {
3682 : 0 : std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3683 : 0 : bool fBlockRead{false};
3684 : 0 : {
3685 [ # # ]: 0 : LOCK(cs_main);
3686 : :
3687 : 0 : auto range_flight = mapBlocksInFlight.equal_range(block_transactions.blockhash);
3688 : 0 : size_t already_in_flight = std::distance(range_flight.first, range_flight.second);
3689 : 0 : bool requested_block_from_this_peer{false};
3690 : :
3691 : : // Multimap ensures ordering of outstanding requests. It's either empty or first in line.
3692 [ # # # # ]: 0 : bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId());
3693 : :
3694 [ # # ]: 0 : while (range_flight.first != range_flight.second) {
3695 [ # # ]: 0 : auto [node_id, block_it] = range_flight.first->second;
3696 [ # # # # ]: 0 : if (node_id == pfrom.GetId() && block_it->partialBlock) {
3697 : : requested_block_from_this_peer = true;
3698 : : break;
3699 : : }
3700 : 0 : range_flight.first++;
3701 : : }
3702 : :
3703 [ # # ]: 0 : if (!requested_block_from_this_peer) {
3704 [ # # # # : 0 : LogDebug(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId());
# # ]
3705 : 0 : return;
3706 : : }
3707 : :
3708 [ # # ]: 0 : PartiallyDownloadedBlock& partialBlock = *range_flight.first->second.second->partialBlock;
3709 : :
3710 [ # # ]: 0 : if (partialBlock.header.IsNull()) {
3711 : : // It is possible for the header to be empty if a previous call to FillBlock wiped the header, but left
3712 : : // the PartiallyDownloadedBlock pointer around (i.e. did not call RemoveBlockRequest). In this case, we
3713 : : // should not call LookupBlockIndex below.
3714 [ # # ]: 0 : RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId());
3715 [ # # # # ]: 0 : Misbehaving(peer, "previous compact block reconstruction attempt failed");
3716 [ # # # # : 0 : LogDebug(BCLog::NET, "Peer %d sent compact block transactions multiple times", pfrom.GetId());
# # ]
3717 : 0 : return;
3718 : : }
3719 : :
3720 : : // We should not have gotten this far in compact block processing unless it's attached to a known header
3721 [ # # ]: 0 : const CBlockIndex* prev_block{Assume(m_chainman.m_blockman.LookupBlockIndex(partialBlock.header.hashPrevBlock))};
3722 [ # # ]: 0 : ReadStatus status = partialBlock.FillBlock(*pblock, block_transactions.txn,
3723 : 0 : /*segwit_active=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT));
3724 [ # # ]: 0 : if (status == READ_STATUS_INVALID) {
3725 [ # # ]: 0 : RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect
3726 [ # # # # ]: 0 : Misbehaving(peer, "invalid compact block/non-matching block transactions");
3727 : 0 : return;
3728 [ # # ]: 0 : } else if (status == READ_STATUS_FAILED) {
3729 [ # # ]: 0 : if (first_in_flight) {
3730 : : // Might have collided, fall back to getdata now :(
3731 : : // We keep the failed partialBlock to disallow processing another compact block announcement from the same
3732 : : // peer for the same block. We let the full block download below continue under the same m_downloading_since
3733 : : // timer.
3734 : 0 : std::vector<CInv> invs;
3735 [ # # ]: 0 : invs.emplace_back(MSG_BLOCK | GetFetchFlags(peer), block_transactions.blockhash);
3736 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::GETDATA, invs);
3737 : 0 : } else {
3738 [ # # ]: 0 : RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId());
3739 [ # # # # : 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());
# # ]
3740 : 0 : return;
3741 : : }
3742 : : } else {
3743 : : // Block is okay for further processing
3744 [ # # ]: 0 : RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // it is now an empty pointer
3745 : 0 : fBlockRead = true;
3746 : : // mapBlockSource is used for potentially punishing peers and
3747 : : // updating which peers send us compact blocks, so the race
3748 : : // between here and cs_main in ProcessNewBlock is fine.
3749 : : // BIP 152 permits peers to relay compact blocks after validating
3750 : : // the header only; we should not punish peers if the block turns
3751 : : // out to be invalid.
3752 [ # # ]: 0 : mapBlockSource.emplace(block_transactions.blockhash, std::make_pair(pfrom.GetId(), false));
3753 : : }
3754 : 0 : } // Don't hold cs_main when we call into ProcessNewBlock
3755 [ # # ]: 0 : if (fBlockRead) {
3756 : : // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
3757 : : // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
3758 : : // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
3759 : : // disk-space attacks), but this should be safe due to the
3760 : : // protections in the compact block handler -- see related comment
3761 : : // in compact block optimistic reconstruction handling.
3762 [ # # # # ]: 0 : ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
3763 : : }
3764 : : return;
3765 : 0 : }
3766 : :
3767 : 0 : void PeerManagerImpl::LogBlockHeader(const CBlockIndex& index, const CNode& peer, bool via_compact_block) {
3768 : : // To prevent log spam, this function should only be called after it was determined that a
3769 : : // header is both new and valid.
3770 : : //
3771 : : // These messages are valuable for detecting potential selfish mining behavior;
3772 : : // if multiple displacing headers are seen near simultaneously across many
3773 : : // nodes in the network, this might be an indication of selfish mining.
3774 : : // In addition it can be used to identify peers which send us a header, but
3775 : : // don't followup with a complete and valid (compact) block.
3776 : : // Having this log by default when not in IBD ensures broad availability of
3777 : : // this data in case investigation is merited.
3778 : 0 : const auto msg = strprintf(
3779 : : "Saw new %sheader hash=%s height=%d %s",
3780 [ # # ]: 0 : via_compact_block ? "cmpctblock " : "",
3781 [ # # ]: 0 : index.GetBlockHash().ToString(),
3782 : 0 : index.nHeight,
3783 : 0 : peer.LogPeer()
3784 [ # # ]: 0 : );
3785 [ # # ]: 0 : if (m_chainman.IsInitialBlockDownload()) {
3786 [ # # # # : 0 : LogDebug(BCLog::VALIDATION, "%s", msg);
# # ]
3787 : : } else {
3788 [ # # ]: 0 : LogInfo("%s", msg);
3789 : : }
3790 : 0 : }
3791 : :
3792 : 0 : void PeerManagerImpl::PushPrivateBroadcastTx(CNode& node)
3793 : : {
3794 : 0 : Assume(node.IsPrivateBroadcastConn());
3795 : :
3796 [ # # ]: 0 : const auto opt_tx{m_tx_for_private_broadcast.PickTxForSend(node.GetId(), CService{node.addr})};
3797 [ # # ]: 0 : if (!opt_tx) {
3798 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "Disconnecting: no more transactions for private broadcast (connected in vain), %s", node.LogPeer());
# # # # ]
3799 : 0 : node.fDisconnect = true;
3800 : 0 : return;
3801 : : }
3802 [ # # ]: 0 : const CTransactionRef& tx{*opt_tx};
3803 : :
3804 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "P2P handshake completed, sending INV for txid=%s%s, %s",
# # # # #
# # # # #
# # # # #
# # # ]
3805 : : tx->GetHash().ToString(), tx->HasWitness() ? strprintf(", wtxid=%s", tx->GetWitnessHash().ToString()) : "",
3806 : : node.LogPeer());
3807 : :
3808 [ # # # # : 0 : MakeAndPushMessage(node, NetMsgType::INV, std::vector<CInv>{{CInv{MSG_TX, tx->GetHash().ToUint256()}}});
# # # # ]
3809 : 0 : }
3810 : :
3811 : 5 : void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string& msg_type, DataStream& vRecv,
3812 : : const NodeClock::time_point time_received,
3813 : : const std::atomic<bool>& interruptMsgProc)
3814 : : {
3815 : 5 : AssertLockHeld(g_msgproc_mutex);
3816 : :
3817 [ + - - + : 5 : LogDebug(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
- + + - ]
3818 : :
3819 : :
3820 [ + + ]: 5 : if (msg_type == NetMsgType::VERSION) {
3821 [ - + ]: 3 : if (pfrom.nVersion != 0) {
3822 [ # # ]: 0 : LogDebug(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId());
3823 : 0 : return;
3824 : : }
3825 : :
3826 : 3 : int64_t nTime;
3827 : 3 : CService addrMe;
3828 : 3 : uint64_t nNonce = 1;
3829 : 3 : ServiceFlags nServices;
3830 : 3 : int nVersion;
3831 [ + - ]: 3 : std::string cleanSubVer;
3832 : 3 : int starting_height = -1;
3833 : 3 : bool fRelay = true;
3834 : :
3835 [ + - + - : 3 : vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
+ - ]
3836 [ - + ]: 3 : if (nTime < 0) {
3837 : 0 : nTime = 0;
3838 : : }
3839 [ + - ]: 3 : vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer
3840 [ + - ]: 3 : vRecv >> CNetAddr::V1(addrMe);
3841 [ + - + + ]: 3 : if (!pfrom.IsInboundConn() && !pfrom.IsPrivateBroadcastConn())
3842 : : {
3843 : : // Overwrites potentially existing services. In contrast to this,
3844 : : // unvalidated services received via gossip relay in ADDR/ADDRV2
3845 : : // messages are only ever added but cannot replace existing ones.
3846 [ + - ]: 2 : m_addrman.SetServices(pfrom.addr, nServices);
3847 : : }
3848 [ + - + + ]: 3 : if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices))
3849 : : {
3850 [ + - + - : 1 : LogDebug(BCLog::NET, "peer does not offer the expected services (%08x offered, %08x expected), %s",
+ - + - ]
3851 : : nServices,
3852 : : GetDesirableServiceFlags(nServices),
3853 : : pfrom.DisconnectMsg());
3854 : 1 : pfrom.fDisconnect = true;
3855 : 1 : return;
3856 : : }
3857 : :
3858 [ - + ]: 2 : if (nVersion < MIN_PEER_PROTO_VERSION) {
3859 : : // disconnect from peers older than this proto version
3860 [ # # # # : 0 : LogDebug(BCLog::NET, "peer using obsolete version %i, %s", nVersion, pfrom.DisconnectMsg());
# # # # ]
3861 : 0 : pfrom.fDisconnect = true;
3862 : 0 : return;
3863 : : }
3864 : :
3865 [ - + + + ]: 2 : if (!vRecv.empty()) {
3866 : : // The version message includes information about the sending node which we don't use:
3867 : : // - 8 bytes (service bits)
3868 : : // - 16 bytes (ipv6 address)
3869 : : // - 2 bytes (port)
3870 [ + - ]: 1 : vRecv.ignore(26);
3871 [ + - ]: 1 : vRecv >> nNonce;
3872 : : }
3873 [ - + + + ]: 2 : if (!vRecv.empty()) {
3874 [ + - ]: 1 : std::string strSubVer;
3875 [ + - ]: 1 : vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
3876 [ - + + - ]: 1 : cleanSubVer = SanitizeString(strSubVer);
3877 : 1 : }
3878 [ - + + + ]: 2 : if (!vRecv.empty()) {
3879 [ + - ]: 1 : vRecv >> starting_height;
3880 : : }
3881 [ - + + + ]: 2 : if (!vRecv.empty())
3882 [ + - ]: 1 : vRecv >> fRelay;
3883 : : // Disconnect if we connected to ourself
3884 [ - + - - : 2 : if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce))
- - ]
3885 : : {
3886 [ # # # # ]: 0 : LogInfo("connected to self at %s, disconnecting\n", pfrom.addr.ToStringAddrPort());
3887 : 0 : pfrom.fDisconnect = true;
3888 : 0 : return;
3889 : : }
3890 : :
3891 [ - + - - : 2 : if (pfrom.IsInboundConn() && addrMe.IsRoutable())
- - ]
3892 : : {
3893 [ # # ]: 0 : SeenLocal(addrMe);
3894 : : }
3895 : :
3896 : : // Inbound peers send us their version message when they connect.
3897 : : // We send our version message in response.
3898 [ - + ]: 2 : if (pfrom.IsInboundConn()) {
3899 [ # # ]: 0 : PushNodeVersion(pfrom, peer);
3900 : : }
3901 : :
3902 : : // Change version
3903 [ + - + - ]: 4 : const int greatest_common_version = std::min(nVersion, pfrom.AdvertisedVersion());
3904 : 2 : pfrom.SetCommonVersion(greatest_common_version);
3905 : 2 : pfrom.nVersion = nVersion;
3906 : :
3907 [ + - ]: 2 : pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices);
3908 [ + - ]: 2 : peer.m_their_services = nServices;
3909 [ + - ]: 2 : pfrom.SetAddrLocal(addrMe);
3910 : 2 : {
3911 [ + - ]: 2 : LOCK(pfrom.m_subver_mutex);
3912 [ + - + - ]: 4 : pfrom.cleanSubVer = cleanSubVer;
3913 : 0 : }
3914 : :
3915 : : // Only initialize the Peer::TxRelay m_relay_txs data structure if:
3916 : : // - this isn't an outbound block-relay-only connection, and
3917 : : // - this isn't an outbound feeler connection, and
3918 : : // - fRelay=true (the peer wishes to receive transaction announcements)
3919 : : // or we're offering NODE_BLOOM to this peer. NODE_BLOOM means that
3920 : : // the peer may turn on transaction relay later.
3921 [ + - ]: 2 : if (!pfrom.IsBlockOnlyConn() &&
3922 [ + - + - : 2 : !pfrom.IsFeelerConn() &&
- + ]
3923 [ # # ]: 0 : (fRelay || (peer.m_our_services & NODE_BLOOM))) {
3924 [ + - ]: 2 : auto* const tx_relay = peer.SetTxRelay();
3925 : 2 : {
3926 [ + - ]: 2 : LOCK(tx_relay->m_bloom_filter_mutex);
3927 [ + - ]: 2 : tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message
3928 : 2 : }
3929 [ + - ]: 2 : if (fRelay) pfrom.m_relays_txs = true;
3930 : : }
3931 : :
3932 [ + - ]: 2 : const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)};
3933 [ + - + - : 2 : LogDebug(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, %s%s",
- + - - +
- + - + -
+ - + - +
- ]
3934 : : cleanSubVer.empty() ? "<no user agent>" : cleanSubVer, pfrom.nVersion,
3935 : : starting_height, addrMe.ToStringAddrPort(), fRelay, pfrom.LogPeer(),
3936 : : (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : ""));
3937 : :
3938 [ - + ]: 2 : if (pfrom.IsPrivateBroadcastConn()) {
3939 [ # # ]: 0 : if (fRelay) {
3940 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::VERACK);
3941 : : } else {
3942 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "Disconnecting: does not support transaction relay (connected in vain), %s",
# # # # ]
3943 : : pfrom.LogPeer());
3944 : 0 : pfrom.fDisconnect = true;
3945 : : }
3946 : 0 : return;
3947 : : }
3948 : :
3949 [ + - ]: 2 : if (greatest_common_version >= WTXID_RELAY_VERSION) {
3950 [ + - + - ]: 2 : MakeAndPushMessage(pfrom, NetMsgType::WTXIDRELAY);
3951 : : }
3952 : :
3953 : : // Signal ADDRv2 support (BIP155).
3954 : 2 : if (greatest_common_version >= 70016) {
3955 : : // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some
3956 : : // implementations reject messages they don't know. As a courtesy, don't send
3957 : : // it to nodes with a version before 70016, as no software is known to support
3958 : : // BIP155 that doesn't announce at least that protocol version number.
3959 [ + - + - ]: 2 : MakeAndPushMessage(pfrom, NetMsgType::SENDADDRV2);
3960 : : }
3961 : :
3962 [ - + ]: 2 : if (greatest_common_version >= WTXID_RELAY_VERSION && m_txreconciliation) {
3963 : : // Per BIP-330, we announce txreconciliation support if:
3964 : : // - protocol version per the peer's VERSION message supports WTXID_RELAY;
3965 : : // - transaction relay is supported per the peer's VERSION message
3966 : : // - this is not a block-relay-only connection and not a feeler
3967 : : // - this is not an addr fetch connection;
3968 : : // - we are not in -blocksonly mode.
3969 [ # # ]: 0 : const auto* tx_relay = peer.GetTxRelay();
3970 [ # # # # : 0 : if (tx_relay && WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs) &&
# # ]
3971 [ # # # # : 0 : !pfrom.IsAddrFetchConn() && !m_opts.ignore_incoming_txs) {
# # ]
3972 [ # # ]: 0 : const uint64_t recon_salt = m_txreconciliation->PreRegisterPeer(pfrom.GetId());
3973 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::SENDTXRCNCL,
3974 : : TXRECONCILIATION_VERSION, recon_salt);
3975 : : }
3976 : : }
3977 : :
3978 : 2 : if (greatest_common_version >= FEATURE_VERSION) {
3979 : : // announce supported features
3980 : : // MakeAndPushFeature(pfrom, NetMsgFeature::FOO, uint32_t{1});
3981 : : }
3982 : :
3983 : : // If we have too many tx-relaying inbound peers, attempt to evict an existing one.
3984 : : // Only if this fails, disconnect this peer.
3985 [ + - + - ]: 2 : if (MaybeDisconnectForTxRelayCapacity(pfrom, msg_type, /*protect_peer=*/pfrom.GetId())) return;
3986 [ + - + - ]: 2 : MakeAndPushMessage(pfrom, NetMsgType::VERACK);
3987 : :
3988 : : // Potentially mark this peer as a preferred download peer.
3989 : 2 : {
3990 [ + - ]: 2 : LOCK(cs_main);
3991 : 2 : CNodeState* state = State(pfrom.GetId());
3992 [ - + - - : 2 : state->fPreferredDownload = (!pfrom.IsInboundConn() || pfrom.HasPermission(NetPermissionFlags::NoBan)) && !pfrom.IsAddrFetchConn() && CanServeBlocks(peer);
+ - - + ]
3993 [ + - ]: 2 : m_num_preferred_download_peers += state->fPreferredDownload;
3994 : 2 : }
3995 : :
3996 : : // Attempt to initialize address relay for outbound peers and use result
3997 : : // to decide whether to send GETADDR, so that we don't send it to
3998 : : // inbound, feelers, or outbound block-relay-only peers.
3999 : 2 : bool send_getaddr{false};
4000 [ + - ]: 2 : if (!pfrom.IsInboundConn()) {
4001 [ + - ]: 2 : send_getaddr = SetupAddressRelay(pfrom, peer);
4002 : : }
4003 [ + - ]: 2 : if (send_getaddr) {
4004 : : // Do a one-time address fetch to help populate/update our addrman.
4005 : : // If we're starting up for the first time, our addrman may be pretty
4006 : : // empty, so this mechanism is important to help us connect to the network.
4007 : : // We skip this for block-relay-only peers. We want to avoid
4008 : : // potentially leaking addr information and we do not want to
4009 : : // indicate to the peer that we will participate in addr relay.
4010 [ + - + - ]: 2 : MakeAndPushMessage(pfrom, NetMsgType::GETADDR);
4011 : 2 : peer.m_getaddr_sent = true;
4012 : : // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response
4013 : : // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
4014 : 2 : peer.m_addr_token_bucket += MAX_ADDR_TO_SEND;
4015 : : }
4016 : :
4017 [ + - ]: 2 : if (!pfrom.IsInboundConn()) {
4018 : : // For non-inbound connections, we update the addrman to record
4019 : : // connection success so that addrman will have an up-to-date
4020 : : // notion of which peers are online and available.
4021 : : //
4022 : : // While we strive to not leak information about block-relay-only
4023 : : // connections via the addrman, not moving an address to the tried
4024 : : // table is also potentially detrimental because new-table entries
4025 : : // are subject to eviction in the event of addrman collisions. We
4026 : : // mitigate the information-leak by never calling
4027 : : // AddrMan::Connected() on block-relay-only peers; see
4028 : : // FinalizeNode().
4029 : : //
4030 : : // This moves an address from New to Tried table in Addrman,
4031 : : // resolves tried-table collisions, etc.
4032 [ + - ]: 2 : m_addrman.Good(pfrom.addr);
4033 : : }
4034 : :
4035 : 2 : peer.m_time_offset = NodeSeconds{std::chrono::seconds{nTime}} - Now<NodeSeconds>();
4036 [ + - ]: 2 : if (!pfrom.IsInboundConn()) {
4037 : : // Don't use timedata samples from inbound peers to make it
4038 : : // harder for others to create false warnings about our clock being out of sync.
4039 [ + - ]: 2 : m_outbound_time_offsets.Add(peer.m_time_offset);
4040 [ + - ]: 2 : m_outbound_time_offsets.WarnIfOutOfSync();
4041 : : }
4042 : :
4043 : : // If the peer is old enough to have the old alert system, send it the final alert.
4044 [ - + ]: 2 : if (greatest_common_version <= 70012) {
4045 : 0 : constexpr auto finalAlert{"60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"_hex};
4046 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, "alert", finalAlert);
4047 : : }
4048 : :
4049 : : // Feeler connections exist only to verify if address is online.
4050 [ - + ]: 2 : if (pfrom.IsFeelerConn()) {
4051 [ # # # # : 0 : LogDebug(BCLog::NET, "feeler connection completed, %s", pfrom.DisconnectMsg());
# # # # ]
4052 : 0 : pfrom.fDisconnect = true;
4053 : : }
4054 : 2 : return;
4055 : 3 : }
4056 : :
4057 [ - + ]: 2 : if (pfrom.nVersion == 0) {
4058 : : // Must have a version message before anything else
4059 [ # # # # : 0 : LogDebug(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
# # ]
4060 : 0 : return;
4061 : : }
4062 : :
4063 [ + - ]: 2 : if (msg_type == NetMsgType::VERACK) {
4064 [ - + ]: 2 : if (pfrom.fSuccessfullyConnected) {
4065 [ # # ]: 0 : LogDebug(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId());
4066 : 0 : return;
4067 : : }
4068 : :
4069 : 4 : auto new_peer_msg = [&]() {
4070 : 2 : const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)};
4071 : 2 : return strprintf("New %s peer connected: transport: %s, version: %d, %s%s",
4072 [ + - ]: 4 : pfrom.ConnectionTypeAsString(),
4073 [ + - ]: 4 : TransportTypeAsString(pfrom.m_transport->GetInfo().transport_type),
4074 [ + - ]: 4 : pfrom.nVersion.load(), pfrom.LogPeer(),
4075 [ - + + - ]: 6 : (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : ""));
4076 : 2 : };
4077 : :
4078 : : // Log successful connections unconditionally for outbound, but not for inbound as those
4079 : : // can be triggered by an attacker at high rate.
4080 [ - + ]: 2 : if (pfrom.IsInboundConn()) {
4081 [ # # # # ]: 0 : LogDebug(BCLog::NET, "%s", new_peer_msg());
4082 : : } else {
4083 [ + - ]: 2 : LogInfo("%s", new_peer_msg());
4084 : : }
4085 : :
4086 [ + - ]: 2 : if (auto tx_relay = peer.GetTxRelay()) {
4087 : : // `TxRelay::m_tx_inventory_to_send` must be empty before the
4088 : : // version handshake is completed as
4089 : : // `TxRelay::m_next_inv_send_time` is first initialised in
4090 : : // `SendMessages` after the verack is received. Any transactions
4091 : : // received during the version handshake would otherwise
4092 : : // immediately be advertised without random delay, potentially
4093 : : // leaking the time of arrival to a spy.
4094 [ + - - + : 4 : Assume(WITH_LOCK(
+ - ]
4095 : : tx_relay->m_tx_inventory_mutex,
4096 : : return tx_relay->m_tx_inventory_to_send.empty() &&
4097 : : tx_relay->m_next_inv_send_time == 0s));
4098 : : }
4099 : :
4100 [ - + ]: 2 : if (pfrom.IsPrivateBroadcastConn()) {
4101 : 0 : pfrom.fSuccessfullyConnected = true;
4102 : : // The peer may intend to later send us NetMsgType::FEEFILTER limiting
4103 : : // cheap transactions, but we don't wait for that and thus we may send
4104 : : // them a transaction below their threshold. This is ok because this
4105 : : // relay logic is designed to work even in cases when the peer drops
4106 : : // the transaction (due to it being too cheap, or for other reasons).
4107 : 0 : PushPrivateBroadcastTx(pfrom);
4108 : 0 : return;
4109 : : }
4110 : :
4111 [ + - ]: 2 : if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) {
4112 : : // Tell our peer we are willing to provide version 2 cmpctblocks.
4113 : : // However, we do not request new block announcements using
4114 : : // cmpctblock messages.
4115 : : // We send this to non-NODE NETWORK peers as well, because
4116 : : // they may wish to request compact blocks from us
4117 [ + - ]: 4 : MakeAndPushMessage(pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION);
4118 : : }
4119 : :
4120 [ - + ]: 2 : if (m_txreconciliation) {
4121 [ # # # # ]: 0 : if (!peer.m_wtxid_relay || !m_txreconciliation->IsPeerRegistered(pfrom.GetId())) {
4122 : : // We could have optimistically pre-registered/registered the peer. In that case,
4123 : : // we should forget about the reconciliation state here if this wasn't followed
4124 : : // by WTXIDRELAY (since WTXIDRELAY can't be announced later).
4125 : 0 : m_txreconciliation->ForgetPeer(pfrom.GetId());
4126 : : }
4127 : : }
4128 : :
4129 : 2 : {
4130 [ + - ]: 2 : LOCK2(::cs_main, m_tx_download_mutex);
4131 : 2 : const CNodeState* state = State(pfrom.GetId());
4132 : 2 : m_txdownloadman.ConnectedPeer(pfrom.GetId(), node::TxDownloadConnectionInfo {
4133 [ + - ]: 2 : .m_preferred = state->fPreferredDownload,
4134 : 2 : .m_relay_permissions = pfrom.HasPermission(NetPermissionFlags::Relay),
4135 [ + - ]: 2 : .m_wtxid_relay = peer.m_wtxid_relay,
4136 : : });
4137 [ + - ]: 2 : }
4138 : :
4139 : 2 : pfrom.fSuccessfullyConnected = true;
4140 : 2 : return;
4141 : : }
4142 : :
4143 [ # # ]: 0 : if (msg_type == NetMsgType::SENDHEADERS) {
4144 : 0 : peer.m_prefers_headers = true;
4145 : 0 : return;
4146 : : }
4147 : :
4148 [ # # ]: 0 : if (msg_type == NetMsgType::SENDCMPCT) {
4149 : 0 : uint8_t sendcmpct_hb{0};
4150 : 0 : uint64_t sendcmpct_version{0};
4151 : 0 : vRecv >> sendcmpct_hb >> sendcmpct_version;
4152 : :
4153 : : // BIP152: the first integer is interpreted as a boolean and MUST have a
4154 : : // value of either 1 or 0.
4155 [ # # ]: 0 : if (sendcmpct_hb > 1) {
4156 [ # # ]: 0 : Misbehaving(peer, "invalid sendcmpct announce field");
4157 : 0 : return;
4158 : : }
4159 : :
4160 : : // Only support compact block relay with witnesses
4161 [ # # ]: 0 : if (sendcmpct_version != CMPCTBLOCKS_VERSION) return;
4162 : :
4163 : 0 : LOCK(cs_main);
4164 : 0 : CNodeState* nodestate = State(pfrom.GetId());
4165 : 0 : nodestate->m_provides_cmpctblocks = true;
4166 : 0 : nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
4167 : : // save whether peer selects us as BIP152 high-bandwidth peer
4168 : : // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth)
4169 [ # # ]: 0 : pfrom.m_bip152_highbandwidth_from = sendcmpct_hb;
4170 [ # # ]: 0 : return;
4171 : 0 : }
4172 : :
4173 : : // BIP339 defines feature negotiation of wtxidrelay, which must happen between
4174 : : // VERSION and VERACK to avoid relay problems from switching after a connection is up.
4175 [ # # ]: 0 : if (msg_type == NetMsgType::WTXIDRELAY) {
4176 [ # # ]: 0 : if (pfrom.fSuccessfullyConnected) {
4177 : : // Disconnect peers that send a wtxidrelay message after VERACK.
4178 [ # # # # ]: 0 : LogDebug(BCLog::NET, "wtxidrelay received after verack, %s", pfrom.DisconnectMsg());
4179 : 0 : pfrom.fDisconnect = true;
4180 : 0 : return;
4181 : : }
4182 [ # # ]: 0 : if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) {
4183 [ # # ]: 0 : if (!peer.m_wtxid_relay) {
4184 : 0 : peer.m_wtxid_relay = true;
4185 : 0 : m_wtxid_relay_peers++;
4186 : : } else {
4187 [ # # ]: 0 : LogDebug(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId());
4188 : : }
4189 : : } else {
4190 [ # # ]: 0 : LogDebug(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId());
4191 : : }
4192 : 0 : return;
4193 : : }
4194 : :
4195 : : // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen
4196 : : // between VERSION and VERACK.
4197 [ # # ]: 0 : if (msg_type == NetMsgType::SENDADDRV2) {
4198 [ # # ]: 0 : if (pfrom.fSuccessfullyConnected) {
4199 : : // Disconnect peers that send a SENDADDRV2 message after VERACK.
4200 [ # # # # ]: 0 : LogDebug(BCLog::NET, "sendaddrv2 received after verack, %s", pfrom.DisconnectMsg());
4201 : 0 : pfrom.fDisconnect = true;
4202 : 0 : return;
4203 : : }
4204 : 0 : peer.m_wants_addrv2 = true;
4205 : 0 : return;
4206 : : }
4207 : :
4208 [ # # ]: 0 : if (msg_type == NetMsgType::FEATURE) {
4209 [ # # ]: 0 : if (pfrom.fSuccessfullyConnected) {
4210 : : // Disconnect peers that send a FEATURE message after VERACK.
4211 [ # # # # ]: 0 : LogDebug(BCLog::NET, "feature received after verack, %s", pfrom.DisconnectMsg());
4212 : 0 : pfrom.fDisconnect = true;
4213 : 0 : return;
4214 [ # # ]: 0 : } else if (pfrom.GetCommonVersion() < FEATURE_VERSION) {
4215 : : // Disconnect peers that send a FEATURE message without valid version negotiation.
4216 [ # # # # ]: 0 : LogDebug(BCLog::NET, "feature received with incompatible version %d, %s", pfrom.GetCommonVersion(), pfrom.DisconnectMsg());
4217 : 0 : pfrom.fDisconnect = true;
4218 : 0 : return;
4219 : : }
4220 : :
4221 [ # # ]: 0 : std::string feature_id;
4222 : 0 : DataStream feature_data;
4223 : 0 : try {
4224 [ # # ]: 0 : vRecv >> LIMITED_STRING(feature_id, MAX_FEATUREID_LENGTH);
4225 : 0 : std::vector<unsigned char> feature_data_vec;
4226 [ # # ]: 0 : vRecv >> LIMITED_VECTOR(feature_data_vec, MAX_FEATUREDATA_LENGTH);
4227 [ # # # # ]: 0 : feature_data = DataStream(feature_data_vec);
4228 [ # # ]: 0 : } catch (const std::exception&) {
4229 : 0 : feature_id.clear(); // use empty feature_id as error indicator
4230 : 0 : }
4231 [ # # # # : 0 : if (feature_id.size() < 4 || !vRecv.empty()) {
# # ]
4232 [ # # # # : 0 : LogDebug(BCLog::NET, "invalid feature payload, %s", pfrom.DisconnectMsg());
# # # # ]
4233 : 0 : pfrom.fDisconnect = true;
4234 : 0 : return;
4235 : : }
4236 : :
4237 : : // if (feature_id == NetMsgFeature::FOO) {
4238 : : // ...
4239 : : // return;
4240 : : // }
4241 : :
4242 : : // ignore unknown feature_id
4243 [ # # # # : 0 : LogDebug(BCLog::NET, "unknown feature advertised: %s", SanitizeString(feature_id));
# # # # #
# ]
4244 : 0 : return;
4245 : 0 : }
4246 : :
4247 : : // Received from a peer demonstrating readiness to announce transactions via reconciliations.
4248 : : // This feature negotiation must happen between VERSION and VERACK to avoid relay problems
4249 : : // from switching announcement protocols after the connection is up.
4250 [ # # ]: 0 : if (msg_type == NetMsgType::SENDTXRCNCL) {
4251 [ # # ]: 0 : if (!m_txreconciliation) {
4252 [ # # ]: 0 : LogDebug(BCLog::NET, "sendtxrcncl from peer=%d ignored, as our node does not have txreconciliation enabled\n", pfrom.GetId());
4253 : 0 : return;
4254 : : }
4255 : :
4256 [ # # ]: 0 : if (pfrom.fSuccessfullyConnected) {
4257 [ # # # # ]: 0 : LogDebug(BCLog::NET, "sendtxrcncl received after verack, %s", pfrom.DisconnectMsg());
4258 : 0 : pfrom.fDisconnect = true;
4259 : 0 : return;
4260 : : }
4261 : :
4262 : : // Peer must not offer us reconciliations if we specified no tx relay support in VERSION.
4263 [ # # ]: 0 : if (RejectIncomingTxs(pfrom)) {
4264 [ # # # # ]: 0 : LogDebug(BCLog::NET, "sendtxrcncl received to which we indicated no tx relay, %s", pfrom.DisconnectMsg());
4265 : 0 : pfrom.fDisconnect = true;
4266 : 0 : return;
4267 : : }
4268 : :
4269 : : // Peer must not offer us reconciliations if they specified no tx relay support in VERSION.
4270 : : // This flag might also be false in other cases, but the RejectIncomingTxs check above
4271 : : // eliminates them, so that this flag fully represents what we are looking for.
4272 : 0 : const auto* tx_relay = peer.GetTxRelay();
4273 [ # # # # : 0 : if (!tx_relay || !WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs)) {
# # ]
4274 [ # # # # ]: 0 : LogDebug(BCLog::NET, "sendtxrcncl received which indicated no tx relay to us, %s", pfrom.DisconnectMsg());
4275 : 0 : pfrom.fDisconnect = true;
4276 : 0 : return;
4277 : : }
4278 : :
4279 : 0 : uint32_t peer_txreconcl_version;
4280 : 0 : uint64_t remote_salt;
4281 : 0 : vRecv >> peer_txreconcl_version >> remote_salt;
4282 : :
4283 : 0 : const ReconciliationRegisterResult result = m_txreconciliation->RegisterPeer(pfrom.GetId(), pfrom.IsInboundConn(),
4284 : : peer_txreconcl_version, remote_salt);
4285 [ # # # # ]: 0 : switch (result) {
4286 : 0 : case ReconciliationRegisterResult::NOT_FOUND:
4287 [ # # ]: 0 : LogDebug(BCLog::NET, "Ignore unexpected txreconciliation signal from peer=%d\n", pfrom.GetId());
4288 : : break;
4289 : : case ReconciliationRegisterResult::SUCCESS:
4290 : : break;
4291 : 0 : case ReconciliationRegisterResult::ALREADY_REGISTERED:
4292 [ # # # # ]: 0 : LogDebug(BCLog::NET, "txreconciliation protocol violation (sendtxrcncl received from already registered peer), %s", pfrom.DisconnectMsg());
4293 : 0 : pfrom.fDisconnect = true;
4294 : 0 : return;
4295 : 0 : case ReconciliationRegisterResult::PROTOCOL_VIOLATION:
4296 [ # # # # ]: 0 : LogDebug(BCLog::NET, "txreconciliation protocol violation, %s", pfrom.DisconnectMsg());
4297 : 0 : pfrom.fDisconnect = true;
4298 : 0 : return;
4299 : : }
4300 : 0 : return;
4301 : : }
4302 : :
4303 [ # # ]: 0 : if (!pfrom.fSuccessfullyConnected) {
4304 [ # # # # : 0 : LogDebug(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
# # ]
4305 : 0 : return;
4306 : : }
4307 : :
4308 [ # # ]: 0 : if (pfrom.IsPrivateBroadcastConn()) {
4309 [ # # # # ]: 0 : if (msg_type != NetMsgType::PONG && msg_type != NetMsgType::GETDATA) {
4310 [ # # # # ]: 0 : LogDebug(BCLog::PRIVBROADCAST, "Ignoring incoming message '%s', %s", msg_type, pfrom.LogPeer());
4311 : 0 : return;
4312 : : }
4313 : : }
4314 : :
4315 [ # # # # ]: 0 : if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
4316 : 0 : const auto ser_params{
4317 [ # # ]: 0 : msg_type == NetMsgType::ADDRV2 ?
4318 : : // Set V2 param so that the CNetAddr and CAddress
4319 : : // unserialize methods know that an address in v2 format is coming.
4320 : : CAddress::V2_NETWORK :
4321 : : CAddress::V1_NETWORK,
4322 : : };
4323 : :
4324 : 0 : std::vector<CAddress> vAddr;
4325 [ # # ]: 0 : vRecv >> ser_params(vAddr);
4326 [ # # # # ]: 0 : ProcessAddrs(msg_type, pfrom, peer, std::move(vAddr), interruptMsgProc);
4327 : 0 : return;
4328 : 0 : }
4329 : :
4330 [ # # ]: 0 : if (msg_type == NetMsgType::INV) {
4331 : 0 : std::vector<CInv> vInv;
4332 [ # # ]: 0 : vRecv >> vInv;
4333 [ # # # # ]: 0 : if (vInv.size() > MAX_INV_SZ)
4334 : : {
4335 [ # # # # ]: 0 : Misbehaving(peer, strprintf("inv message size = %u", vInv.size()));
4336 : 0 : return;
4337 : : }
4338 : :
4339 : 0 : const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
4340 : :
4341 [ # # # # ]: 0 : LOCK2(cs_main, m_tx_download_mutex);
4342 : :
4343 : 0 : const auto current_time{GetTime<std::chrono::microseconds>()};
4344 : 0 : uint256* best_block{nullptr};
4345 : :
4346 [ # # ]: 0 : for (CInv& inv : vInv) {
4347 [ # # ]: 0 : if (interruptMsgProc) return;
4348 : :
4349 : : // Ignore INVs that don't match wtxidrelay setting.
4350 : : // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting.
4351 : : // This is fine as no INV messages are involved in that process.
4352 [ # # ]: 0 : if (peer.m_wtxid_relay) {
4353 [ # # ]: 0 : if (inv.IsMsgTx()) continue;
4354 : : } else {
4355 [ # # ]: 0 : if (inv.IsMsgWtx()) continue;
4356 : : }
4357 : :
4358 [ # # ]: 0 : if (inv.IsMsgBlk()) {
4359 [ # # ]: 0 : const bool fAlreadyHave = AlreadyHaveBlock(inv.hash);
4360 [ # # # # : 0 : LogDebug(BCLog::NET, "got inv: %s %s peer=%d", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
# # # # #
# ]
4361 : :
4362 [ # # ]: 0 : UpdateBlockAvailability(pfrom.GetId(), inv.hash);
4363 [ # # # # : 0 : if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() && !IsBlockRequested(inv.hash)) {
# # ]
4364 : : // Headers-first is the primary method of announcement on
4365 : : // the network. If a node fell back to sending blocks by
4366 : : // inv, it may be for a re-org, or because we haven't
4367 : : // completed initial headers sync. The final block hash
4368 : : // provided should be the highest, so send a getheaders and
4369 : : // then fetch the blocks we need to catch up.
4370 : : best_block = &inv.hash;
4371 : : }
4372 [ # # ]: 0 : } else if (inv.IsGenTxMsg()) {
4373 [ # # ]: 0 : if (reject_tx_invs) {
4374 [ # # # # : 0 : LogDebug(BCLog::NET, "transaction (%s) inv sent in violation of protocol, %s", inv.hash.ToString(), pfrom.DisconnectMsg());
# # # # #
# ]
4375 : 0 : pfrom.fDisconnect = true;
4376 : 0 : return;
4377 : : }
4378 [ # # ]: 0 : const GenTxid gtxid = ToGenTxid(inv);
4379 [ # # ]: 0 : AddKnownTx(peer, inv.hash);
4380 : :
4381 [ # # ]: 0 : if (!m_chainman.IsInitialBlockDownload()) {
4382 [ # # ]: 0 : const bool fAlreadyHave{m_txdownloadman.AddTxAnnouncement(pfrom.GetId(), gtxid, current_time)};
4383 [ # # # # : 0 : LogDebug(BCLog::NET, "got inv: %s %s peer=%d", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
# # # # #
# ]
4384 : : }
4385 : : } else {
4386 [ # # # # : 0 : LogDebug(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId());
# # # # ]
4387 : : }
4388 : : }
4389 : :
4390 [ # # ]: 0 : if (best_block != nullptr) {
4391 : : // If we haven't started initial headers-sync with this peer, then
4392 : : // consider sending a getheaders now. On initial startup, there's a
4393 : : // reliability vs bandwidth tradeoff, where we are only trying to do
4394 : : // initial headers sync with one peer at a time, with a long
4395 : : // timeout (at which point, if the sync hasn't completed, we will
4396 : : // disconnect the peer and then choose another). In the meantime,
4397 : : // as new blocks are found, we are willing to add one new peer per
4398 : : // block to sync with as well, to sync quicker in the case where
4399 : : // our initial peer is unresponsive (but less bandwidth than we'd
4400 : : // use if we turned on sync with all peers).
4401 [ # # ]: 0 : CNodeState& state{*Assert(State(pfrom.GetId()))};
4402 [ # # # # : 0 : if (state.fSyncStarted || (!peer.m_inv_triggered_getheaders_before_sync && *best_block != m_last_block_inv_triggering_headers_sync)) {
# # ]
4403 [ # # # # : 0 : if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), peer)) {
# # ]
4404 [ # # # # : 0 : LogDebug(BCLog::NET, "getheaders (%d) %s to peer=%d\n",
# # # # ]
4405 : : m_chainman.m_best_header->nHeight, best_block->ToString(),
4406 : : pfrom.GetId());
4407 : : }
4408 [ # # ]: 0 : if (!state.fSyncStarted) {
4409 : 0 : peer.m_inv_triggered_getheaders_before_sync = true;
4410 : : // Update the last block hash that triggered a new headers
4411 : : // sync, so that we don't turn on headers sync with more
4412 : : // than 1 new peer every new block.
4413 : 0 : m_last_block_inv_triggering_headers_sync = *best_block;
4414 : : }
4415 : : }
4416 : : }
4417 : :
4418 : 0 : return;
4419 [ # # ]: 0 : }
4420 : :
4421 [ # # ]: 0 : if (msg_type == NetMsgType::GETDATA) {
4422 : 0 : std::vector<CInv> vInv;
4423 [ # # ]: 0 : vRecv >> vInv;
4424 [ # # # # ]: 0 : if (vInv.size() > MAX_INV_SZ)
4425 : : {
4426 [ # # # # ]: 0 : Misbehaving(peer, strprintf("getdata message size = %u", vInv.size()));
4427 : 0 : return;
4428 : : }
4429 : :
4430 [ # # # # : 0 : LogDebug(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId());
# # # # ]
4431 : :
4432 [ # # # # ]: 0 : if (vInv.size() > 0) {
4433 [ # # # # : 0 : LogDebug(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
# # # # ]
4434 : : }
4435 : :
4436 [ # # ]: 0 : if (pfrom.IsPrivateBroadcastConn()) {
4437 [ # # ]: 0 : const auto pushed_tx_opt{m_tx_for_private_broadcast.GetTxForNode(pfrom.GetId())};
4438 [ # # ]: 0 : if (!pushed_tx_opt) {
4439 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "Disconnecting: got GETDATA without sending an INV, %s",
# # # # ]
4440 : : pfrom.LogPeer());
4441 : 0 : pfrom.fDisconnect = true;
4442 : 0 : return;
4443 : : }
4444 : :
4445 [ # # ]: 0 : const CTransactionRef& pushed_tx{*pushed_tx_opt};
4446 : :
4447 : : // The GETDATA request must contain exactly one inv and it must be for the transaction
4448 : : // that we INVed to the peer earlier.
4449 [ # # # # : 0 : if (vInv.size() == 1 && vInv[0].IsMsgTx() && vInv[0].hash == pushed_tx->GetHash().ToUint256()) {
# # # # ]
4450 : :
4451 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::TX, TX_WITH_WITNESS(*pushed_tx));
4452 : :
4453 : 0 : peer.m_ping_queued = true; // Ensure a ping will be sent: mimic a request via RPC.
4454 [ # # ]: 0 : MaybeSendPing(pfrom, peer, NodeClock::now());
4455 : : } else {
4456 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "Disconnecting: got an unexpected GETDATA message, %s",
# # # # ]
4457 : : pfrom.LogPeer());
4458 : 0 : pfrom.fDisconnect = true;
4459 : : }
4460 : 0 : return;
4461 : 0 : }
4462 : :
4463 : 0 : {
4464 [ # # ]: 0 : LOCK(peer.m_getdata_requests_mutex);
4465 [ # # ]: 0 : peer.m_getdata_requests.insert(peer.m_getdata_requests.end(), vInv.begin(), vInv.end());
4466 [ # # ]: 0 : ProcessGetData(pfrom, peer, interruptMsgProc);
4467 : 0 : }
4468 : :
4469 : 0 : return;
4470 : 0 : }
4471 : :
4472 [ # # ]: 0 : if (msg_type == NetMsgType::GETBLOCKS) {
4473 : 0 : CBlockLocator locator;
4474 : 0 : uint256 hashStop;
4475 [ # # # # ]: 0 : vRecv >> locator >> hashStop;
4476 : :
4477 [ # # # # ]: 0 : if (locator.vHave.size() > MAX_LOCATOR_SZ) {
4478 [ # # # # : 0 : LogDebug(BCLog::NET, "getblocks locator size %lld > %d, %s", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.DisconnectMsg());
# # # # ]
4479 : 0 : pfrom.fDisconnect = true;
4480 : 0 : return;
4481 : : }
4482 : :
4483 : : // We might have announced the currently-being-connected tip using a
4484 : : // compact block, which resulted in the peer sending a getblocks
4485 : : // request, which we would otherwise respond to without the new block.
4486 : : // To avoid this situation we simply verify that we are on our best
4487 : : // known chain now. This is super overkill, but we handle it better
4488 : : // for getheaders requests, and there are no known nodes which support
4489 : : // compact blocks but still use getblocks to request blocks.
4490 : 0 : {
4491 : 0 : std::shared_ptr<const CBlock> a_recent_block;
4492 : 0 : {
4493 [ # # ]: 0 : LOCK(m_most_recent_block_mutex);
4494 [ # # ]: 0 : a_recent_block = m_most_recent_block;
4495 : 0 : }
4496 [ # # ]: 0 : BlockValidationState state;
4497 [ # # # # : 0 : if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
# # # # #
# ]
4498 [ # # # # : 0 : LogDebug(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
# # # # ]
4499 : : }
4500 [ # # ]: 0 : }
4501 : :
4502 [ # # ]: 0 : LOCK(cs_main);
4503 : :
4504 : : // Find the last block the caller has in the main chain
4505 [ # # # # ]: 0 : const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
4506 : :
4507 : : // Send the rest of the chain
4508 [ # # ]: 0 : if (pindex)
4509 [ # # ]: 0 : pindex = m_chainman.ActiveChain().Next(*pindex);
4510 : 0 : int nLimit = 500;
4511 [ # # # # : 0 : LogDebug(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom.GetId());
# # # # #
# # # #
# ]
4512 [ # # # # ]: 0 : for (; pindex; pindex = m_chainman.ActiveChain().Next(*pindex))
4513 : : {
4514 [ # # ]: 0 : if (pindex->GetBlockHash() == hashStop)
4515 : : {
4516 [ # # # # : 0 : LogDebug(BCLog::NET, " getblocks stopping at %d %s", pindex->nHeight, pindex->GetBlockHash().ToString());
# # # # ]
4517 : : break;
4518 : : }
4519 : : // If pruning, don't inv blocks unless we have on disk and are likely to still have
4520 : : // for some reasonable time window (1 hour) that block relay might require.
4521 : 0 : const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
4522 [ # # # # : 0 : if (m_chainman.m_blockman.IsPruneMode() && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave)) {
# # # # #
# ]
4523 [ # # # # : 0 : LogDebug(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
# # # # ]
4524 : : break;
4525 : : }
4526 [ # # # # : 0 : WITH_LOCK(peer.m_block_inv_mutex, peer.m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
# # ]
4527 [ # # ]: 0 : if (--nLimit <= 0) {
4528 : : // When this block is requested, we'll send an inv that'll
4529 : : // trigger the peer to getblocks the next batch of inventory.
4530 [ # # # # : 0 : LogDebug(BCLog::NET, " getblocks stopping at limit %d %s", pindex->nHeight, pindex->GetBlockHash().ToString());
# # # # ]
4531 [ # # # # ]: 0 : WITH_LOCK(peer.m_block_inv_mutex, {peer.m_continuation_block = pindex->GetBlockHash();});
4532 : : break;
4533 : : }
4534 : : }
4535 [ # # ]: 0 : return;
4536 : 0 : }
4537 : :
4538 [ # # ]: 0 : if (msg_type == NetMsgType::GETBLOCKTXN) {
4539 : 0 : BlockTransactionsRequest req;
4540 [ # # ]: 0 : vRecv >> req;
4541 : :
4542 : : // No legitimate reason to send indexes empty
4543 [ # # ]: 0 : if (req.indexes.empty()) {
4544 [ # # # # : 0 : LogDebug(BCLog::NET, "getblocktxn received with no transaction indexes, %s", pfrom.DisconnectMsg());
# # # # ]
4545 : 0 : pfrom.fDisconnect = true;
4546 : 0 : return;
4547 : : }
4548 : :
4549 : : // Verify differential encoding invariant: indexes must be strictly increasing
4550 : : // DifferenceFormatter should guarantee this property during deserialization
4551 [ # # # # ]: 0 : for (size_t i = 1; i < req.indexes.size(); ++i) {
4552 : 0 : Assume(req.indexes[i] > req.indexes[i-1]);
4553 : : }
4554 : :
4555 : 0 : std::shared_ptr<const CBlock> recent_block;
4556 : 0 : {
4557 [ # # ]: 0 : LOCK(m_most_recent_block_mutex);
4558 [ # # ]: 0 : if (m_most_recent_block_hash == req.blockhash)
4559 : 0 : recent_block = m_most_recent_block;
4560 : : // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion
4561 : 0 : }
4562 [ # # ]: 0 : if (recent_block) {
4563 [ # # ]: 0 : SendBlockTransactions(pfrom, peer, *recent_block, req);
4564 : : return;
4565 : : }
4566 : :
4567 : 0 : FlatFilePos block_pos{};
4568 : 0 : {
4569 [ # # ]: 0 : LOCK(cs_main);
4570 : :
4571 [ # # ]: 0 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
4572 [ # # # # ]: 0 : if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4573 [ # # # # : 0 : LogDebug(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId());
# # ]
4574 [ # # ]: 0 : return;
4575 : : }
4576 : :
4577 [ # # # # : 0 : if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
# # ]
4578 : 0 : block_pos = pindex->GetBlockPos();
4579 : : }
4580 : 0 : }
4581 : :
4582 [ # # ]: 0 : if (!block_pos.IsNull()) {
4583 : 0 : CBlock block;
4584 [ # # ]: 0 : const bool ret{m_chainman.m_blockman.ReadBlock(block, block_pos, req.blockhash)};
4585 : : // If height is above MAX_BLOCKTXN_DEPTH then this block cannot get
4586 : : // pruned after we release cs_main above, so this read should never fail.
4587 [ # # ]: 0 : assert(ret);
4588 : :
4589 [ # # ]: 0 : SendBlockTransactions(pfrom, peer, block, req);
4590 : 0 : return;
4591 : 0 : }
4592 : :
4593 : : // If an older block is requested (should never happen in practice,
4594 : : // but can happen in tests) send a block response instead of a
4595 : : // blocktxn response. Sending a full block response instead of a
4596 : : // small blocktxn response is preferable in the case where a peer
4597 : : // might maliciously send lots of getblocktxn requests to trigger
4598 : : // expensive disk reads, because it will require the peer to
4599 : : // actually receive all the data read from disk over the network.
4600 [ # # # # : 0 : LogDebug(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
# # ]
4601 [ # # ]: 0 : CInv inv{MSG_WITNESS_BLOCK, req.blockhash};
4602 [ # # # # ]: 0 : WITH_LOCK(peer.m_getdata_requests_mutex, peer.m_getdata_requests.push_back(inv));
4603 : : // The message processing loop will go around again (without pausing) and we'll respond then
4604 : : return;
4605 : 0 : }
4606 : :
4607 [ # # ]: 0 : if (msg_type == NetMsgType::GETHEADERS) {
4608 : 0 : CBlockLocator locator;
4609 : 0 : uint256 hashStop;
4610 [ # # # # ]: 0 : vRecv >> locator >> hashStop;
4611 : :
4612 [ # # # # ]: 0 : if (locator.vHave.size() > MAX_LOCATOR_SZ) {
4613 [ # # # # : 0 : LogDebug(BCLog::NET, "getheaders locator size %lld > %d, %s", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.DisconnectMsg());
# # # # ]
4614 : 0 : pfrom.fDisconnect = true;
4615 : 0 : return;
4616 : : }
4617 : :
4618 [ # # ]: 0 : if (m_chainman.m_blockman.LoadingBlocks()) {
4619 [ # # # # : 0 : LogDebug(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId());
# # ]
4620 : 0 : return;
4621 : : }
4622 : :
4623 [ # # ]: 0 : LOCK(cs_main);
4624 : :
4625 : : // Don't serve headers from our active chain until our chainwork is at least
4626 : : // the minimum chain work. This prevents us from starting a low-work headers
4627 : : // sync that will inevitably be aborted by our peer.
4628 [ # # # # : 0 : if (m_chainman.ActiveTip() == nullptr ||
# # ]
4629 [ # # # # : 0 : (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && !pfrom.HasPermission(NetPermissionFlags::Download))) {
# # # # ]
4630 [ # # # # : 0 : LogDebug(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId());
# # ]
4631 : : // Just respond with an empty headers message, to tell the peer to
4632 : : // go away but not treat us as unresponsive.
4633 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::HEADERS, std::vector<CBlockHeader>());
4634 : 0 : return;
4635 : : }
4636 : :
4637 : 0 : CNodeState *nodestate = State(pfrom.GetId());
4638 : 0 : const CBlockIndex* pindex = nullptr;
4639 [ # # ]: 0 : if (locator.IsNull())
4640 : : {
4641 : : // If locator is null, return the hashStop block
4642 [ # # ]: 0 : pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
4643 [ # # ]: 0 : if (!pindex) {
4644 : : return;
4645 : : }
4646 [ # # # # ]: 0 : if (!BlockRequestAllowed(*pindex)) {
4647 [ # # # # : 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());
# # ]
4648 : 0 : return;
4649 : : }
4650 : : }
4651 : : else
4652 : : {
4653 : : // Find the last block the caller has in the main chain
4654 [ # # # # ]: 0 : pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
4655 [ # # ]: 0 : if (pindex)
4656 [ # # ]: 0 : pindex = m_chainman.ActiveChain().Next(*pindex);
4657 : : }
4658 : :
4659 : : // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4660 : 0 : std::vector<CBlock> vHeaders;
4661 : 0 : int nLimit = m_opts.max_headers_result;
4662 [ # # # # : 0 : LogDebug(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId());
# # # # #
# # # #
# ]
4663 [ # # # # ]: 0 : for (; pindex; pindex = m_chainman.ActiveChain().Next(*pindex))
4664 : : {
4665 [ # # ]: 0 : vHeaders.emplace_back(pindex->GetBlockHeader());
4666 [ # # # # ]: 0 : if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4667 : : break;
4668 : : }
4669 : : // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR
4670 : : // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty
4671 : : // headers message). In both cases it's safe to update
4672 : : // pindexBestHeaderSent to be our tip.
4673 : : //
4674 : : // It is important that we simply reset the BestHeaderSent value here,
4675 : : // and not max(BestHeaderSent, newHeaderSent). We might have announced
4676 : : // the currently-being-connected tip using a compact block, which
4677 : : // resulted in the peer sending a headers request, which we respond to
4678 : : // without the new block. By resetting the BestHeaderSent, we ensure we
4679 : : // will re-announce the new block via headers (or compact blocks again)
4680 : : // in the SendMessages logic.
4681 [ # # # # : 0 : nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip();
# # ]
4682 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders));
4683 : 0 : return;
4684 : 0 : }
4685 : :
4686 [ # # ]: 0 : if (msg_type == NetMsgType::TX) {
4687 [ # # ]: 0 : if (RejectIncomingTxs(pfrom)) {
4688 [ # # # # ]: 0 : LogDebug(BCLog::NET, "transaction sent in violation of protocol, %s", pfrom.DisconnectMsg());
4689 : 0 : pfrom.fDisconnect = true;
4690 : 0 : return;
4691 : : }
4692 : :
4693 : : // Stop processing the transaction early if we are still in IBD since we don't
4694 : : // have enough information to validate it yet. Sending unsolicited transactions
4695 : : // is not considered a protocol violation, so don't punish the peer.
4696 [ # # ]: 0 : if (m_chainman.IsInitialBlockDownload()) return;
4697 : :
4698 : 0 : CTransactionRef ptx;
4699 [ # # ]: 0 : vRecv >> TX_WITH_WITNESS(ptx);
4700 : :
4701 [ # # ]: 0 : const Txid& txid = ptx->GetHash();
4702 [ # # ]: 0 : const Wtxid& wtxid = ptx->GetWitnessHash();
4703 : :
4704 [ # # ]: 0 : const uint256& hash = peer.m_wtxid_relay ? wtxid.ToUint256() : txid.ToUint256();
4705 [ # # ]: 0 : AddKnownTx(peer, hash);
4706 : :
4707 [ # # # # ]: 0 : if (const auto num_broadcasted{m_tx_for_private_broadcast.Remove(ptx)}) {
4708 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "Received our privately broadcast transaction (txid=%s) from the "
# # # # ]
4709 : : "network from %s; stopping private broadcast attempts",
4710 : : txid.ToString(), pfrom.LogPeer());
4711 [ # # ]: 0 : if (NUM_PRIVATE_BROADCAST_PER_TX > num_broadcasted.value()) {
4712 : : // Not all of the initial NUM_PRIVATE_BROADCAST_PER_TX connections were needed.
4713 : : // Tell CConnman it does not need to start the remaining ones.
4714 [ # # ]: 0 : m_connman.m_private_broadcast.NumToOpenSub(NUM_PRIVATE_BROADCAST_PER_TX - num_broadcasted.value());
4715 : : }
4716 : : }
4717 : :
4718 [ # # # # ]: 0 : LOCK2(cs_main, m_tx_download_mutex);
4719 : :
4720 [ # # # # ]: 0 : const auto& [should_validate, package_to_validate] = m_txdownloadman.ReceivedTx(pfrom.GetId(), ptx);
4721 [ # # ]: 0 : if (!should_validate) {
4722 [ # # ]: 0 : if (pfrom.HasPermission(NetPermissionFlags::ForceRelay)) {
4723 : : // Always relay transactions received from peers with forcerelay
4724 : : // permission, even if they were already in the mempool, allowing
4725 : : // the node to function as a gateway for nodes hidden behind it.
4726 [ # # # # ]: 0 : if (!m_mempool.exists(txid)) {
4727 [ # # # # : 0 : LogInfo("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n",
# # ]
4728 : : txid.ToString(), wtxid.ToString(), pfrom.GetId());
4729 : : } else {
4730 [ # # # # : 0 : LogInfo("Force relaying tx %s (wtxid=%s) from peer=%d\n",
# # ]
4731 : : txid.ToString(), wtxid.ToString(), pfrom.GetId());
4732 [ # # ]: 0 : InitiateTxBroadcastToAll(wtxid);
4733 : : }
4734 : : }
4735 : :
4736 [ # # ]: 0 : if (package_to_validate) {
4737 [ # # # # ]: 0 : const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)};
4738 [ # # # # : 0 : LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(),
# # # # #
# ]
4739 : : package_result.m_state.IsValid() ? "package accepted" : "package rejected");
4740 [ # # # # ]: 0 : ProcessPackageResult(package_to_validate.value(), package_result);
4741 : 0 : }
4742 : 0 : return;
4743 : : }
4744 : :
4745 : : // ReceivedTx should not be telling us to validate the tx and a package.
4746 [ # # ]: 0 : Assume(!package_to_validate.has_value());
4747 : :
4748 [ # # ]: 0 : const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx);
4749 : 0 : const TxValidationState& state = result.m_state;
4750 : :
4751 [ # # ]: 0 : if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
4752 [ # # ]: 0 : ProcessValidTx(pfrom.GetId(), ptx, result.m_replaced_transactions);
4753 : 0 : pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
4754 : : }
4755 [ # # ]: 0 : if (state.IsInvalid()) {
4756 [ # # # # ]: 0 : if (auto package_to_validate{ProcessInvalidTx(pfrom.GetId(), ptx, state, /*first_time_failure=*/true)}) {
4757 [ # # # # ]: 0 : const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)};
4758 [ # # # # : 0 : LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(),
# # # # #
# ]
4759 : : package_result.m_state.IsValid() ? "package accepted" : "package rejected");
4760 [ # # # # ]: 0 : ProcessPackageResult(package_to_validate.value(), package_result);
4761 : 0 : }
4762 : : }
4763 : :
4764 : 0 : return;
4765 [ # # # # : 0 : }
# # ]
4766 : :
4767 [ # # ]: 0 : if (msg_type == NetMsgType::CMPCTBLOCK)
4768 : : {
4769 : : // Ignore cmpctblock received while importing
4770 [ # # ]: 0 : if (m_chainman.m_blockman.LoadingBlocks()) {
4771 [ # # # # ]: 0 : LogDebug(BCLog::CMPCTBLOCK, "%s sent us a compact block even though we are still loading blocks!", pfrom.LogPeer());
4772 : 0 : return;
4773 [ # # ]: 0 : } else if (m_opts.ignore_incoming_txs) {
4774 [ # # # # ]: 0 : LogDebug(BCLog::CMPCTBLOCK, "%s sent us a compact block even though we are blocksonly!", pfrom.LogPeer());
4775 : 0 : return;
4776 : : }
4777 : :
4778 : 0 : {
4779 : 0 : LOCK(cs_main);
4780 : 0 : const CNodeState *nodestate = State(pfrom.GetId());
4781 [ # # ]: 0 : if (!nodestate->m_provides_cmpctblocks) {
4782 [ # # # # : 0 : LogDebug(BCLog::CMPCTBLOCK, "%s sent us a compact block despite never having sent us a SENDCMPCT!", pfrom.LogPeer());
# # # # ]
4783 [ # # ]: 0 : return;
4784 : : }
4785 : 0 : }
4786 : :
4787 : 0 : CBlockHeaderAndShortTxIDs cmpctblock;
4788 [ # # ]: 0 : vRecv >> cmpctblock;
4789 : :
4790 : 0 : bool received_new_header = false;
4791 [ # # ]: 0 : const auto blockhash = cmpctblock.header.GetHash();
4792 : :
4793 : 0 : {
4794 [ # # ]: 0 : LOCK(cs_main);
4795 : :
4796 [ # # ]: 0 : const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock);
4797 [ # # ]: 0 : if (!prev_block) {
4798 : : // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
4799 [ # # ]: 0 : if (!m_chainman.IsInitialBlockDownload()) {
4800 [ # # # # ]: 0 : MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), peer);
4801 : : }
4802 : 0 : return;
4803 [ # # # # : 0 : } else if (prev_block->nChainWork + GetBlockProof(cmpctblock.header) < GetAntiDoSWorkThreshold()) {
# # ]
4804 : : // If we get a low-work header in a compact block, we can ignore it.
4805 [ # # # # : 0 : LogDebug(BCLog::NET, "Ignoring low-work compact block from peer %d\n", pfrom.GetId());
# # ]
4806 : 0 : return;
4807 : : }
4808 : :
4809 [ # # # # ]: 0 : if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) {
4810 : 0 : received_new_header = true;
4811 : : }
4812 : 0 : }
4813 : :
4814 : 0 : const CBlockIndex *pindex = nullptr;
4815 [ # # ]: 0 : BlockValidationState state;
4816 [ # # # # ]: 0 : if (!m_chainman.ProcessNewBlockHeaders({{cmpctblock.header}}, /*min_pow_checked=*/true, state, &pindex)) {
4817 [ # # ]: 0 : if (state.IsInvalid()) {
4818 [ # # # # ]: 0 : MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block=*/true, "invalid header via cmpctblock");
4819 : 0 : return;
4820 : : }
4821 : : }
4822 : :
4823 : : // If AcceptBlockHeader returned true, it set pindex
4824 [ # # ]: 0 : Assert(pindex);
4825 [ # # ]: 0 : if (received_new_header) {
4826 [ # # ]: 0 : LogBlockHeader(*pindex, pfrom, /*via_compact_block=*/true);
4827 : : }
4828 : :
4829 : 0 : bool fProcessBLOCKTXN = false;
4830 : :
4831 : : // If we end up treating this as a plain headers message, call that as well
4832 : : // without cs_main.
4833 : 0 : bool fRevertToHeaderProcessing = false;
4834 : :
4835 : : // Keep a CBlock for "optimistic" compactblock reconstructions (see
4836 : : // below)
4837 [ # # ]: 0 : std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4838 : 0 : bool fBlockReconstructed = false;
4839 : :
4840 : 0 : {
4841 [ # # ]: 0 : LOCK(cs_main);
4842 [ # # ]: 0 : UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
4843 : :
4844 : 0 : CNodeState *nodestate = State(pfrom.GetId());
4845 : :
4846 : : // If this was a new header with more work than our tip, update the
4847 : : // peer's last block announcement time
4848 [ # # # # : 0 : if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
# # # # #
# ]
4849 [ # # ]: 0 : nodestate->m_last_block_announcement = GetTime();
4850 : : }
4851 : :
4852 [ # # ]: 0 : if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
4853 : : return;
4854 : :
4855 : 0 : auto range_flight = mapBlocksInFlight.equal_range(pindex->GetBlockHash());
4856 : 0 : size_t already_in_flight = std::distance(range_flight.first, range_flight.second);
4857 : 0 : bool requested_block_from_this_peer{false};
4858 : :
4859 : : // Multimap ensures ordering of outstanding requests. It's either empty or first in line.
4860 [ # # # # ]: 0 : bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId());
4861 : :
4862 [ # # ]: 0 : while (range_flight.first != range_flight.second) {
4863 [ # # ]: 0 : if (range_flight.first->second.first == pfrom.GetId()) {
4864 : : requested_block_from_this_peer = true;
4865 : : break;
4866 : : }
4867 : 0 : range_flight.first++;
4868 : : }
4869 : :
4870 [ # # # # ]: 0 : if (!requested_block_from_this_peer && !pfrom.m_bip152_highbandwidth_to) {
4871 [ # # # # : 0 : LogDebug(BCLog::CMPCTBLOCK, "%s, not marked as high-bandwidth, sent us an unsolicited compact block!", pfrom.LogPeer());
# # # # ]
4872 : 0 : return;
4873 : : }
4874 : :
4875 [ # # # # : 0 : if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better
# # # # ]
4876 [ # # ]: 0 : pindex->nTx != 0) { // We had this block at some point, but pruned it
4877 [ # # ]: 0 : if (requested_block_from_this_peer) {
4878 : : // We requested this block for some reason, but our mempool will probably be useless
4879 : : // so we just grab the block via normal getdata
4880 [ # # ]: 0 : std::vector<CInv> vInv(1);
4881 [ # # ]: 0 : vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(peer), blockhash);
4882 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4883 : 0 : }
4884 : 0 : return;
4885 : : }
4886 : :
4887 : : // If we're not close to tip yet, give up and let parallel block fetch work its magic
4888 [ # # # # : 0 : if (!already_in_flight && !CanDirectFetch()) {
# # ]
4889 : : return;
4890 : : }
4891 : :
4892 : : // We want to be a bit conservative just to be extra careful about DoS
4893 : : // possibilities in compact block processing...
4894 [ # # # # : 0 : if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
# # ]
4895 [ # # # # : 0 : if ((already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK && nodestate->vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
# # ]
4896 : : requested_block_from_this_peer) {
4897 : 0 : std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
4898 [ # # # # ]: 0 : if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) {
4899 [ # # ]: 0 : if (!(*queuedBlockIt)->partialBlock)
4900 [ # # # # ]: 0 : (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool));
4901 : : else {
4902 : : // The block was already in flight using compact blocks from the same peer
4903 [ # # # # : 0 : LogDebug(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
# # ]
4904 : 0 : return;
4905 : : }
4906 : : }
4907 : :
4908 [ # # ]: 0 : PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
4909 [ # # ]: 0 : ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
4910 [ # # ]: 0 : if (status == READ_STATUS_INVALID) {
4911 [ # # ]: 0 : RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect
4912 [ # # # # ]: 0 : Misbehaving(peer, "invalid compact block");
4913 : 0 : return;
4914 [ # # ]: 0 : } else if (status == READ_STATUS_FAILED) {
4915 [ # # ]: 0 : if (first_in_flight) {
4916 : : // Duplicate txindexes, the block is now in-flight, so just request it
4917 [ # # ]: 0 : std::vector<CInv> vInv(1);
4918 [ # # ]: 0 : vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(peer), blockhash);
4919 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4920 : 0 : } else {
4921 : : // Give up for this peer and wait for other peer(s)
4922 [ # # ]: 0 : RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId());
4923 : : }
4924 : 0 : return;
4925 : : }
4926 : :
4927 : 0 : BlockTransactionsRequest req;
4928 [ # # # # ]: 0 : for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
4929 [ # # # # ]: 0 : if (!partialBlock.IsTxAvailable(i))
4930 [ # # ]: 0 : req.indexes.push_back(i);
4931 : : }
4932 [ # # ]: 0 : if (req.indexes.empty()) {
4933 : : fProcessBLOCKTXN = true;
4934 [ # # ]: 0 : } else if (first_in_flight) {
4935 : : // We will try to round-trip any compact blocks we get on failure,
4936 : : // as long as it's first...
4937 : 0 : req.blockhash = pindex->GetBlockHash();
4938 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
4939 [ # # ]: 0 : } else if (pfrom.m_bip152_highbandwidth_to &&
4940 [ # # # # ]: 0 : (!pfrom.IsInboundConn() ||
4941 [ # # # # ]: 0 : IsBlockRequestedFromOutbound(blockhash) ||
4942 : : already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK - 1)) {
4943 : : // ... or it's a hb relay peer and:
4944 : : // - peer is outbound, or
4945 : : // - we already have an outbound attempt in flight(so we'll take what we can get), or
4946 : : // - it's not the final parallel download slot (which we may reserve for first outbound)
4947 : 0 : req.blockhash = pindex->GetBlockHash();
4948 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
4949 : : } else {
4950 : : // Give up for this peer and wait for other peer(s)
4951 [ # # ]: 0 : RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId());
4952 : : }
4953 : 0 : } else {
4954 : : // This block is either already in flight from a different
4955 : : // peer, or this peer has too many blocks outstanding to
4956 : : // download from.
4957 : : // Optimistically try to reconstruct anyway since we might be
4958 : : // able to without any round trips.
4959 : 0 : PartiallyDownloadedBlock tempBlock(&m_mempool);
4960 [ # # ]: 0 : ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
4961 [ # # ]: 0 : if (status != READ_STATUS_OK) {
4962 : : // TODO: don't ignore failures
4963 : 0 : return;
4964 : : }
4965 : 0 : std::vector<CTransactionRef> dummy;
4966 [ # # ]: 0 : const CBlockIndex* prev_block{Assume(m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock))};
4967 [ # # ]: 0 : status = tempBlock.FillBlock(*pblock, dummy,
4968 : 0 : /*segwit_active=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT));
4969 [ # # ]: 0 : if (status == READ_STATUS_OK) {
4970 : 0 : fBlockReconstructed = true;
4971 : : }
4972 : 0 : }
4973 : : } else {
4974 [ # # ]: 0 : if (requested_block_from_this_peer) {
4975 : : // We requested this block, but its far into the future, so our
4976 : : // mempool will probably be useless - request the block normally
4977 [ # # ]: 0 : std::vector<CInv> vInv(1);
4978 [ # # ]: 0 : vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(peer), blockhash);
4979 [ # # # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4980 : 0 : return;
4981 : 0 : } else {
4982 : : // If this was an announce-cmpctblock, we want the same treatment as a header message
4983 : : fRevertToHeaderProcessing = true;
4984 : : }
4985 : : }
4986 : 0 : } // cs_main
4987 : :
4988 [ # # ]: 0 : if (fProcessBLOCKTXN) {
4989 : 0 : BlockTransactions txn;
4990 : 0 : txn.blockhash = blockhash;
4991 [ # # ]: 0 : return ProcessCompactBlockTxns(pfrom, peer, txn);
4992 : 0 : }
4993 : :
4994 [ # # ]: 0 : if (fRevertToHeaderProcessing) {
4995 : : // Headers received from HB compact block peers are permitted to be
4996 : : // relayed before full validation (see BIP 152), so we don't want to disconnect
4997 : : // the peer if the header turns out to be for an invalid block.
4998 : : // Note that if a peer tries to build on an invalid chain, that
4999 : : // will be detected and the peer will be disconnected/discouraged.
5000 [ # # # # ]: 0 : return ProcessHeadersMessage(pfrom, peer, {cmpctblock.header}, /*via_compact_block=*/true);
5001 : : }
5002 : :
5003 [ # # ]: 0 : if (fBlockReconstructed) {
5004 : : // If we got here, we were able to optimistically reconstruct a
5005 : : // block that is in flight from some other peer.
5006 : 0 : {
5007 [ # # ]: 0 : LOCK(cs_main);
5008 [ # # # # ]: 0 : mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false));
5009 : 0 : }
5010 : : // Setting force_processing to true means that we bypass some of
5011 : : // our anti-DoS protections in AcceptBlock, which filters
5012 : : // unrequested blocks that might be trying to waste our resources
5013 : : // (eg disk space). Because we only try to reconstruct blocks when
5014 : : // we're close to caught up (via the CanDirectFetch() requirement
5015 : : // above, combined with the behavior of not requesting blocks until
5016 : : // we have a chain with at least the minimum chain work), and we ignore
5017 : : // compact blocks with less work than our tip, it is safe to treat
5018 : : // reconstructed compact blocks as having been requested.
5019 [ # # # # ]: 0 : ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
5020 [ # # ]: 0 : LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
5021 [ # # # # : 0 : if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
# # ]
5022 : : // Clear download state for this block, which is in
5023 : : // process from some other peer. We do this after calling
5024 : : // ProcessNewBlock so that a malleated cmpctblock announcement
5025 : : // can't be used to interfere with block relay.
5026 [ # # # # ]: 0 : RemoveBlockRequest(pblock->GetHash(), std::nullopt);
5027 : : }
5028 : 0 : }
5029 : 0 : return;
5030 : 0 : }
5031 : :
5032 [ # # ]: 0 : if (msg_type == NetMsgType::BLOCKTXN)
5033 : : {
5034 : : // Ignore blocktxn received while importing
5035 [ # # ]: 0 : if (m_chainman.m_blockman.LoadingBlocks()) {
5036 [ # # ]: 0 : LogDebug(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId());
5037 : 0 : return;
5038 : : }
5039 : :
5040 : 0 : BlockTransactions resp;
5041 [ # # ]: 0 : vRecv >> resp;
5042 : :
5043 [ # # ]: 0 : return ProcessCompactBlockTxns(pfrom, peer, resp);
5044 : 0 : }
5045 : :
5046 [ # # ]: 0 : if (msg_type == NetMsgType::HEADERS)
5047 : : {
5048 : : // Ignore headers received while importing
5049 [ # # ]: 0 : if (m_chainman.m_blockman.LoadingBlocks()) {
5050 [ # # ]: 0 : LogDebug(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
5051 : 0 : return;
5052 : : }
5053 : :
5054 : 0 : std::vector<CBlockHeader> headers;
5055 : :
5056 : : // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5057 [ # # ]: 0 : unsigned int nCount = ReadCompactSize(vRecv);
5058 [ # # ]: 0 : if (nCount > m_opts.max_headers_result) {
5059 [ # # # # ]: 0 : Misbehaving(peer, strprintf("headers message size = %u", nCount));
5060 : 0 : return;
5061 : : }
5062 [ # # ]: 0 : headers.resize(nCount);
5063 [ # # ]: 0 : for (unsigned int n = 0; n < nCount; n++) {
5064 [ # # ]: 0 : vRecv >> headers[n];
5065 [ # # ]: 0 : ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5066 : : }
5067 : :
5068 [ # # ]: 0 : ProcessHeadersMessage(pfrom, peer, std::move(headers), /*via_compact_block=*/false);
5069 : :
5070 : : // Check if the headers presync progress needs to be reported to validation.
5071 : : // This needs to be done without holding the m_headers_presync_mutex lock.
5072 [ # # ]: 0 : if (m_headers_presync_should_signal.exchange(false)) {
5073 : 0 : HeadersPresyncStats stats;
5074 : 0 : {
5075 [ # # ]: 0 : LOCK(m_headers_presync_mutex);
5076 : 0 : auto it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
5077 [ # # ]: 0 : if (it != m_headers_presync_stats.end()) stats = it->second;
5078 : 0 : }
5079 [ # # ]: 0 : if (stats.second) {
5080 [ # # ]: 0 : m_chainman.ReportHeadersPresync(stats.second->first, stats.second->second);
5081 : : }
5082 : : }
5083 : :
5084 : 0 : return;
5085 : 0 : }
5086 : :
5087 [ # # ]: 0 : if (msg_type == NetMsgType::BLOCK)
5088 : : {
5089 : : // Ignore block received while importing
5090 [ # # ]: 0 : if (m_chainman.m_blockman.LoadingBlocks()) {
5091 [ # # ]: 0 : LogDebug(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId());
5092 : 0 : return;
5093 : : }
5094 : :
5095 : 0 : std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
5096 [ # # ]: 0 : vRecv >> TX_WITH_WITNESS(*pblock);
5097 : :
5098 [ # # # # : 0 : LogDebug(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId());
# # # # #
# ]
5099 : :
5100 [ # # # # : 0 : const CBlockIndex* prev_block{WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};
# # ]
5101 : :
5102 : : // Check for possible mutation if it connects to something we know so we can check for DEPLOYMENT_SEGWIT being active
5103 [ # # # # : 0 : if (prev_block && IsBlockMutated(/*block=*/*pblock,
# # ]
5104 : 0 : /*check_witness_root=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT))) {
5105 [ # # # # : 0 : LogDebug(BCLog::NET, "Received mutated block from peer=%d\n", peer.m_id);
# # ]
5106 [ # # # # ]: 0 : Misbehaving(peer, "mutated block");
5107 [ # # # # : 0 : WITH_LOCK(cs_main, RemoveBlockRequest(pblock->GetHash(), peer.m_id));
# # ]
5108 : : return;
5109 : : }
5110 : :
5111 : 0 : bool forceProcessing = false;
5112 [ # # ]: 0 : const uint256 hash(pblock->GetHash());
5113 : 0 : bool min_pow_checked = false;
5114 : 0 : {
5115 [ # # ]: 0 : LOCK(cs_main);
5116 : : // Always process the block if we requested it, since we may
5117 : : // need it even when it's not a candidate for a new best tip.
5118 : 0 : forceProcessing = IsBlockRequested(hash);
5119 [ # # ]: 0 : RemoveBlockRequest(hash, pfrom.GetId());
5120 : : // mapBlockSource is only used for punishing peers and setting
5121 : : // which peers send us compact blocks, so the race between here and
5122 : : // cs_main in ProcessNewBlock is fine.
5123 [ # # ]: 0 : mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
5124 : :
5125 : : // Check claimed work on this block against our anti-dos thresholds.
5126 [ # # # # : 0 : if (prev_block && prev_block->nChainWork + GetBlockProof(*pblock) >= GetAntiDoSWorkThreshold()) {
# # # # #
# ]
5127 : : min_pow_checked = true;
5128 : : }
5129 : 0 : }
5130 [ # # # # ]: 0 : ProcessBlock(pfrom, pblock, forceProcessing, min_pow_checked);
5131 : 0 : return;
5132 : 0 : }
5133 : :
5134 [ # # ]: 0 : if (msg_type == NetMsgType::GETADDR) {
5135 : : // This asymmetric behavior for inbound and outbound connections was introduced
5136 : : // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5137 : : // to users' AddrMan and later request them by sending getaddr messages.
5138 : : // Making nodes which are behind NAT and can only make outgoing connections ignore
5139 : : // the getaddr message mitigates the attack.
5140 [ # # ]: 0 : if (!pfrom.IsInboundConn()) {
5141 [ # # # # ]: 0 : LogDebug(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId());
5142 : 0 : return;
5143 : : }
5144 : :
5145 : : // Since this must be an inbound connection, SetupAddressRelay will
5146 : : // never fail.
5147 [ # # ]: 0 : Assume(SetupAddressRelay(pfrom, peer));
5148 : :
5149 : : // Only send one GetAddr response per connection to reduce resource waste
5150 : : // and discourage addr stamping of INV announcements.
5151 [ # # ]: 0 : if (peer.m_getaddr_recvd) {
5152 [ # # ]: 0 : LogDebug(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId());
5153 : 0 : return;
5154 : : }
5155 : 0 : peer.m_getaddr_recvd = true;
5156 : :
5157 : 0 : peer.m_addrs_to_send.clear();
5158 : 0 : std::vector<CAddress> vAddr;
5159 [ # # ]: 0 : if (pfrom.HasPermission(NetPermissionFlags::Addr)) {
5160 [ # # ]: 0 : vAddr = m_connman.GetAddressesUnsafe(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /*network=*/std::nullopt);
5161 : : } else {
5162 [ # # ]: 0 : vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
5163 : : }
5164 [ # # ]: 0 : for (const CAddress &addr : vAddr) {
5165 [ # # ]: 0 : PushAddress(peer, addr);
5166 : : }
5167 : 0 : return;
5168 : 0 : }
5169 : :
5170 [ # # ]: 0 : if (msg_type == NetMsgType::MEMPOOL) {
5171 : : // Only process received mempool messages if we advertise NODE_BLOOM
5172 : : // or if the peer has mempool permissions.
5173 [ # # # # ]: 0 : if (!(peer.m_our_services & NODE_BLOOM) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
5174 : : {
5175 [ # # ]: 0 : if (!pfrom.HasPermission(NetPermissionFlags::NoBan))
5176 : : {
5177 [ # # # # ]: 0 : LogDebug(BCLog::NET, "mempool request with bloom filters disabled, %s", pfrom.DisconnectMsg());
5178 : 0 : pfrom.fDisconnect = true;
5179 : : }
5180 : 0 : return;
5181 : : }
5182 : :
5183 [ # # # # ]: 0 : if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
5184 : : {
5185 [ # # ]: 0 : if (!pfrom.HasPermission(NetPermissionFlags::NoBan))
5186 : : {
5187 [ # # # # ]: 0 : LogDebug(BCLog::NET, "mempool request with bandwidth limit reached, %s", pfrom.DisconnectMsg());
5188 : 0 : pfrom.fDisconnect = true;
5189 : : }
5190 : 0 : return;
5191 : : }
5192 : :
5193 [ # # ]: 0 : if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
5194 : 0 : LOCK(tx_relay->m_tx_inventory_mutex);
5195 [ # # ]: 0 : tx_relay->m_send_mempool = true;
5196 : 0 : }
5197 : 0 : return;
5198 : : }
5199 : :
5200 [ # # ]: 0 : if (msg_type == NetMsgType::PING) {
5201 [ # # ]: 0 : if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
5202 : 0 : uint64_t nonce = 0;
5203 : 0 : vRecv >> nonce;
5204 : : // Echo the message back with the nonce. This allows for two useful features:
5205 : : //
5206 : : // 1) A remote node can quickly check if the connection is operational
5207 : : // 2) Remote nodes can measure the latency of the network thread. If this node
5208 : : // is overloaded it won't respond to pings quickly and the remote node can
5209 : : // avoid sending us more work, like chain download requests.
5210 : : //
5211 : : // The nonce stops the remote getting confused between different pings: without
5212 : : // it, if the remote node sends a ping once per second and this node takes 5
5213 : : // seconds to respond to each, the 5th ping the remote sends would appear to
5214 : : // return very quickly.
5215 [ # # ]: 0 : MakeAndPushMessage(pfrom, NetMsgType::PONG, nonce);
5216 : : }
5217 : 0 : return;
5218 : : }
5219 : :
5220 [ # # ]: 0 : if (msg_type == NetMsgType::PONG) {
5221 : 0 : ProcessPong(pfrom, peer, /*ping_end=*/time_received, vRecv);
5222 : 0 : return;
5223 : : }
5224 : :
5225 [ # # ]: 0 : if (msg_type == NetMsgType::FILTERLOAD) {
5226 [ # # ]: 0 : if (!(peer.m_our_services & NODE_BLOOM)) {
5227 [ # # # # ]: 0 : LogDebug(BCLog::NET, "filterload received despite not offering bloom services, %s", pfrom.DisconnectMsg());
5228 : 0 : pfrom.fDisconnect = true;
5229 : 0 : return;
5230 : : }
5231 [ # # ]: 0 : CBloomFilter filter;
5232 [ # # ]: 0 : vRecv >> filter;
5233 : :
5234 [ # # # # ]: 0 : if (!filter.IsWithinSizeConstraints())
5235 : : {
5236 : : // There is no excuse for sending a too-large filter
5237 [ # # # # ]: 0 : Misbehaving(peer, "too-large bloom filter");
5238 [ # # # # ]: 0 : } else if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
5239 : 0 : {
5240 [ # # ]: 0 : LOCK(tx_relay->m_bloom_filter_mutex);
5241 [ # # # # : 0 : tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
# # ]
5242 [ # # ]: 0 : tx_relay->m_relay_txs = true;
5243 : 0 : }
5244 [ # # ]: 0 : pfrom.m_bloom_filter_loaded = true;
5245 : 0 : pfrom.m_relays_txs = true;
5246 [ # # ]: 0 : MaybeDisconnectForTxRelayCapacity(pfrom, msg_type);
5247 : : }
5248 : 0 : return;
5249 : 0 : }
5250 : :
5251 [ # # ]: 0 : if (msg_type == NetMsgType::FILTERADD) {
5252 [ # # ]: 0 : if (!(peer.m_our_services & NODE_BLOOM)) {
5253 [ # # # # ]: 0 : LogDebug(BCLog::NET, "filteradd received despite not offering bloom services, %s", pfrom.DisconnectMsg());
5254 : 0 : pfrom.fDisconnect = true;
5255 : 0 : return;
5256 : : }
5257 : 0 : std::vector<unsigned char> vData;
5258 [ # # ]: 0 : vRecv >> vData;
5259 : :
5260 : : // Nodes must NEVER send a data item > MAX_SCRIPT_ELEMENT_SIZE bytes (the max size for a script data object,
5261 : : // and thus, the maximum size any matched object can have) in a filteradd message
5262 : 0 : bool bad = false;
5263 [ # # # # ]: 0 : if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
5264 : : bad = true;
5265 [ # # # # ]: 0 : } else if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
5266 [ # # ]: 0 : LOCK(tx_relay->m_bloom_filter_mutex);
5267 [ # # ]: 0 : if (tx_relay->m_bloom_filter) {
5268 [ # # # # ]: 0 : tx_relay->m_bloom_filter->insert(vData);
5269 : : } else {
5270 : : bad = true;
5271 : : }
5272 : 0 : }
5273 [ # # ]: 0 : if (bad) {
5274 [ # # # # ]: 0 : Misbehaving(peer, "bad filteradd message");
5275 : : }
5276 : 0 : return;
5277 : 0 : }
5278 : :
5279 [ # # ]: 0 : if (msg_type == NetMsgType::FILTERCLEAR) {
5280 [ # # ]: 0 : if (!(peer.m_our_services & NODE_BLOOM)) {
5281 [ # # # # ]: 0 : LogDebug(BCLog::NET, "filterclear received despite not offering bloom services, %s", pfrom.DisconnectMsg());
5282 : 0 : pfrom.fDisconnect = true;
5283 : 0 : return;
5284 : : }
5285 : 0 : auto tx_relay = peer.GetTxRelay();
5286 [ # # ]: 0 : if (!tx_relay) return;
5287 : :
5288 : 0 : {
5289 : 0 : LOCK(tx_relay->m_bloom_filter_mutex);
5290 [ # # ]: 0 : tx_relay->m_bloom_filter = nullptr;
5291 [ # # ]: 0 : tx_relay->m_relay_txs = true;
5292 : 0 : }
5293 : 0 : pfrom.m_bloom_filter_loaded = false;
5294 : 0 : pfrom.m_relays_txs = true;
5295 : 0 : MaybeDisconnectForTxRelayCapacity(pfrom, msg_type);
5296 : 0 : return;
5297 : : }
5298 : :
5299 [ # # ]: 0 : if (msg_type == NetMsgType::FEEFILTER) {
5300 : 0 : CAmount newFeeFilter = 0;
5301 : 0 : vRecv >> newFeeFilter;
5302 [ # # ]: 0 : if (MoneyRange(newFeeFilter)) {
5303 [ # # ]: 0 : if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
5304 : 0 : tx_relay->m_fee_filter_received = newFeeFilter;
5305 : : }
5306 [ # # # # ]: 0 : LogDebug(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
5307 : : }
5308 : 0 : return;
5309 : : }
5310 : :
5311 [ # # ]: 0 : if (msg_type == NetMsgType::GETCFILTERS) {
5312 : 0 : ProcessGetCFilters(pfrom, peer, vRecv);
5313 : 0 : return;
5314 : : }
5315 : :
5316 [ # # ]: 0 : if (msg_type == NetMsgType::GETCFHEADERS) {
5317 : 0 : ProcessGetCFHeaders(pfrom, peer, vRecv);
5318 : 0 : return;
5319 : : }
5320 : :
5321 [ # # ]: 0 : if (msg_type == NetMsgType::GETCFCHECKPT) {
5322 : 0 : ProcessGetCFCheckPt(pfrom, peer, vRecv);
5323 : 0 : return;
5324 : : }
5325 : :
5326 [ # # ]: 0 : if (msg_type == NetMsgType::NOTFOUND) {
5327 : 0 : std::vector<CInv> vInv;
5328 [ # # ]: 0 : vRecv >> vInv;
5329 : 0 : std::vector<GenTxid> tx_invs;
5330 [ # # # # ]: 0 : if (vInv.size() <= node::MAX_PEER_TX_ANNOUNCEMENTS + MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5331 [ # # ]: 0 : for (CInv &inv : vInv) {
5332 [ # # ]: 0 : if (inv.IsGenTxMsg()) {
5333 [ # # # # ]: 0 : tx_invs.emplace_back(ToGenTxid(inv));
5334 : : }
5335 : : }
5336 : : }
5337 [ # # ]: 0 : LOCK(m_tx_download_mutex);
5338 [ # # ]: 0 : m_txdownloadman.ReceivedNotFound(pfrom.GetId(), tx_invs);
5339 [ # # ]: 0 : return;
5340 : 0 : }
5341 : :
5342 : : // Ignore unknown message types for extensibility
5343 [ # # # # : 0 : LogDebug(BCLog::NET, "Unknown message type \"%s\" from peer=%d", SanitizeString(msg_type), pfrom.GetId());
# # ]
5344 : : return;
5345 : : }
5346 : :
5347 : 16 : bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer)
5348 : : {
5349 : 16 : {
5350 : 16 : LOCK(peer.m_misbehavior_mutex);
5351 : :
5352 : : // There's nothing to do if the m_should_discourage flag isn't set
5353 [ + + + - ]: 16 : if (!peer.m_should_discourage) return false;
5354 : :
5355 [ + - ]: 4 : peer.m_should_discourage = false;
5356 : 12 : } // peer.m_misbehavior_mutex
5357 : :
5358 [ - + ]: 4 : if (pnode.HasPermission(NetPermissionFlags::NoBan)) {
5359 : : // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission
5360 : 0 : LogWarning("Not punishing noban peer %d!", peer.m_id);
5361 : 0 : return false;
5362 : : }
5363 : :
5364 [ - + ]: 4 : if (pnode.IsManualConn()) {
5365 : : // We never disconnect or discourage manual peers for bad behavior
5366 : 0 : LogWarning("Not punishing manually connected peer %d!", peer.m_id);
5367 : 0 : return false;
5368 : : }
5369 : :
5370 [ - + ]: 4 : if (pnode.addr.IsLocal()) {
5371 : : // We disconnect local peers for bad behavior but don't discourage (since that would discourage
5372 : : // all peers on the same local address)
5373 [ # # # # ]: 0 : LogDebug(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n",
5374 : : pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
5375 : 0 : pnode.fDisconnect = true;
5376 : 0 : return true;
5377 : : }
5378 : :
5379 : : // Normal case: Disconnect the peer and discourage all nodes sharing the address
5380 [ + - ]: 4 : LogDebug(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id);
5381 [ + - ]: 4 : if (m_banman) m_banman->Discourage(pnode.addr);
5382 : 4 : m_connman.DisconnectNode(pnode.addr);
5383 : 4 : return true;
5384 : : }
5385 : :
5386 : 2 : bool PeerManagerImpl::MaybeDisconnectForTxRelayCapacity(CNode& node, const std::string& msg_type, std::optional<NodeId> protect_peer)
5387 : : {
5388 [ - + - - ]: 2 : if (!node.IsInboundConn() || !node.m_relays_txs) return false;
5389 [ # # ]: 0 : if (m_connman.EvictTxPeerIfFull(protect_peer)) return false;
5390 : :
5391 [ # # ]: 0 : LogDebug(BCLog::NET, "failed to find a tx-relaying eviction candidate - connection dropped after %s message, peer=%d\n", msg_type, node.GetId());
5392 : 0 : node.fDisconnect = true;
5393 : 0 : return true;
5394 : : }
5395 : :
5396 : 5 : bool PeerManagerImpl::ProcessMessages(CNode& node, std::atomic<bool>& interruptMsgProc)
5397 : : {
5398 : 5 : AssertLockNotHeld(m_tx_download_mutex);
5399 : 5 : AssertLockHeld(g_msgproc_mutex);
5400 : :
5401 : 5 : PeerRef maybe_peer{GetPeerRef(node.GetId())};
5402 [ + - ]: 5 : if (maybe_peer == nullptr) return false;
5403 [ + - ]: 5 : Peer& peer{*maybe_peer};
5404 : :
5405 : : // For outbound connections, ensure that the initial VERSION message
5406 : : // has been sent first before processing any incoming messages
5407 [ + - + - ]: 5 : if (!node.IsInboundConn() && !peer.m_outbound_version_message_sent) return false;
5408 : :
5409 : 5 : {
5410 [ + - ]: 5 : LOCK(peer.m_getdata_requests_mutex);
5411 [ - + ]: 5 : if (!peer.m_getdata_requests.empty()) {
5412 [ # # ]: 0 : ProcessGetData(node, peer, interruptMsgProc);
5413 : : }
5414 : 0 : }
5415 : :
5416 [ + - ]: 5 : const bool processed_orphan = ProcessOrphanTx(peer);
5417 : :
5418 [ + - ]: 5 : if (node.fDisconnect)
5419 : : return false;
5420 : :
5421 [ + - ]: 5 : if (processed_orphan) return true;
5422 : :
5423 : : // this maintains the order of responses
5424 : : // and prevents m_getdata_requests to grow unbounded
5425 : 5 : {
5426 [ + - ]: 5 : LOCK(peer.m_getdata_requests_mutex);
5427 [ - + - - ]: 5 : if (!peer.m_getdata_requests.empty()) return true;
5428 : 0 : }
5429 : :
5430 : : // Don't bother if send buffer is too full to respond anyway
5431 [ + - ]: 5 : if (node.fPauseSend) return false;
5432 : :
5433 [ + - ]: 5 : auto poll_result{node.PollMessage()};
5434 [ + - ]: 5 : if (!poll_result) {
5435 : : // No message to process
5436 : : return false;
5437 : : }
5438 : :
5439 [ - + ]: 5 : CNetMessage& msg{poll_result->first};
5440 : 5 : bool fMoreWork = poll_result->second;
5441 : :
5442 : : TRACEPOINT(net, inbound_message,
5443 : : node.GetId(),
5444 : : node.m_addr_name.c_str(),
5445 : : node.ConnectionTypeAsString().c_str(),
5446 : : msg.m_type.c_str(),
5447 : : msg.m_recv.size(),
5448 : : msg.m_recv.data()
5449 : 5 : );
5450 : :
5451 [ - + ]: 5 : if (m_opts.capture_messages) {
5452 [ # # ]: 0 : CaptureMessage(node.addr, msg.m_type, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true);
5453 : : }
5454 : :
5455 : 5 : try {
5456 [ + - ]: 5 : ProcessMessage(peer, node, msg.m_type, msg.m_recv, msg.m_time, interruptMsgProc);
5457 [ + - ]: 5 : if (interruptMsgProc) return false;
5458 : 5 : {
5459 [ + - ]: 5 : LOCK(peer.m_getdata_requests_mutex);
5460 [ - + ]: 5 : if (!peer.m_getdata_requests.empty()) fMoreWork = true;
5461 : 5 : }
5462 : : // Does this peer have an orphan ready to reconsider?
5463 : : // (Note: we may have provided a parent for an orphan provided
5464 : : // by another peer that was already processed; in that case,
5465 : : // the extra work may not be noticed, possibly resulting in an
5466 : : // unnecessary 100ms delay)
5467 [ + - ]: 5 : LOCK(m_tx_download_mutex);
5468 [ + - - + ]: 5 : if (m_txdownloadman.HaveMoreWork(peer.m_id)) fMoreWork = true;
5469 [ - - ]: 5 : } catch (const std::exception& e) {
5470 [ - - - - : 0 : LogDebug(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size, e.what(), typeid(e).name());
- - - - -
- - - ]
5471 : 0 : } catch (...) {
5472 [ - - - - : 0 : LogDebug(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size);
- - - - -
- ]
5473 [ - - ]: 0 : }
5474 : :
5475 : : return fMoreWork;
5476 : 10 : }
5477 : :
5478 : 6 : void PeerManagerImpl::ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds)
5479 : : {
5480 : 6 : AssertLockHeld(cs_main);
5481 : :
5482 : 6 : CNodeState &state = *State(pto.GetId());
5483 : :
5484 [ + - + + : 6 : if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) {
+ - ]
5485 : : // This is an outbound peer subject to disconnection if they don't
5486 : : // announce a block with as much work as the current tip within
5487 : : // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
5488 : : // their chain has more work than ours, we should sync to it,
5489 : : // unless it's invalid, in which case we should find that out and
5490 : : // disconnect from them elsewhere).
5491 [ - + - - : 5 : if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
- - ]
5492 : : // 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
5493 [ # # ]: 0 : if (state.m_chain_sync.m_timeout != 0s) {
5494 : 0 : state.m_chain_sync.m_timeout = 0s;
5495 : 0 : state.m_chain_sync.m_work_header = nullptr;
5496 : 0 : state.m_chain_sync.m_sent_getheaders = false;
5497 : : }
5498 [ + + + - : 5 : } 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)) {
- + - - ]
5499 : : // 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
5500 : : // AND
5501 : : // we are noticing this for the first time (m_timeout is 0)
5502 : : // OR we noticed this at some point within the last CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds and set a timeout
5503 : : // 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).
5504 : : // Either way, set a new timeout based on our current tip.
5505 : 2 : state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
5506 [ - + ]: 2 : state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
5507 : 2 : state.m_chain_sync.m_sent_getheaders = false;
5508 [ + - + + ]: 3 : } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) {
5509 : : // No evidence yet that our peer has synced to a chain with work equal to that
5510 : : // of our tip, when we first detected it was behind. Send a single getheaders
5511 : : // message to give the peer a chance to update us.
5512 [ + + ]: 2 : if (state.m_chain_sync.m_sent_getheaders) {
5513 : : // They've run out of time to catch up!
5514 [ - + - - : 1 : LogInfo("Outbound peer has old chain, best known block = %s, %s", state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", pto.DisconnectMsg());
+ - + - ]
5515 : 1 : pto.fDisconnect = true;
5516 : : } else {
5517 [ - + ]: 1 : assert(state.m_chain_sync.m_work_header);
5518 : : // Here, we assume that the getheaders message goes out,
5519 : : // because it'll either go out or be skipped because of a
5520 : : // getheaders in-flight already, in which case the peer should
5521 : : // still respond to us with a sufficiently high work chain tip.
5522 [ + - ]: 1 : MaybeSendGetHeaders(pto,
5523 : 1 : GetLocator(state.m_chain_sync.m_work_header->pprev),
5524 : : peer);
5525 [ + - - + : 1 : 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());
- - + - +
- ]
5526 : 1 : state.m_chain_sync.m_sent_getheaders = true;
5527 : : // Bump the timeout to allow a response, which could clear the timeout
5528 : : // (if the response shows the peer has synced), reset the timeout (if
5529 : : // the peer syncs to the required work but not to our tip), or result
5530 : : // in disconnect (if we advance to the timeout and pindexBestKnownBlock
5531 : : // has not sufficiently progressed)
5532 : 1 : state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
5533 : : }
5534 : : }
5535 : : }
5536 : 6 : }
5537 : :
5538 : 10 : void PeerManagerImpl::EvictExtraOutboundPeers(NodeClock::time_point now)
5539 : : {
5540 : : // If we have any extra block-relay-only peers, disconnect the youngest unless
5541 : : // it's given us a block -- in which case, compare with the second-youngest, and
5542 : : // out of those two, disconnect the peer who least recently gave us a block.
5543 : : // The youngest block-relay-only peer would be the extra peer we connected
5544 : : // to temporarily in order to sync our tip; see net.cpp.
5545 : : // Note that we use higher nodeid as a measure for most recent connection.
5546 [ + + ]: 10 : if (m_connman.GetExtraBlockRelayCount() > 0) {
5547 : 3 : std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0};
5548 : :
5549 [ + - ]: 3 : m_connman.ForEachNode([&](CNode* pnode) {
5550 [ + - - + ]: 9 : if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return;
5551 [ + - ]: 9 : if (pnode->GetId() > youngest_peer.first) {
5552 : 9 : next_youngest_peer = youngest_peer;
5553 : 9 : youngest_peer.first = pnode->GetId();
5554 : 9 : youngest_peer.second = pnode->m_last_block_time;
5555 : : }
5556 : : });
5557 : 3 : NodeId to_disconnect = youngest_peer.first;
5558 [ + + ]: 3 : if (youngest_peer.second > next_youngest_peer.second) {
5559 : : // Our newest block-relay-only peer gave us a block more recently;
5560 : : // disconnect our second youngest.
5561 : 1 : to_disconnect = next_youngest_peer.first;
5562 : : }
5563 [ + - ]: 6 : m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5564 : 3 : AssertLockHeld(::cs_main);
5565 : : // Make sure we're not getting a block right now, and that
5566 : : // we've been connected long enough for this eviction to happen
5567 : : // at all.
5568 : : // Note that we only request blocks from a peer if we learn of a
5569 : : // valid headers chain with at least as much work as our tip.
5570 : 3 : CNodeState *node_state = State(pnode->GetId());
5571 [ + - + + ]: 6 : if (node_state == nullptr ||
5572 [ + - ]: 5 : (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->vBlocksInFlight.empty())) {
5573 : 2 : pnode->fDisconnect = true;
5574 [ + - ]: 2 : LogDebug(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n",
5575 : : pnode->GetId(), count_seconds(pnode->m_last_block_time));
5576 : 2 : return true;
5577 : : } else {
5578 [ + - ]: 1 : LogDebug(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
5579 : : pnode->GetId(), TicksSinceEpoch<std::chrono::seconds>(pnode->m_connected), node_state->vBlocksInFlight.size());
5580 : : }
5581 : : return false;
5582 : : });
5583 : : }
5584 : :
5585 : : // Check whether we have too many outbound-full-relay peers
5586 [ + + ]: 10 : if (m_connman.GetExtraFullOutboundCount() > 0) {
5587 : : // If we have more outbound-full-relay peers than we target, disconnect one.
5588 : : // Pick the outbound-full-relay peer that least recently announced
5589 : : // us a new block, with ties broken by choosing the more recent
5590 : : // connection (higher node id)
5591 : : // Protect peers from eviction if we don't have another connection
5592 : : // to their network, counting both outbound-full-relay and manual peers.
5593 : 4 : NodeId worst_peer = -1;
5594 : 4 : int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
5595 : :
5596 [ + - ]: 4 : m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_connman.GetNodesMutex()) {
5597 : 38 : AssertLockHeld(::cs_main);
5598 : :
5599 : : // Only consider outbound-full-relay peers that are not already
5600 : : // marked for disconnection
5601 [ + - - + ]: 38 : if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return;
5602 : 38 : CNodeState *state = State(pnode->GetId());
5603 [ + - ]: 38 : if (state == nullptr) return; // shouldn't be possible, but just in case
5604 : : // Don't evict our protected peers
5605 [ + - ]: 38 : if (state->m_chain_sync.m_protect) return;
5606 : : // If this is the only connection on a particular network that is
5607 : : // OUTBOUND_FULL_RELAY or MANUAL, protect it.
5608 [ + + ]: 38 : if (!m_connman.MultipleManualOrFullOutboundConns(pnode->addr.GetNetwork())) return;
5609 [ + + + + : 37 : if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
+ - ]
5610 : 34 : worst_peer = pnode->GetId();
5611 : 34 : oldest_block_announcement = state->m_last_block_announcement;
5612 : : }
5613 : : });
5614 [ + - ]: 4 : if (worst_peer != -1) {
5615 [ + - ]: 4 : bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5616 : 4 : AssertLockHeld(::cs_main);
5617 : :
5618 : : // Only disconnect a peer that has been connected to us for
5619 : : // some reasonable fraction of our check-frequency, to give
5620 : : // it time for new information to have arrived.
5621 : : // Also don't disconnect any peer we're trying to download a
5622 : : // block from.
5623 : 4 : CNodeState &state = *State(pnode->GetId());
5624 [ + - + - ]: 4 : if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.vBlocksInFlight.empty()) {
5625 [ + - ]: 4 : LogDebug(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
5626 : 4 : pnode->fDisconnect = true;
5627 : 4 : return true;
5628 : : } else {
5629 [ # # ]: 0 : LogDebug(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
5630 : : pnode->GetId(), TicksSinceEpoch<std::chrono::seconds>(pnode->m_connected), state.vBlocksInFlight.size());
5631 : 0 : return false;
5632 : : }
5633 : : });
5634 [ + - ]: 4 : if (disconnected) {
5635 : : // If we disconnected an extra peer, that means we successfully
5636 : : // connected to at least one peer after the last time we
5637 : : // detected a stale tip. Don't try any more extra peers until
5638 : : // we next detect a stale tip, to limit the load we put on the
5639 : : // network from these extra connections.
5640 : 4 : m_connman.SetTryNewOutboundPeer(false);
5641 : : }
5642 : : }
5643 : : }
5644 : 10 : }
5645 : :
5646 : 10 : void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
5647 : : {
5648 : 10 : LOCK(cs_main);
5649 : :
5650 : 10 : const auto current_time{NodeClock::now()};
5651 : 10 : auto now{GetTime<std::chrono::seconds>()};
5652 : :
5653 [ + - ]: 10 : EvictExtraOutboundPeers(current_time);
5654 : :
5655 [ + + ]: 10 : if (now > m_stale_tip_check_time) {
5656 : : // Check whether our tip is stale, and if so, allow using an extra
5657 : : // outbound peer
5658 [ + - + - : 3 : if (!m_chainman.m_blockman.LoadingBlocks() && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
+ - + + ]
5659 [ + - ]: 1 : LogInfo("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
5660 : : count_seconds(now - m_last_tip_update.load()));
5661 [ + - ]: 1 : m_connman.SetTryNewOutboundPeer(true);
5662 [ + - - + ]: 2 : } else if (m_connman.GetTryNewOutboundPeer()) {
5663 [ # # ]: 0 : m_connman.SetTryNewOutboundPeer(false);
5664 : : }
5665 : 3 : m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
5666 : : }
5667 : :
5668 [ + - + - : 10 : if (!m_initial_sync_finished && CanDirectFetch()) {
- + ]
5669 [ # # ]: 0 : m_connman.StartExtraBlockRelayPeers();
5670 : 0 : m_initial_sync_finished = true;
5671 : : }
5672 : 10 : }
5673 : :
5674 : 6 : void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, NodeClock::time_point now)
5675 : : {
5676 [ - - ]: 6 : if (m_connman.ShouldRunInactivityChecks(node_to, now) &&
5677 [ - + - - : 6 : peer.m_ping_nonce_sent &&
- - ]
5678 [ # # ]: 0 : now > peer.m_ping_start.load() + TIMEOUT_INTERVAL)
5679 : : {
5680 : : // The ping timeout is using mocktime. To disable the check during
5681 : : // testing, increase -peertimeout.
5682 [ # # # # ]: 0 : LogDebug(BCLog::NET, "ping timeout: %fs, %s", Ticks<SecondsDouble>(now - peer.m_ping_start.load()), node_to.DisconnectMsg());
5683 : 0 : node_to.fDisconnect = true;
5684 : 0 : return;
5685 : : }
5686 : :
5687 : 6 : bool pingSend = false;
5688 : :
5689 [ - + ]: 6 : if (peer.m_ping_queued) {
5690 : : // RPC ping request by user
5691 : 0 : pingSend = true;
5692 : : }
5693 : :
5694 [ + + - + ]: 6 : if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) {
5695 : : // Ping automatically sent as a latency probe & keepalive.
5696 : : pingSend = true;
5697 : : }
5698 : :
5699 [ + + ]: 6 : if (pingSend) {
5700 : 3 : uint64_t nonce;
5701 : 3 : do {
5702 : 3 : nonce = FastRandomContext().rand64();
5703 [ - + ]: 3 : } while (nonce == 0);
5704 : 3 : peer.m_ping_queued = false;
5705 : 3 : peer.m_ping_start = now;
5706 [ + - ]: 3 : if (node_to.GetCommonVersion() > BIP0031_VERSION) {
5707 : 3 : peer.m_ping_nonce_sent = nonce;
5708 [ + - ]: 6 : MakeAndPushMessage(node_to, NetMsgType::PING, nonce);
5709 : : } else {
5710 : : // Peer is too old to support ping message type with nonce, pong will never arrive.
5711 : 0 : peer.m_ping_nonce_sent = 0;
5712 [ # # ]: 0 : MakeAndPushMessage(node_to, NetMsgType::PING);
5713 : : }
5714 : : }
5715 : : }
5716 : :
5717 : 6 : void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time)
5718 : : {
5719 : : // Nothing to do for non-address-relay peers
5720 [ + + ]: 6 : if (!peer.m_addr_relay_enabled) return;
5721 : :
5722 : 5 : LOCK(peer.m_addr_send_times_mutex);
5723 : : // Periodically advertise our local address to the peer.
5724 [ + - + + : 5 : if (fListen && !m_chainman.IsInitialBlockDownload() &&
+ - ]
5725 [ + - ]: 1 : peer.m_next_local_addr_send < current_time) {
5726 : : // If we've sent before, clear the bloom filter for the peer, so that our
5727 : : // self-announcement will actually go out.
5728 : : // This might be unnecessary if the bloom filter has already rolled
5729 : : // over since our last self-announcement, but there is only a small
5730 : : // bandwidth cost that we can incur by doing this (which happens
5731 : : // once a day on average).
5732 [ - + ]: 1 : if (peer.m_next_local_addr_send != 0us) {
5733 [ # # ]: 0 : peer.m_addr_known->reset();
5734 : : }
5735 [ + - + - ]: 1 : if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
5736 : 1 : CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()};
5737 [ + - ]: 1 : if (peer.m_next_local_addr_send == 0us) {
5738 : : // Send the initial self-announcement in its own message. This makes sure
5739 : : // rate-limiting with limited start-tokens doesn't ignore it if the first
5740 : : // message ends up containing multiple addresses.
5741 [ + - + - ]: 1 : if (IsAddrCompatible(peer, local_addr)) {
5742 [ - + + + : 2 : std::vector<CAddress> self_announcement{local_addr};
- - ]
5743 [ - + ]: 1 : if (peer.m_wants_addrv2) {
5744 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::ADDRV2, CAddress::V2_NETWORK(self_announcement));
5745 : : } else {
5746 [ + - + - ]: 2 : MakeAndPushMessage(node, NetMsgType::ADDR, CAddress::V1_NETWORK(self_announcement));
5747 : : }
5748 : 1 : }
5749 : : } else {
5750 : : // All later self-announcements are sent together with the other addresses.
5751 [ # # ]: 0 : PushAddress(peer, local_addr);
5752 : : }
5753 : 1 : }
5754 : 1 : peer.m_next_local_addr_send = current_time + m_rng.rand_exp_duration(AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
5755 : : }
5756 : :
5757 : : // We sent an `addr` message to this peer recently. Nothing more to do.
5758 [ + + ]: 5 : if (current_time <= peer.m_next_addr_send) return;
5759 : :
5760 [ - + ]: 4 : peer.m_next_addr_send = current_time + m_rng.rand_exp_duration(AVG_ADDRESS_BROADCAST_INTERVAL);
5761 : :
5762 [ - + - + ]: 4 : if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) {
5763 : : // Should be impossible since we always check size before adding to
5764 : : // m_addrs_to_send. Recover by trimming the vector.
5765 [ # # ]: 0 : peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND);
5766 : : }
5767 : :
5768 : : // Remove addr records that the peer already knows about, and add new
5769 : : // addrs to the m_addr_known filter on the same pass.
5770 : 4 : auto addr_already_known = [&peer](const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) {
5771 [ # # # # ]: 0 : bool ret = peer.m_addr_known->contains(addr.GetKey());
5772 [ # # # # : 0 : if (!ret) peer.m_addr_known->insert(addr.GetKey());
# # ]
5773 : 0 : return ret;
5774 : 4 : };
5775 : 4 : peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known),
5776 [ + - ]: 4 : peer.m_addrs_to_send.end());
5777 : :
5778 : : // No addr messages to send
5779 [ - + ]: 4 : if (peer.m_addrs_to_send.empty()) return;
5780 : :
5781 [ # # ]: 0 : if (peer.m_wants_addrv2) {
5782 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::ADDRV2, CAddress::V2_NETWORK(peer.m_addrs_to_send));
5783 : : } else {
5784 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::ADDR, CAddress::V1_NETWORK(peer.m_addrs_to_send));
5785 : : }
5786 : 0 : peer.m_addrs_to_send.clear();
5787 : :
5788 : : // we only send the big addr message once
5789 [ # # # # ]: 0 : if (peer.m_addrs_to_send.capacity() > 40) {
5790 : 0 : peer.m_addrs_to_send.shrink_to_fit();
5791 : : }
5792 : 6 : }
5793 : :
5794 : 6 : void PeerManagerImpl::MaybeSendSendHeaders(CNode& node, Peer& peer)
5795 : : {
5796 : : // Delay sending SENDHEADERS (BIP 130) until we're done with an
5797 : : // initial-headers-sync with this peer. Receiving headers announcements for
5798 : : // new blocks while trying to sync their headers chain is problematic,
5799 : : // because of the state tracking done.
5800 [ + - + - ]: 6 : if (!peer.m_sent_sendheaders && node.GetCommonVersion() >= SENDHEADERS_VERSION) {
5801 : 6 : LOCK(cs_main);
5802 : 6 : CNodeState &state = *State(node.GetId());
5803 [ - + - - ]: 6 : if (state.pindexBestKnownBlock != nullptr &&
5804 [ # # # # ]: 0 : state.pindexBestKnownBlock->nChainWork > m_chainman.MinimumChainWork()) {
5805 : : // Tell our peer we prefer to receive headers rather than inv's
5806 : : // We send this to non-NODE NETWORK peers as well, because even
5807 : : // non-NODE NETWORK peers can announce blocks (such as pruning
5808 : : // nodes)
5809 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::SENDHEADERS);
5810 : 0 : peer.m_sent_sendheaders = true;
5811 : : }
5812 : 6 : }
5813 : 6 : }
5814 : :
5815 : 6 : void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time)
5816 : : {
5817 [ + - ]: 6 : if (m_opts.ignore_incoming_txs) return;
5818 [ + - ]: 6 : if (pto.GetCommonVersion() < FEEFILTER_VERSION) return;
5819 : : // peers with the forcerelay permission should not filter txs to us
5820 [ + - ]: 6 : if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return;
5821 : : // Don't send feefilter messages to outbound block-relay-only peers since they should never announce
5822 : : // transactions to us, regardless of feefilter state.
5823 [ + - ]: 6 : if (pto.IsBlockOnlyConn()) return;
5824 : :
5825 : 6 : CAmount currentFilter = m_mempool.GetMinFee().GetFeePerK();
5826 : :
5827 [ + + ]: 6 : if (m_chainman.IsInitialBlockDownload()) {
5828 : : // Received tx-inv messages are discarded when the active
5829 : : // chainstate is in IBD, so tell the peer to not send them.
5830 : : currentFilter = MAX_MONEY;
5831 : : } else {
5832 [ + - + - : 1 : static const CAmount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)};
+ - ]
5833 [ - + ]: 1 : if (peer.m_fee_filter_sent == MAX_FILTER) {
5834 : : // Send the current filter if we sent MAX_FILTER previously
5835 : : // and made it out of IBD.
5836 : 0 : peer.m_next_send_feefilter = 0us;
5837 : : }
5838 : : }
5839 [ + + ]: 6 : if (current_time > peer.m_next_send_feefilter) {
5840 : 5 : CAmount filterToSend = m_fee_filter_rounder.round(currentFilter);
5841 : : // We always have a fee filter of at least the min relay fee
5842 [ + + ]: 5 : filterToSend = std::max(filterToSend, m_mempool.m_opts.min_relay_feerate.GetFeePerK());
5843 [ + + ]: 5 : if (filterToSend != peer.m_fee_filter_sent) {
5844 [ + - ]: 3 : MakeAndPushMessage(pto, NetMsgType::FEEFILTER, filterToSend);
5845 : 3 : peer.m_fee_filter_sent = filterToSend;
5846 : : }
5847 : 5 : peer.m_next_send_feefilter = current_time + m_rng.rand_exp_duration(AVG_FEEFILTER_BROADCAST_INTERVAL);
5848 : : }
5849 : : // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
5850 : : // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
5851 [ - + ]: 1 : else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter &&
5852 [ # # # # ]: 0 : (currentFilter < 3 * peer.m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
5853 : 0 : peer.m_next_send_feefilter = current_time + m_rng.randrange<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
5854 : : }
5855 : : }
5856 : :
5857 : 2 : bool PeerManagerImpl::RejectIncomingTxs(const CNode& peer) const
5858 : : {
5859 : : // block-relay-only peers may never send txs to us
5860 [ + - ]: 2 : if (peer.IsBlockOnlyConn()) return true;
5861 [ + - ]: 2 : if (peer.IsFeelerConn()) return true;
5862 : : // In -blocksonly mode, peers need the 'relay' permission to send txs to us
5863 [ - + - - ]: 2 : if (m_opts.ignore_incoming_txs && !peer.HasPermission(NetPermissionFlags::Relay)) return true;
5864 : : return false;
5865 : : }
5866 : :
5867 : 0 : void PeerManagerImpl::ProcessPong(CNode& pfrom, Peer& peer, const NodeClock::time_point ping_end, DataStream& vRecv)
5868 : : {
5869 : 0 : uint64_t nonce = 0;
5870 [ # # ]: 0 : const size_t nAvail{vRecv.size()};
5871 : 0 : bool bPingFinished = false;
5872 [ # # ]: 0 : std::string sProblem;
5873 : :
5874 [ # # ]: 0 : if (nAvail >= sizeof(nonce)) {
5875 [ # # ]: 0 : vRecv >> nonce;
5876 : :
5877 : : // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5878 [ # # ]: 0 : if (peer.m_ping_nonce_sent != 0) {
5879 [ # # ]: 0 : if (nonce == peer.m_ping_nonce_sent) {
5880 : : // Matching pong received, this ping is no longer outstanding
5881 : 0 : bPingFinished = true;
5882 [ # # ]: 0 : const auto ping_time = ping_end - peer.m_ping_start.load();
5883 [ # # ]: 0 : if (ping_time.count() >= 0) {
5884 : : // Let connman know about this successful ping-pong
5885 : 0 : pfrom.PongReceived(ping_time);
5886 [ # # ]: 0 : if (pfrom.IsPrivateBroadcastConn()) {
5887 [ # # ]: 0 : m_tx_for_private_broadcast.NodeConfirmedReception(pfrom.GetId());
5888 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "Got a PONG (the transaction will probably reach the network), marking for disconnect, %s",
# # # # ]
5889 : : pfrom.LogPeer());
5890 : 0 : pfrom.fDisconnect = true;
5891 : : }
5892 : : } else {
5893 : : // This should never happen
5894 [ # # ]: 0 : sProblem = "Timing mishap";
5895 : : }
5896 : : } else {
5897 : : // Nonce mismatches are normal when pings are overlapping
5898 [ # # ]: 0 : sProblem = "Nonce mismatch";
5899 [ # # ]: 0 : if (nonce == 0) {
5900 : : // This is most likely a bug in another implementation somewhere; cancel this ping
5901 : 0 : bPingFinished = true;
5902 [ # # ]: 0 : sProblem = "Nonce zero";
5903 : : }
5904 : : }
5905 : : } else {
5906 [ # # ]: 0 : sProblem = "Unsolicited pong without ping";
5907 : : }
5908 : : } else {
5909 : : // This is most likely a bug in another implementation somewhere; cancel this ping
5910 : 0 : bPingFinished = true;
5911 [ # # ]: 0 : sProblem = "Short payload";
5912 : : }
5913 : :
5914 [ # # ]: 0 : if (!(sProblem.empty())) {
5915 [ # # # # : 0 : LogDebug(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
# # ]
5916 : : pfrom.GetId(),
5917 : : sProblem,
5918 : : peer.m_ping_nonce_sent,
5919 : : nonce,
5920 : : nAvail);
5921 : : }
5922 [ # # ]: 0 : if (bPingFinished) {
5923 : 0 : peer.m_ping_nonce_sent = 0;
5924 : : }
5925 : 0 : }
5926 : :
5927 : 2 : bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer)
5928 : : {
5929 : : // We don't participate in addr relay with outbound block-relay-only
5930 : : // connections to prevent providing adversaries with the additional
5931 : : // information of addr traffic to infer the link.
5932 [ + - ]: 2 : if (node.IsBlockOnlyConn()) return false;
5933 : :
5934 : : // We don't participate in addr relay with feeler connections because
5935 : : // they are disconnected shortly after the handshake completes,
5936 : : // before the node will receive the addr response.
5937 [ + - ]: 2 : if (node.IsFeelerConn()) return false;
5938 : :
5939 [ + - ]: 2 : if (!peer.m_addr_relay_enabled.exchange(true)) {
5940 : : // During version message processing (non-block-relay-only outbound peers)
5941 : : // or on first addr-related message we have received (inbound peers), initialize
5942 : : // m_addr_known.
5943 : 2 : peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
5944 : : }
5945 : :
5946 : : return true;
5947 : : }
5948 : :
5949 : 0 : void PeerManagerImpl::ProcessAddrs(std::string_view msg_type, CNode& pfrom, Peer& peer, std::vector<CAddress>&& vAddr, const std::atomic<bool>& interruptMsgProc)
5950 : : {
5951 : 0 : AssertLockNotHeld(m_peer_mutex);
5952 : 0 : AssertLockHeld(g_msgproc_mutex);
5953 : :
5954 [ # # ]: 0 : if (!SetupAddressRelay(pfrom, peer)) {
5955 [ # # # # ]: 0 : LogDebug(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
5956 : 0 : return;
5957 : : }
5958 : :
5959 [ # # # # ]: 0 : if (vAddr.size() > MAX_ADDR_TO_SEND)
5960 : : {
5961 [ # # ]: 0 : Misbehaving(peer, strprintf("%s message size = %u", msg_type, vAddr.size()));
5962 : 0 : return;
5963 : : }
5964 : :
5965 : : // Store the new addresses
5966 : 0 : std::vector<CAddress> vAddrOk;
5967 : :
5968 : : // Update/increment addr rate limiting bucket.
5969 : 0 : const auto current_time{NodeClock::now()};
5970 [ # # ]: 0 : if (peer.m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
5971 : : // Don't increment bucket if it's already full
5972 : 0 : const auto time_diff{current_time - peer.m_addr_token_timestamp};
5973 [ # # ]: 0 : const double increment{std::max(Ticks<SecondsDouble>(time_diff), 0.0) * MAX_ADDR_RATE_PER_SECOND};
5974 [ # # ]: 0 : peer.m_addr_token_bucket = std::min<double>(peer.m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET);
5975 : : }
5976 : 0 : peer.m_addr_token_timestamp = current_time;
5977 : :
5978 : 0 : const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr);
5979 : 0 : uint64_t num_proc = 0;
5980 : 0 : uint64_t num_rate_limit = 0;
5981 : 0 : std::shuffle(vAddr.begin(), vAddr.end(), m_rng);
5982 [ # # ]: 0 : for (CAddress& addr : vAddr)
5983 : : {
5984 [ # # ]: 0 : if (interruptMsgProc)
5985 : 0 : return;
5986 : :
5987 : : // Apply rate limiting.
5988 [ # # ]: 0 : if (peer.m_addr_token_bucket < 1.0) {
5989 [ # # ]: 0 : if (rate_limited) {
5990 : 0 : ++num_rate_limit;
5991 : 0 : continue;
5992 : : }
5993 : : } else {
5994 : 0 : peer.m_addr_token_bucket -= 1.0;
5995 : : }
5996 : : // We only bother storing full nodes, though this may include
5997 : : // things which we would not make an outbound connection to, in
5998 : : // part because we may make feeler connections to them.
5999 [ # # # # ]: 0 : if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices))
6000 : 0 : continue;
6001 : :
6002 [ # # # # ]: 0 : if (addr.nTime <= NodeSeconds{100000000s} || addr.nTime > current_time + 10min) {
6003 : 0 : addr.nTime = std::chrono::time_point_cast<std::chrono::seconds>(current_time - 5 * 24h);
6004 : : }
6005 [ # # ]: 0 : AddAddressKnown(peer, addr);
6006 [ # # # # : 0 : if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
# # # # #
# ]
6007 : : // Do not process banned/discouraged addresses beyond remembering we received them
6008 : 0 : continue;
6009 : : }
6010 : 0 : ++num_proc;
6011 [ # # ]: 0 : const bool reachable{g_reachable_nets.Contains(addr)};
6012 [ # # # # : 0 : if (addr.nTime > current_time - 10min && !peer.m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) {
# # # # #
# ]
6013 : : // Relay to a limited number of other nodes
6014 [ # # ]: 0 : RelayAddress(pfrom.GetId(), addr, reachable);
6015 : : }
6016 : : // Do not store addresses outside our network
6017 [ # # ]: 0 : if (reachable) {
6018 [ # # ]: 0 : vAddrOk.push_back(addr);
6019 : : }
6020 : : }
6021 [ # # ]: 0 : peer.m_addr_processed += num_proc;
6022 : 0 : peer.m_addr_rate_limited += num_rate_limit;
6023 [ # # # # : 0 : LogDebug(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n",
# # # # ]
6024 : : vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
6025 : :
6026 [ # # ]: 0 : m_addrman.Add(vAddrOk, pfrom.addr, /*time_penalty=*/2h);
6027 [ # # # # ]: 0 : if (vAddr.size() < 1000) peer.m_getaddr_sent = false;
6028 : :
6029 : : // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements
6030 [ # # # # ]: 0 : if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
6031 [ # # # # : 0 : LogDebug(BCLog::NET, "addrfetch connection completed, %s", pfrom.DisconnectMsg());
# # # # ]
6032 : 0 : pfrom.fDisconnect = true;
6033 : : }
6034 : 0 : }
6035 : :
6036 : 16 : bool PeerManagerImpl::SendMessages(CNode& node)
6037 : : {
6038 : 16 : AssertLockNotHeld(m_tx_download_mutex);
6039 : 16 : AssertLockHeld(g_msgproc_mutex);
6040 : :
6041 : 16 : PeerRef maybe_peer{GetPeerRef(node.GetId())};
6042 [ + - ]: 16 : if (!maybe_peer) return false;
6043 [ + - ]: 16 : Peer& peer{*maybe_peer};
6044 : 16 : const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
6045 : :
6046 : : // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
6047 : : // disconnect misbehaving peers even before the version handshake is complete.
6048 [ + - + + ]: 16 : if (MaybeDiscourageAndDisconnect(node, peer)) return true;
6049 : :
6050 : : // Initiate version handshake for outbound connections
6051 [ + + + + ]: 12 : if (!node.IsInboundConn() && !peer.m_outbound_version_message_sent) {
6052 [ + - ]: 3 : PushNodeVersion(node, peer);
6053 : 3 : peer.m_outbound_version_message_sent = true;
6054 : : }
6055 : :
6056 : : // Don't send anything until the version handshake is complete
6057 [ + + + - ]: 12 : if (!node.fSuccessfullyConnected || node.fDisconnect)
6058 : 6 : return true;
6059 : :
6060 : 6 : const auto now{NodeClock::now()};
6061 : 6 : const auto current_time{GetTime<std::chrono::microseconds>()};
6062 : :
6063 : : // The logic below does not apply to private broadcast peers, so skip it.
6064 : : // Also in CConnman::PushMessage() we make sure that unwanted messages are
6065 : : // not sent. This here is just an optimization.
6066 [ - + ]: 6 : if (node.IsPrivateBroadcastConn()) {
6067 [ # # ]: 0 : if (node.m_connected + PRIVATE_BROADCAST_MAX_CONNECTION_LIFETIME < now) {
6068 [ # # # # : 0 : LogDebug(BCLog::PRIVBROADCAST, "Disconnecting: did not complete the transaction send within %d seconds, %s",
# # # # ]
6069 : : count_seconds(PRIVATE_BROADCAST_MAX_CONNECTION_LIFETIME), node.LogPeer());
6070 : 0 : node.fDisconnect = true;
6071 : : }
6072 : 0 : return true;
6073 : : }
6074 : :
6075 [ - + - - ]: 6 : if (node.IsAddrFetchConn() && now - node.m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
6076 [ # # # # : 0 : LogDebug(BCLog::NET, "addrfetch connection timeout, %s", node.DisconnectMsg());
# # # # ]
6077 : 0 : node.fDisconnect = true;
6078 : 0 : return true;
6079 : : }
6080 : :
6081 [ + - ]: 6 : MaybeSendPing(node, peer, now);
6082 : :
6083 : : // MaybeSendPing may have marked peer for disconnection
6084 [ + - ]: 6 : if (node.fDisconnect) return true;
6085 : :
6086 [ + - ]: 6 : MaybeSendAddr(node, peer, current_time);
6087 : :
6088 [ + - ]: 6 : MaybeSendSendHeaders(node, peer);
6089 : :
6090 [ + - ]: 6 : ProcessInvBacklog(now);
6091 : :
6092 : 6 : {
6093 [ + - ]: 6 : LOCK(cs_main);
6094 : :
6095 : 6 : CNodeState &state = *State(node.GetId());
6096 : :
6097 : : // Start block sync
6098 [ - + ]: 6 : if (m_chainman.m_best_header == nullptr) {
6099 [ # # # # ]: 0 : m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
6100 : : }
6101 : :
6102 : : // Determine whether we might try initial headers sync or parallel
6103 : : // block download from this peer -- this mostly affects behavior while
6104 : : // in IBD (once out of IBD, we sync from all peers).
6105 : 6 : bool sync_blocks_and_headers_from_peer = false;
6106 [ + + ]: 6 : if (state.fPreferredDownload) {
6107 : : sync_blocks_and_headers_from_peer = true;
6108 [ - + - - ]: 1 : } else if (CanServeBlocks(peer) && !node.IsAddrFetchConn()) {
6109 : : // Typically this is an inbound peer. If we don't have any outbound
6110 : : // peers, or if we aren't downloading any blocks from such peers,
6111 : : // then allow block downloads from this peer, too.
6112 : : // We prefer downloading blocks from outbound peers to avoid
6113 : : // putting undue load on (say) some home user who is just making
6114 : : // outbound connections to the network, but if our only source of
6115 : : // the latest blocks is from an inbound peer, we have to be sure to
6116 : : // eventually download it (and not just wait indefinitely for an
6117 : : // outbound peer to have it).
6118 [ # # # # ]: 0 : if (m_num_preferred_download_peers == 0 || mapBlocksInFlight.empty()) {
6119 : : sync_blocks_and_headers_from_peer = true;
6120 : : }
6121 : : }
6122 : :
6123 [ + + + + : 6 : if (!state.fSyncStarted && CanServeBlocks(peer) && !m_chainman.m_blockman.LoadingBlocks()) {
+ - ]
6124 : : // Only actively request headers from a single peer, unless we're close to today.
6125 [ + - - + : 2 : if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->Time() > NodeClock::now() - 24h) {
- - ]
6126 : 2 : const CBlockIndex* pindexStart = m_chainman.m_best_header;
6127 : : /* If possible, start at the block preceding the currently
6128 : : best known header. This ensures that we always get a
6129 : : non-empty list of headers back as long as the peer
6130 : : is up-to-date. With a non-empty response, we can initialise
6131 : : the peer's known best block. This wouldn't be possible
6132 : : if we requested starting at m_chainman.m_best_header and
6133 : : got back an empty response. */
6134 [ - + ]: 2 : if (pindexStart->pprev)
6135 : 0 : pindexStart = pindexStart->pprev;
6136 [ + - + - : 2 : if (MaybeSendGetHeaders(node, GetLocator(pindexStart), peer)) {
+ - ]
6137 [ + - + - : 2 : LogDebug(BCLog::NET, "initial getheaders (%d) to peer=%d", pindexStart->nHeight, node.GetId());
+ - ]
6138 : :
6139 : 2 : state.fSyncStarted = true;
6140 : 2 : peer.m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
6141 : : (
6142 : : // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
6143 : : // to maintain precision
6144 : 2 : std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
6145 : 2 : Ticks<std::chrono::seconds>(NodeClock::now() - m_chainman.m_best_header->Time()) / consensusParams.nPowTargetSpacing
6146 : 2 : );
6147 : 2 : nSyncStarted++;
6148 : : }
6149 : : }
6150 : : }
6151 : :
6152 : : //
6153 : : // Try sending block announcements via headers
6154 : : //
6155 : 6 : {
6156 : : // If we have no more than MAX_BLOCKS_TO_ANNOUNCE in our
6157 : : // list of block hashes we're relaying, and our peer wants
6158 : : // headers announcements, then find the first header
6159 : : // not yet known to our peer but would connect, and send.
6160 : : // If no header would connect, or if we have too many
6161 : : // blocks, or if the peer doesn't want headers, just
6162 : : // add all to the inv queue.
6163 [ + - ]: 6 : LOCK(peer.m_block_inv_mutex);
6164 : 6 : std::vector<CBlock> vHeaders;
6165 : 12 : bool fRevertToInv = ((!peer.m_prefers_headers &&
6166 [ + - - + : 6 : (!state.m_requested_hb_cmpctblocks || peer.m_blocks_for_headers_relay.size() > 1)) ||
- - - - ]
6167 [ # # # # ]: 0 : peer.m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE);
6168 : 6 : const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
6169 [ + - ]: 6 : ProcessBlockAvailability(node.GetId()); // ensure pindexBestKnownBlock is up-to-date
6170 : :
6171 [ - + ]: 6 : if (!fRevertToInv) {
6172 : 0 : bool fFoundStartingHeader = false;
6173 : : // Try to find first header that our peer doesn't have, and
6174 : : // then send all headers past that one. If we come across any
6175 : : // headers that aren't on m_chainman.ActiveChain(), give up.
6176 [ # # ]: 0 : for (const uint256& hash : peer.m_blocks_for_headers_relay) {
6177 [ # # ]: 0 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
6178 [ # # ]: 0 : assert(pindex);
6179 [ # # # # : 0 : if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
# # ]
6180 : : // Bail out if we reorged away from this block
6181 : : fRevertToInv = true;
6182 : : break;
6183 : : }
6184 [ # # # # ]: 0 : if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
6185 : : // This means that the list of blocks to announce don't
6186 : : // connect to each other.
6187 : : // This shouldn't really be possible to hit during
6188 : : // regular operation (because reorgs should take us to
6189 : : // a chain that has some block not on the prior chain,
6190 : : // which should be caught by the prior check), but one
6191 : : // way this could happen is by using invalidateblock /
6192 : : // reconsiderblock repeatedly on the tip, causing it to
6193 : : // be added multiple times to m_blocks_for_headers_relay.
6194 : : // Robustly deal with this rare situation by reverting
6195 : : // to an inv.
6196 : : fRevertToInv = true;
6197 : : break;
6198 : : }
6199 : 0 : pBestIndex = pindex;
6200 [ # # ]: 0 : if (fFoundStartingHeader) {
6201 : : // add this to the headers message
6202 [ # # ]: 0 : vHeaders.emplace_back(pindex->GetBlockHeader());
6203 [ # # # # ]: 0 : } else if (PeerHasHeader(&state, pindex)) {
6204 : 0 : continue; // keep looking for the first new block
6205 [ # # # # : 0 : } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
# # ]
6206 : : // Peer doesn't have this header but they do have the prior one.
6207 : : // Start sending headers.
6208 : 0 : fFoundStartingHeader = true;
6209 [ # # ]: 0 : vHeaders.emplace_back(pindex->GetBlockHeader());
6210 : : } else {
6211 : : // Peer doesn't have this header or the prior one -- nothing will
6212 : : // connect, so bail out.
6213 : : fRevertToInv = true;
6214 : : break;
6215 : : }
6216 : : }
6217 : : }
6218 [ # # # # ]: 0 : if (!fRevertToInv && !vHeaders.empty()) {
6219 [ # # # # : 0 : if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
# # ]
6220 : : // We only send up to 1 block as header-and-ids, as otherwise
6221 : : // probably means we're doing an initial-ish-sync or they're slow
6222 [ # # # # : 0 : LogDebug(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
# # # # #
# ]
6223 : : vHeaders.front().GetHash().ToString(), node.GetId());
6224 : :
6225 : 0 : std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
6226 : 0 : {
6227 [ # # ]: 0 : LOCK(m_most_recent_block_mutex);
6228 [ # # ]: 0 : if (m_most_recent_block_hash == pBestIndex->GetBlockHash()) {
6229 [ # # # # ]: 0 : cached_cmpctblock_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, *m_most_recent_compact_block);
6230 : : }
6231 : 0 : }
6232 [ # # ]: 0 : if (cached_cmpctblock_msg.has_value()) {
6233 [ # # ]: 0 : PushMessage(node, std::move(cached_cmpctblock_msg.value()));
6234 : : } else {
6235 : 0 : CBlock block;
6236 [ # # ]: 0 : const bool ret{m_chainman.m_blockman.ReadBlock(block, *pBestIndex)};
6237 [ # # ]: 0 : assert(ret);
6238 [ # # ]: 0 : CBlockHeaderAndShortTxIDs cmpctblock{block, m_rng.rand64()};
6239 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::CMPCTBLOCK, cmpctblock);
6240 : 0 : }
6241 [ # # ]: 0 : state.pindexBestHeaderSent = pBestIndex;
6242 [ # # ]: 0 : } else if (peer.m_prefers_headers) {
6243 [ # # ]: 0 : if (vHeaders.size() > 1) {
6244 [ # # # # : 0 : LogDebug(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
# # # # #
# # # #
# ]
6245 : : vHeaders.size(),
6246 : : vHeaders.front().GetHash().ToString(),
6247 : : vHeaders.back().GetHash().ToString(), node.GetId());
6248 : : } else {
6249 [ # # # # : 0 : LogDebug(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
# # # # #
# ]
6250 : : vHeaders.front().GetHash().ToString(), node.GetId());
6251 : : }
6252 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders));
6253 : 0 : state.pindexBestHeaderSent = pBestIndex;
6254 : : } else
6255 : : fRevertToInv = true;
6256 : : }
6257 [ + - ]: 6 : if (fRevertToInv) {
6258 : : // If falling back to using an inv, just try to inv the tip.
6259 : : // The last entry in m_blocks_for_headers_relay was our tip at some point
6260 : : // in the past.
6261 [ - + ]: 6 : if (!peer.m_blocks_for_headers_relay.empty()) {
6262 : 0 : const uint256& hashToAnnounce = peer.m_blocks_for_headers_relay.back();
6263 [ # # ]: 0 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
6264 [ # # ]: 0 : assert(pindex);
6265 : :
6266 : : // Warn if we're announcing a block that is not on the main chain.
6267 : : // This should be very rare and could be optimized out.
6268 : : // Just log for now.
6269 [ # # # # : 0 : if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
# # ]
6270 [ # # # # : 0 : LogDebug(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
# # # # #
# # # #
# ]
6271 : : hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString());
6272 : : }
6273 : :
6274 : : // If the peer's chain has this block, don't inv it back.
6275 [ # # # # ]: 0 : if (!PeerHasHeader(&state, pindex)) {
6276 [ # # ]: 0 : peer.m_blocks_for_inv_relay.push_back(hashToAnnounce);
6277 [ # # # # : 0 : LogDebug(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
# # # # ]
6278 : : node.GetId(), hashToAnnounce.ToString());
6279 : : }
6280 : : }
6281 : : }
6282 [ - + ]: 6 : peer.m_blocks_for_headers_relay.clear();
6283 [ + - ]: 6 : }
6284 : :
6285 : : //
6286 : : // Message: inventory
6287 : : //
6288 : 6 : std::vector<CInv> vInv;
6289 : 6 : {
6290 [ + - ]: 6 : LOCK(peer.m_block_inv_mutex);
6291 [ - + + - ]: 6 : vInv.reserve(peer.m_blocks_for_inv_relay.size());
6292 : :
6293 : : // Add blocks
6294 [ - + ]: 6 : for (const uint256& hash : peer.m_blocks_for_inv_relay) {
6295 [ # # ]: 0 : vInv.emplace_back(MSG_BLOCK, hash);
6296 [ # # # # ]: 0 : if (vInv.size() == MAX_INV_SZ) {
6297 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::INV, vInv);
6298 [ # # ]: 0 : vInv.clear();
6299 : : }
6300 : : }
6301 [ - + + - ]: 6 : peer.m_blocks_for_inv_relay.clear();
6302 : 0 : }
6303 : :
6304 [ + - + + ]: 6 : if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
6305 [ + - ]: 5 : LOCK(tx_relay->m_tx_inventory_mutex);
6306 : : // Check whether periodic sends should happen
6307 [ + + ]: 5 : bool fSendTrickle = node.HasPermission(NetPermissionFlags::NoBan);
6308 [ + + ]: 5 : if (tx_relay->m_next_inv_send_time < current_time) {
6309 : 4 : fSendTrickle = true;
6310 [ - + ]: 4 : if (node.IsInboundConn()) {
6311 [ # # ]: 0 : tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL, node.m_network_key);
6312 : : } else {
6313 : 4 : tx_relay->m_next_inv_send_time = current_time + m_rng.rand_exp_duration(OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
6314 : : }
6315 : : }
6316 : :
6317 : : // Time to send but the peer has requested we not relay transactions.
6318 [ - + ]: 5 : if (fSendTrickle) {
6319 [ + - ]: 4 : LOCK(tx_relay->m_bloom_filter_mutex);
6320 [ - + - - : 4 : if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear();
+ - ]
6321 : 4 : }
6322 : :
6323 : : // Respond to BIP35 mempool requests
6324 [ + - - + ]: 4 : if (fSendTrickle && tx_relay->m_send_mempool) {
6325 [ # # ]: 0 : auto vtxinfo = m_mempool.infoAll();
6326 : :
6327 : : // Ensure we'll respond to GETDATA requests for anything we're about to announce
6328 [ # # # # ]: 0 : tx_relay->m_last_inv_sequence = WITH_LOCK(m_mempool.cs, return m_mempool.GetSequence());
6329 : :
6330 : 0 : tx_relay->m_send_mempool = false;
6331 [ # # ]: 0 : const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
6332 : :
6333 : : // we'll send everything in the mempool momentarily, so this is redundant
6334 [ # # ]: 0 : tx_relay->m_tx_inventory_to_send.clear();
6335 : :
6336 [ # # ]: 0 : LOCK(tx_relay->m_bloom_filter_mutex);
6337 : :
6338 [ # # ]: 0 : for (const auto& txinfo : vtxinfo) {
6339 [ # # ]: 0 : const Txid& txid{txinfo.tx->GetHash()};
6340 [ # # ]: 0 : const Wtxid& wtxid{txinfo.tx->GetWitnessHash()};
6341 [ # # ]: 0 : const auto inv = peer.m_wtxid_relay ?
6342 : : CInv{MSG_WTX, wtxid.ToUint256()} :
6343 [ # # # # ]: 0 : CInv{MSG_TX, txid.ToUint256()};
6344 : :
6345 : : // Don't send transactions that peers will not put into their mempool
6346 [ # # # # ]: 0 : if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
6347 : 0 : continue;
6348 : : }
6349 [ # # ]: 0 : if (tx_relay->m_bloom_filter) {
6350 [ # # # # ]: 0 : if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
6351 : : }
6352 [ # # ]: 0 : tx_relay->m_tx_inventory_known_filter.insert(inv.hash);
6353 [ # # ]: 0 : vInv.push_back(inv);
6354 [ # # # # ]: 0 : if (vInv.size() == MAX_INV_SZ) {
6355 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::INV, vInv);
6356 [ # # ]: 0 : vInv.clear();
6357 : : }
6358 : : }
6359 : 0 : }
6360 : :
6361 : : // Determine transactions to relay
6362 : 4 : if (fSendTrickle) {
6363 : : // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
6364 : : // (sorted from higher priority to lowest, skipping low fee)
6365 [ + - ]: 4 : const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
6366 : :
6367 : 8 : auto inv_tx = [&]() EXCLUSIVE_LOCKS_REQUIRED(tx_relay->m_tx_inventory_mutex) {
6368 : 4 : auto& invs = tx_relay->m_tx_inventory_to_send;
6369 : 4 : std::vector<CTransactionRef> res;
6370 : :
6371 [ - + - + ]: 4 : if (invs.size() == 0) return res;
6372 : :
6373 : : // if previous allocations were excessive, shrink to the current size
6374 [ # # # # ]: 0 : if (invs.capacity() > 2 * invs.size()) invs.shrink_to_fit();
6375 : :
6376 [ # # ]: 0 : LOCK(m_mempool.cs);
6377 [ # # # # ]: 0 : auto txiters = m_mempool.ExtractBestByMiningScoreWithTopology(invs, invs.size());
6378 [ # # # # ]: 0 : res.reserve(txiters.size());
6379 [ # # ]: 0 : for (auto txiter : txiters) {
6380 [ # # # # : 0 : if (txiter->GetFee() < filterrate.GetFee(txiter->GetTxSize())) {
# # ]
6381 : 0 : continue; // higher feerate CPFP txs may follow, so just skip, don't stop
6382 : : }
6383 [ # # # # : 0 : res.push_back(txiter->GetSharedTx());
# # ]
6384 : : }
6385 : : // Ensure we'll respond to GETDATA requests for anything we're about to announce
6386 : 0 : tx_relay->m_last_inv_sequence = m_mempool.GetSequence();
6387 : 0 : return res;
6388 [ + - - - ]: 4 : }();
6389 : :
6390 [ + - ]: 4 : LOCK(tx_relay->m_bloom_filter_mutex);
6391 [ - + - + : 4 : vInv.reserve(std::min<size_t>(MAX_INV_SZ, vInv.size() + inv_tx.size()));
- + + - ]
6392 [ - + ]: 4 : for (auto& tx : inv_tx) {
6393 : : // `TxRelay::m_tx_inventory_known_filter` contains either txids or wtxids
6394 : : // depending on whether our peer supports wtxid-relay. Therefore, first
6395 : : // construct the inv and then use its hash for the filter check.
6396 [ # # ]: 0 : const auto inv = peer.m_wtxid_relay ?
6397 [ # # ]: 0 : CInv{MSG_WTX, tx->GetWitnessHash().ToUint256()} :
6398 [ # # # # ]: 0 : CInv{MSG_TX, tx->GetHash().ToUint256()};
6399 : : // Check if not in the filter already
6400 [ # # # # ]: 0 : if (tx_relay->m_tx_inventory_known_filter.contains(inv.hash)) {
6401 : 0 : continue;
6402 : : }
6403 [ # # # # : 0 : if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*tx)) continue;
# # ]
6404 : : // Send
6405 [ # # ]: 0 : vInv.push_back(inv);
6406 [ # # # # ]: 0 : if (vInv.size() == MAX_INV_SZ) {
6407 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::INV, vInv);
6408 [ # # ]: 0 : vInv.clear();
6409 : : }
6410 [ # # ]: 0 : tx_relay->m_tx_inventory_known_filter.insert(inv.hash);
6411 : : }
6412 : 4 : }
6413 : 5 : }
6414 [ - + ]: 6 : if (!vInv.empty())
6415 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::INV, vInv);
6416 : :
6417 : : // Detect whether we're stalling
6418 [ - + ]: 6 : auto stalling_timeout = m_block_stalling_timeout.load();
6419 [ - + - - ]: 6 : if (state.m_stalling_since.count() && state.m_stalling_since < current_time - stalling_timeout) {
6420 : : // Stalling only triggers when the block download window cannot move. During normal steady state,
6421 : : // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
6422 : : // should only happen during initial block download.
6423 [ # # # # ]: 0 : LogInfo("Peer is stalling block download, %s", node.DisconnectMsg());
6424 [ # # ]: 0 : node.fDisconnect = true;
6425 : : // Increase timeout for the next peer so that we don't disconnect multiple peers if our own
6426 : : // bandwidth is insufficient.
6427 [ # # ]: 0 : const auto new_timeout = std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX);
6428 [ # # # # ]: 0 : if (stalling_timeout != new_timeout && m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) {
6429 [ # # # # : 0 : LogDebug(BCLog::NET, "Increased stalling timeout temporarily to %d seconds\n", count_seconds(new_timeout));
# # ]
6430 : : }
6431 : 0 : return true;
6432 : : }
6433 : : // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N)
6434 : : // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
6435 : : // We compensate for other peers to prevent killing off peers due to our own downstream link
6436 : : // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
6437 : : // to unreasonably increase our timeout.
6438 [ - + ]: 6 : if (state.vBlocksInFlight.size() > 0) {
6439 : 0 : QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
6440 : 0 : int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1;
6441 [ # # ]: 0 : if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
6442 [ # # # # : 0 : LogInfo("Timeout downloading block %s, %s", queuedBlock.pindex->GetBlockHash().ToString(), node.DisconnectMsg());
# # ]
6443 : 0 : node.fDisconnect = true;
6444 : 0 : return true;
6445 : : }
6446 : : }
6447 : : // Check for headers sync timeouts
6448 [ + + + - ]: 6 : if (state.fSyncStarted && peer.m_headers_sync_timeout < std::chrono::microseconds::max()) {
6449 : : // Detect whether this is a stalling initial-headers-sync peer
6450 [ + - ]: 5 : if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {
6451 [ - + - - : 5 : if (current_time > peer.m_headers_sync_timeout && nSyncStarted == 1 && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)) {
- - ]
6452 : : // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
6453 : : // and we have others we could be using instead.
6454 : : // Note: If all our peers are inbound, then we won't
6455 : : // disconnect our sync peer for stalling; we have bigger
6456 : : // problems if we can't get any outbound peers.
6457 [ # # ]: 0 : if (!node.HasPermission(NetPermissionFlags::NoBan)) {
6458 [ # # # # ]: 0 : LogInfo("Timeout downloading headers, %s", node.DisconnectMsg());
6459 : 0 : node.fDisconnect = true;
6460 : 0 : return true;
6461 : : } else {
6462 [ # # # # ]: 0 : LogInfo("Timeout downloading headers from noban peer, not %s", node.DisconnectMsg());
6463 : : // Reset the headers sync state so that we have a
6464 : : // chance to try downloading from a different peer.
6465 : : // Note: this will also result in at least one more
6466 : : // getheaders message to be sent to
6467 : : // this peer (eventually).
6468 : 0 : state.fSyncStarted = false;
6469 : 0 : nSyncStarted--;
6470 : 0 : peer.m_headers_sync_timeout = 0us;
6471 : : }
6472 : : }
6473 : : } else {
6474 : : // After we've caught up once, reset the timeout so we can't trigger
6475 : : // disconnect later.
6476 : 0 : peer.m_headers_sync_timeout = std::chrono::microseconds::max();
6477 : : }
6478 : : }
6479 : :
6480 : : // Check that outbound peers have reasonable chains
6481 : : // GetTime() is used by this anti-DoS logic so we can test this using mocktime
6482 [ + - ]: 6 : ConsiderEviction(node, peer, GetTime<std::chrono::seconds>());
6483 : :
6484 : : //
6485 : : // Message: getdata (blocks)
6486 : : //
6487 : 6 : std::vector<CInv> vGetData;
6488 [ + + + - : 6 : if (CanServeBlocks(peer) && ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(peer)) || !m_chainman.IsInitialBlockDownload()) && state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
- + - - +
- ]
6489 : 5 : std::vector<const CBlockIndex*> vToDownload;
6490 : 5 : NodeId staller = -1;
6491 : 5 : auto get_inflight_budget = [&state]() {
6492 : 10 : return std::max(0, MAX_BLOCKS_IN_TRANSIT_PER_PEER - static_cast<int>(state.vBlocksInFlight.size()));
6493 : 5 : };
6494 : :
6495 : : // If there are multiple chainstates, download blocks for the
6496 : : // current chainstate first, to prioritize getting to network tip
6497 : : // before downloading historical blocks.
6498 [ - + + - ]: 5 : FindNextBlocksToDownload(peer, get_inflight_budget(), vToDownload, staller);
6499 [ + - ]: 5 : auto historical_blocks{m_chainman.GetHistoricalBlockRange()};
6500 [ - + - - ]: 5 : if (historical_blocks && !IsLimitedPeer(peer)) {
6501 : : // If the first needed historical block is not an ancestor of the last,
6502 : : // we need to start requesting blocks from their last common ancestor.
6503 [ # # ]: 0 : const CBlockIndex* from_tip = LastCommonAncestor(historical_blocks->first, historical_blocks->second);
6504 [ # # ]: 0 : TryDownloadingHistoricalBlocks(
6505 : : peer,
6506 [ # # ]: 0 : get_inflight_budget(),
6507 [ # # ]: 0 : vToDownload, from_tip, historical_blocks->second);
6508 : : }
6509 [ - + ]: 5 : for (const CBlockIndex *pindex : vToDownload) {
6510 : 0 : uint32_t nFetchFlags = GetFetchFlags(peer);
6511 [ # # ]: 0 : vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash());
6512 [ # # ]: 0 : BlockRequested(node.GetId(), *pindex);
6513 [ # # # # : 0 : LogDebug(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
# # # # ]
6514 : : pindex->nHeight, node.GetId());
6515 : : }
6516 [ + - - + ]: 5 : if (state.vBlocksInFlight.empty() && staller != -1) {
6517 [ # # ]: 0 : if (State(staller)->m_stalling_since == 0us) {
6518 : 0 : State(staller)->m_stalling_since = current_time;
6519 [ - - - - : 5 : LogDebug(BCLog::NET, "Stall started peer=%d\n", staller);
- - ]
6520 : : }
6521 : : }
6522 : 5 : }
6523 : :
6524 : : //
6525 : : // Message: getdata (transactions)
6526 : : //
6527 : 6 : {
6528 [ + - ]: 6 : LOCK(m_tx_download_mutex);
6529 [ + - - + ]: 6 : for (const GenTxid& gtxid : m_txdownloadman.GetRequestsToSend(node.GetId(), current_time)) {
6530 [ # # # # : 0 : vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(peer)), gtxid.ToUint256());
# # # ]
6531 [ # # # # ]: 0 : if (vGetData.size() >= MAX_GETDATA_SZ) {
6532 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::GETDATA, vGetData);
6533 [ # # ]: 0 : vGetData.clear();
6534 : : }
6535 [ + - ]: 6 : }
6536 : 0 : }
6537 : :
6538 [ - + ]: 6 : if (!vGetData.empty())
6539 [ # # # # ]: 0 : MakeAndPushMessage(node, NetMsgType::GETDATA, vGetData);
6540 [ + - - - ]: 6 : } // release cs_main
6541 [ + - ]: 6 : MaybeSendFeefilter(node, peer, current_time);
6542 : : return true;
6543 : 16 : }
|