/Users/eugenesiegel/btc/bitcoin/src/net_processing.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright (c) 2009-2010 Satoshi Nakamoto |
2 | | // Copyright (c) 2009-present The Bitcoin Core developers |
3 | | // Distributed under the MIT software license, see the accompanying |
4 | | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
5 | | |
6 | | #include <net_processing.h> |
7 | | |
8 | | #include <addrman.h> |
9 | | #include <arith_uint256.h> |
10 | | #include <banman.h> |
11 | | #include <blockencodings.h> |
12 | | #include <blockfilter.h> |
13 | | #include <chain.h> |
14 | | #include <chainparams.h> |
15 | | #include <common/bloom.h> |
16 | | #include <consensus/amount.h> |
17 | | #include <consensus/params.h> |
18 | | #include <consensus/validation.h> |
19 | | #include <core_memusage.h> |
20 | | #include <crypto/siphash.h> |
21 | | #include <deploymentstatus.h> |
22 | | #include <flatfile.h> |
23 | | #include <headerssync.h> |
24 | | #include <index/blockfilterindex.h> |
25 | | #include <kernel/chain.h> |
26 | | #include <logging.h> |
27 | | #include <merkleblock.h> |
28 | | #include <net.h> |
29 | | #include <net_permissions.h> |
30 | | #include <netaddress.h> |
31 | | #include <netbase.h> |
32 | | #include <netmessagemaker.h> |
33 | | #include <node/blockstorage.h> |
34 | | #include <node/connection_types.h> |
35 | | #include <node/protocol_version.h> |
36 | | #include <node/timeoffsets.h> |
37 | | #include <node/txdownloadman.h> |
38 | | #include <node/txorphanage.h> |
39 | | #include <node/txreconciliation.h> |
40 | | #include <node/warnings.h> |
41 | | #include <policy/feerate.h> |
42 | | #include <policy/fees.h> |
43 | | #include <policy/packages.h> |
44 | | #include <policy/policy.h> |
45 | | #include <primitives/block.h> |
46 | | #include <primitives/transaction.h> |
47 | | #include <protocol.h> |
48 | | #include <random.h> |
49 | | #include <scheduler.h> |
50 | | #include <script/script.h> |
51 | | #include <serialize.h> |
52 | | #include <span.h> |
53 | | #include <streams.h> |
54 | | #include <sync.h> |
55 | | #include <tinyformat.h> |
56 | | #include <txmempool.h> |
57 | | #include <uint256.h> |
58 | | #include <util/check.h> |
59 | | #include <util/strencodings.h> |
60 | | #include <util/time.h> |
61 | | #include <util/trace.h> |
62 | | #include <validation.h> |
63 | | |
64 | | #include <algorithm> |
65 | | #include <array> |
66 | | #include <atomic> |
67 | | #include <compare> |
68 | | #include <cstddef> |
69 | | #include <deque> |
70 | | #include <exception> |
71 | | #include <functional> |
72 | | #include <future> |
73 | | #include <initializer_list> |
74 | | #include <iterator> |
75 | | #include <limits> |
76 | | #include <list> |
77 | | #include <map> |
78 | | #include <memory> |
79 | | #include <optional> |
80 | | #include <queue> |
81 | | #include <ranges> |
82 | | #include <ratio> |
83 | | #include <set> |
84 | | #include <span> |
85 | | #include <typeinfo> |
86 | | #include <utility> |
87 | | |
88 | | using namespace util::hex_literals; |
89 | | |
90 | | TRACEPOINT_SEMAPHORE(net, inbound_message); |
91 | | TRACEPOINT_SEMAPHORE(net, misbehaving_connection); |
92 | | |
93 | | /** Headers download timeout. |
94 | | * Timeout = base + per_header * (expected number of headers) */ |
95 | | static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min; |
96 | | static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms; |
97 | | /** How long to wait for a peer to respond to a getheaders request */ |
98 | | static constexpr auto HEADERS_RESPONSE_TIME{2min}; |
99 | | /** Protect at least this many outbound peers from disconnection due to slow/ |
100 | | * behind headers chain. |
101 | | */ |
102 | | static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4; |
103 | | /** Timeout for (unprotected) outbound peers to sync to our chainwork */ |
104 | | static constexpr auto CHAIN_SYNC_TIMEOUT{20min}; |
105 | | /** How frequently to check for stale tips */ |
106 | | static constexpr auto STALE_CHECK_INTERVAL{10min}; |
107 | | /** How frequently to check for extra outbound peers and disconnect */ |
108 | | static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s}; |
109 | | /** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */ |
110 | | static constexpr auto MINIMUM_CONNECT_TIME{30s}; |
111 | | /** SHA256("main address relay")[0:8] */ |
112 | | static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; |
113 | | /// Age after which a stale block will no longer be served if requested as |
114 | | /// protection against fingerprinting. Set to one month, denominated in seconds. |
115 | | static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60; |
116 | | /// Age after which a block is considered historical for purposes of rate |
117 | | /// limiting block relay. Set to one week, denominated in seconds. |
118 | | static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60; |
119 | | /** Time between pings automatically sent out for latency probing and keepalive */ |
120 | | static constexpr auto PING_INTERVAL{2min}; |
121 | | /** The maximum number of entries in a locator */ |
122 | | static const unsigned int MAX_LOCATOR_SZ = 101; |
123 | | /** The maximum number of entries in an 'inv' protocol message */ |
124 | | static const unsigned int MAX_INV_SZ = 50000; |
125 | | /** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */ |
126 | | static const unsigned int MAX_GETDATA_SZ = 1000; |
127 | | /** Number of blocks that can be requested at any given time from a single peer. */ |
128 | | static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16; |
129 | | /** Default time during which a peer must stall block download progress before being disconnected. |
130 | | * the actual timeout is increased temporarily if peers are disconnected for hitting the timeout */ |
131 | | static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT{2s}; |
132 | | /** Maximum timeout for stalling block download. */ |
133 | | static constexpr auto BLOCK_STALLING_TIMEOUT_MAX{64s}; |
134 | | /** Maximum depth of blocks we're willing to serve as compact blocks to peers |
135 | | * when requested. For older blocks, a regular BLOCK response will be sent. */ |
136 | | static const int MAX_CMPCTBLOCK_DEPTH = 5; |
137 | | /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */ |
138 | | static const int MAX_BLOCKTXN_DEPTH = 10; |
139 | | static_assert(MAX_BLOCKTXN_DEPTH <= MIN_BLOCKS_TO_KEEP, "MAX_BLOCKTXN_DEPTH too high"); |
140 | | /** Size of the "block download window": how far ahead of our current height do we fetch? |
141 | | * Larger windows tolerate larger download speed differences between peer, but increase the potential |
142 | | * degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably |
143 | | * want to make this a per-peer adaptive value at some point. */ |
144 | | static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024; |
145 | | /** Block download timeout base, expressed in multiples of the block interval (i.e. 10 min) */ |
146 | | static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1; |
147 | | /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */ |
148 | | static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5; |
149 | | /** Maximum number of headers to announce when relaying blocks with headers message.*/ |
150 | | static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8; |
151 | | /** Minimum blocks required to signal NODE_NETWORK_LIMITED */ |
152 | | static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288; |
153 | | /** Window, in blocks, for connecting to NODE_NETWORK_LIMITED peers */ |
154 | | static const unsigned int NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS = 144; |
155 | | /** Average delay between local address broadcasts */ |
156 | | static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h}; |
157 | | /** Average delay between peer address broadcasts */ |
158 | | static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s}; |
159 | | /** Delay between rotating the peers we relay a particular address to */ |
160 | | static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h}; |
161 | | /** Average delay between trickled inventory transmissions for inbound peers. |
162 | | * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */ |
163 | | static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s}; |
164 | | /** Average delay between trickled inventory transmissions for outbound peers. |
165 | | * Use a smaller delay as there is less privacy concern for them. |
166 | | * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */ |
167 | | static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s}; |
168 | | /** Maximum rate of inventory items to send per second. |
169 | | * Limits the impact of low-fee transaction floods. */ |
170 | | static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7; |
171 | | /** Target number of tx inventory items to send per transmission. */ |
172 | | static constexpr unsigned int INVENTORY_BROADCAST_TARGET = INVENTORY_BROADCAST_PER_SECOND * count_seconds(INBOUND_INVENTORY_BROADCAST_INTERVAL); |
173 | | /** Maximum number of inventory items to send per transmission. */ |
174 | | static constexpr unsigned int INVENTORY_BROADCAST_MAX = 1000; |
175 | | static_assert(INVENTORY_BROADCAST_MAX >= INVENTORY_BROADCAST_TARGET, "INVENTORY_BROADCAST_MAX too low"); |
176 | | static_assert(INVENTORY_BROADCAST_MAX <= node::MAX_PEER_TX_ANNOUNCEMENTS, "INVENTORY_BROADCAST_MAX too high"); |
177 | | /** Average delay between feefilter broadcasts in seconds. */ |
178 | | static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min}; |
179 | | /** Maximum feefilter broadcast delay after significant change. */ |
180 | | static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min}; |
181 | | /** Maximum number of compact filters that may be requested with one getcfilters. See BIP 157. */ |
182 | | static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000; |
183 | | /** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */ |
184 | | static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000; |
185 | | /** the maximum percentage of addresses from our addrman to return in response to a getaddr message. */ |
186 | | static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23; |
187 | | /** The maximum number of address records permitted in an ADDR message. */ |
188 | | static constexpr size_t MAX_ADDR_TO_SEND{1000}; |
189 | | /** The maximum rate of address records we're willing to process on average. Can be bypassed using |
190 | | * the NetPermissionFlags::Addr permission. */ |
191 | | static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1}; |
192 | | /** The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND |
193 | | * based increments won't go above this, but the MAX_ADDR_TO_SEND increment following GETADDR |
194 | | * is exempt from this limit). */ |
195 | | static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND}; |
196 | | |
197 | | // Internal stuff |
198 | | namespace { |
199 | | /** Blocks that are in flight, and that are in the queue to be downloaded. */ |
200 | | struct QueuedBlock { |
201 | | /** BlockIndex. We must have this since we only request blocks when we've already validated the header. */ |
202 | | const CBlockIndex* pindex; |
203 | | /** Optional, used for CMPCTBLOCK downloads */ |
204 | | std::unique_ptr<PartiallyDownloadedBlock> partialBlock; |
205 | | }; |
206 | | |
207 | | /** |
208 | | * Data structure for an individual peer. This struct is not protected by |
209 | | * cs_main since it does not contain validation-critical data. |
210 | | * |
211 | | * Memory is owned by shared pointers and this object is destructed when |
212 | | * the refcount drops to zero. |
213 | | * |
214 | | * Mutexes inside this struct must not be held when locking m_peer_mutex. |
215 | | * |
216 | | * TODO: move most members from CNodeState to this structure. |
217 | | * TODO: move remaining application-layer data members from CNode to this structure. |
218 | | */ |
219 | | struct Peer { |
220 | | /** Same id as the CNode object for this peer */ |
221 | | const NodeId m_id{0}; |
222 | | |
223 | | /** Services we offered to this peer. |
224 | | * |
225 | | * This is supplied by CConnman during peer initialization. It's const |
226 | | * because there is no protocol defined for renegotiating services |
227 | | * initially offered to a peer. The set of local services we offer should |
228 | | * not change after initialization. |
229 | | * |
230 | | * An interesting example of this is NODE_NETWORK and initial block |
231 | | * download: a node which starts up from scratch doesn't have any blocks |
232 | | * to serve, but still advertises NODE_NETWORK because it will eventually |
233 | | * fulfill this role after IBD completes. P2P code is written in such a |
234 | | * way that it can gracefully handle peers who don't make good on their |
235 | | * service advertisements. */ |
236 | | const ServiceFlags m_our_services; |
237 | | /** Services this peer offered to us. */ |
238 | | std::atomic<ServiceFlags> m_their_services{NODE_NONE}; |
239 | | |
240 | | //! Whether this peer is an inbound connection |
241 | | const bool m_is_inbound; |
242 | | |
243 | | /** Protects misbehavior data members */ |
244 | | Mutex m_misbehavior_mutex; |
245 | | /** Whether this peer should be disconnected and marked as discouraged (unless it has NetPermissionFlags::NoBan permission). */ |
246 | | bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false}; |
247 | | |
248 | | /** Protects block inventory data members */ |
249 | | Mutex m_block_inv_mutex; |
250 | | /** List of blocks that we'll announce via an `inv` message. |
251 | | * There is no final sorting before sending, as they are always sent |
252 | | * immediately and in the order requested. */ |
253 | | std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex); |
254 | | /** Unfiltered list of blocks that we'd like to announce via a `headers` |
255 | | * message. If we can't announce via a `headers` message, we'll fall back to |
256 | | * announcing via `inv`. */ |
257 | | std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex); |
258 | | /** The final block hash that we sent in an `inv` message to this peer. |
259 | | * When the peer requests this block, we send an `inv` message to trigger |
260 | | * the peer to request the next sequence of block hashes. |
261 | | * Most peers use headers-first syncing, which doesn't use this mechanism */ |
262 | | uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {}; |
263 | | |
264 | | /** Set to true once initial VERSION message was sent (only relevant for outbound peers). */ |
265 | | bool m_outbound_version_message_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
266 | | |
267 | | /** This peer's reported block height when we connected */ |
268 | | std::atomic<int> m_starting_height{-1}; |
269 | | |
270 | | /** The pong reply we're expecting, or 0 if no pong expected. */ |
271 | | std::atomic<uint64_t> m_ping_nonce_sent{0}; |
272 | | /** When the last ping was sent, or 0 if no ping was ever sent */ |
273 | | std::atomic<std::chrono::microseconds> m_ping_start{0us}; |
274 | | /** Whether a ping has been requested by the user */ |
275 | | std::atomic<bool> m_ping_queued{false}; |
276 | | |
277 | | /** Whether this peer relays txs via wtxid */ |
278 | | std::atomic<bool> m_wtxid_relay{false}; |
279 | | /** The feerate in the most recent BIP133 `feefilter` message sent to the peer. |
280 | | * It is *not* a p2p protocol violation for the peer to send us |
281 | | * transactions with a lower fee rate than this. See BIP133. */ |
282 | | CAmount m_fee_filter_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0}; |
283 | | /** Timestamp after which we will send the next BIP133 `feefilter` message |
284 | | * to the peer. */ |
285 | | std::chrono::microseconds m_next_send_feefilter GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0}; |
286 | | |
287 | | struct TxRelay { |
288 | | mutable RecursiveMutex m_bloom_filter_mutex; |
289 | | /** Whether we relay transactions to this peer. */ |
290 | | bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false}; |
291 | | /** A bloom filter for which transactions to announce to the peer. See BIP37. */ |
292 | | std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr}; |
293 | | |
294 | | mutable RecursiveMutex m_tx_inventory_mutex; |
295 | | /** A filter of all the (w)txids that the peer has announced to |
296 | | * us or we have announced to the peer. We use this to avoid announcing |
297 | | * the same (w)txid to a peer that already has the transaction. */ |
298 | | CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001}; |
299 | | /** Set of wtxids we still have to announce. For non-wtxid-relay peers, |
300 | | * we retrieve the txid from the corresponding mempool transaction when |
301 | | * constructing the `inv` message. We use the mempool to sort transactions |
302 | | * in dependency order before relay, so this does not have to be sorted. */ |
303 | | std::set<Wtxid> m_tx_inventory_to_send GUARDED_BY(m_tx_inventory_mutex); |
304 | | /** Whether the peer has requested us to send our complete mempool. Only |
305 | | * permitted if the peer has NetPermissionFlags::Mempool or we advertise |
306 | | * NODE_BLOOM. See BIP35. */ |
307 | | bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false}; |
308 | | /** The next time after which we will send an `inv` message containing |
309 | | * transaction announcements to this peer. */ |
310 | | std::chrono::microseconds m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){0}; |
311 | | /** The mempool sequence num at which we sent the last `inv` message to this peer. |
312 | | * Can relay txs with lower sequence numbers than this (see CTxMempool::info_for_relay). */ |
313 | | uint64_t m_last_inv_sequence GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1}; |
314 | | |
315 | | /** Minimum fee rate with which to filter transaction announcements to this node. See BIP133. */ |
316 | | std::atomic<CAmount> m_fee_filter_received{0}; |
317 | | }; |
318 | | |
319 | | /* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */ |
320 | | TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) |
321 | 56.3k | { |
322 | 56.3k | LOCK(m_tx_relay_mutex); Line | Count | Source | 259 | 56.3k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 56.3k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 56.3k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 56.3k | #define PASTE(x, y) x ## y |
|
|
|
|
323 | 56.3k | Assume(!m_tx_relay); Line | Count | Source | 118 | 56.3k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
324 | 56.3k | m_tx_relay = std::make_unique<Peer::TxRelay>(); |
325 | 56.3k | return m_tx_relay.get(); |
326 | 56.3k | }; |
327 | | |
328 | | TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) |
329 | 9.45M | { |
330 | 9.45M | return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get()); Line | Count | Source | 290 | 9.45M | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
331 | 9.45M | }; |
332 | | |
333 | | /** A vector of addresses to send to the peer, limited to MAX_ADDR_TO_SEND. */ |
334 | | std::vector<CAddress> m_addrs_to_send GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
335 | | /** Probabilistic filter to track recent addr messages relayed with this |
336 | | * peer. Used to avoid relaying redundant addresses to this peer. |
337 | | * |
338 | | * We initialize this filter for outbound peers (other than |
339 | | * block-relay-only connections) or when an inbound peer sends us an |
340 | | * address related message (ADDR, ADDRV2, GETADDR). |
341 | | * |
342 | | * Presence of this filter must correlate with m_addr_relay_enabled. |
343 | | **/ |
344 | | std::unique_ptr<CRollingBloomFilter> m_addr_known GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
345 | | /** Whether we are participating in address relay with this connection. |
346 | | * |
347 | | * We set this bool to true for outbound peers (other than |
348 | | * block-relay-only connections), or when an inbound peer sends us an |
349 | | * address related message (ADDR, ADDRV2, GETADDR). |
350 | | * |
351 | | * We use this bool to decide whether a peer is eligible for gossiping |
352 | | * addr messages. This avoids relaying to peers that are unlikely to |
353 | | * forward them, effectively blackholing self announcements. Reasons |
354 | | * peers might support addr relay on the link include that they connected |
355 | | * to us as a block-relay-only peer or they are a light client. |
356 | | * |
357 | | * This field must correlate with whether m_addr_known has been |
358 | | * initialized.*/ |
359 | | std::atomic_bool m_addr_relay_enabled{false}; |
360 | | /** Whether a getaddr request to this peer is outstanding. */ |
361 | | bool m_getaddr_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
362 | | /** Guards address sending timers. */ |
363 | | mutable Mutex m_addr_send_times_mutex; |
364 | | /** Time point to send the next ADDR message to this peer. */ |
365 | | std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0}; |
366 | | /** Time point to possibly re-announce our local address to this peer. */ |
367 | | std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0}; |
368 | | /** Whether the peer has signaled support for receiving ADDRv2 (BIP155) |
369 | | * messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */ |
370 | | std::atomic_bool m_wants_addrv2{false}; |
371 | | /** Whether this peer has already sent us a getaddr message. */ |
372 | | bool m_getaddr_recvd GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
373 | | /** Number of addresses that can be processed from this peer. Start at 1 to |
374 | | * permit self-announcement. */ |
375 | | double m_addr_token_bucket GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1.0}; |
376 | | /** When m_addr_token_bucket was last updated */ |
377 | | std::chrono::microseconds m_addr_token_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){GetTime<std::chrono::microseconds>()}; |
378 | | /** Total number of addresses that were dropped due to rate limiting. */ |
379 | | std::atomic<uint64_t> m_addr_rate_limited{0}; |
380 | | /** Total number of addresses that were processed (excludes rate-limited ones). */ |
381 | | std::atomic<uint64_t> m_addr_processed{0}; |
382 | | |
383 | | /** Whether we've sent this peer a getheaders in response to an inv prior to initial-headers-sync completing */ |
384 | | bool m_inv_triggered_getheaders_before_sync GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
385 | | |
386 | | /** Protects m_getdata_requests **/ |
387 | | Mutex m_getdata_requests_mutex; |
388 | | /** Work queue of items requested by this peer **/ |
389 | | std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex); |
390 | | |
391 | | /** Time of the last getheaders message to this peer */ |
392 | | NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){}; |
393 | | |
394 | | /** Protects m_headers_sync **/ |
395 | | Mutex m_headers_sync_mutex; |
396 | | /** Headers-sync state for this peer (eg for initial sync, or syncing large |
397 | | * reorgs) **/ |
398 | | std::unique_ptr<HeadersSyncState> m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex) GUARDED_BY(m_headers_sync_mutex) {}; |
399 | | |
400 | | /** Whether we've sent our peer a sendheaders message. **/ |
401 | | std::atomic<bool> m_sent_sendheaders{false}; |
402 | | |
403 | | /** When to potentially disconnect peer for stalling headers download */ |
404 | | std::chrono::microseconds m_headers_sync_timeout GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0us}; |
405 | | |
406 | | /** Whether this peer wants invs or headers (when possible) for block announcements */ |
407 | | bool m_prefers_headers GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
408 | | |
409 | | /** Time offset computed during the version handshake based on the |
410 | | * timestamp the peer sent in the version message. */ |
411 | | std::atomic<std::chrono::seconds> m_time_offset{0s}; |
412 | | |
413 | | explicit Peer(NodeId id, ServiceFlags our_services, bool is_inbound) |
414 | 116k | : m_id{id} |
415 | 116k | , m_our_services{our_services} |
416 | 116k | , m_is_inbound{is_inbound} |
417 | 116k | {} |
418 | | |
419 | | private: |
420 | | mutable Mutex m_tx_relay_mutex; |
421 | | |
422 | | /** Transaction relay data. May be a nullptr. */ |
423 | | std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex); |
424 | | }; |
425 | | |
426 | | using PeerRef = std::shared_ptr<Peer>; |
427 | | |
428 | | /** |
429 | | * Maintain validation-specific state about nodes, protected by cs_main, instead |
430 | | * by CNode's own locks. This simplifies asynchronous operation, where |
431 | | * processing of incoming data is done after the ProcessMessage call returns, |
432 | | * and we're no longer holding the node's locks. |
433 | | */ |
434 | | struct CNodeState { |
435 | | //! The best known block we know this peer has announced. |
436 | | const CBlockIndex* pindexBestKnownBlock{nullptr}; |
437 | | //! The hash of the last unknown block this peer has announced. |
438 | | uint256 hashLastUnknownBlock{}; |
439 | | //! The last full block we both have. |
440 | | const CBlockIndex* pindexLastCommonBlock{nullptr}; |
441 | | //! The best header we have sent our peer. |
442 | | const CBlockIndex* pindexBestHeaderSent{nullptr}; |
443 | | //! Whether we've started headers synchronization with this peer. |
444 | | bool fSyncStarted{false}; |
445 | | //! Since when we're stalling block download progress (in microseconds), or 0. |
446 | | std::chrono::microseconds m_stalling_since{0us}; |
447 | | std::list<QueuedBlock> vBlocksInFlight; |
448 | | //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty. |
449 | | std::chrono::microseconds m_downloading_since{0us}; |
450 | | //! Whether we consider this a preferred download peer. |
451 | | bool fPreferredDownload{false}; |
452 | | /** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */ |
453 | | bool m_requested_hb_cmpctblocks{false}; |
454 | | /** Whether this peer will send us cmpctblocks if we request them. */ |
455 | | bool m_provides_cmpctblocks{false}; |
456 | | |
457 | | /** State used to enforce CHAIN_SYNC_TIMEOUT and EXTRA_PEER_CHECK_INTERVAL logic. |
458 | | * |
459 | | * Both are only in effect for outbound, non-manual, non-protected connections. |
460 | | * Any peer protected (m_protect = true) is not chosen for eviction. A peer is |
461 | | * marked as protected if all of these are true: |
462 | | * - its connection type is IsBlockOnlyConn() == false |
463 | | * - it gave us a valid connecting header |
464 | | * - we haven't reached MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT yet |
465 | | * - its chain tip has at least as much work as ours |
466 | | * |
467 | | * CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip, |
468 | | * set a timeout CHAIN_SYNC_TIMEOUT in the future: |
469 | | * - If at timeout their best known block now has more work than our tip |
470 | | * when the timeout was set, then either reset the timeout or clear it |
471 | | * (after comparing against our current tip's work) |
472 | | * - If at timeout their best known block still has less work than our |
473 | | * tip did when the timeout was set, then send a getheaders message, |
474 | | * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future. |
475 | | * If their best known block is still behind when that new timeout is |
476 | | * reached, disconnect. |
477 | | * |
478 | | * EXTRA_PEER_CHECK_INTERVAL: after each interval, if we have too many outbound peers, |
479 | | * drop the outbound one that least recently announced us a new block. |
480 | | */ |
481 | | struct ChainSyncTimeoutState { |
482 | | //! A timeout used for checking whether our peer has sufficiently synced |
483 | | std::chrono::seconds m_timeout{0s}; |
484 | | //! A header with the work we require on our peer's chain |
485 | | const CBlockIndex* m_work_header{nullptr}; |
486 | | //! After timeout is reached, set to true after sending getheaders |
487 | | bool m_sent_getheaders{false}; |
488 | | //! Whether this peer is protected from disconnection due to a bad/slow chain |
489 | | bool m_protect{false}; |
490 | | }; |
491 | | |
492 | | ChainSyncTimeoutState m_chain_sync; |
493 | | |
494 | | //! Time of last new block announcement |
495 | | int64_t m_last_block_announcement{0}; |
496 | | }; |
497 | | |
498 | | class PeerManagerImpl final : public PeerManager |
499 | | { |
500 | | public: |
501 | | PeerManagerImpl(CConnman& connman, AddrMan& addrman, |
502 | | BanMan* banman, ChainstateManager& chainman, |
503 | | CTxMemPool& pool, node::Warnings& warnings, Options opts); |
504 | | |
505 | | /** Overridden from CValidationInterface. */ |
506 | | void ActiveTipChange(const CBlockIndex& new_tip, bool) override |
507 | | EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex); |
508 | | void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override |
509 | | EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex); |
510 | | void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override |
511 | | EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex); |
512 | | void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override |
513 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
514 | | void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) override |
515 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
516 | | void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override |
517 | | EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex); |
518 | | |
519 | | /** Implement NetEventsInterface */ |
520 | | void InitializeNode(const CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_tx_download_mutex); |
521 | | void FinalizeNode(const CNode& node) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, !m_tx_download_mutex); |
522 | | bool HasAllDesirableServiceFlags(ServiceFlags services) const override; |
523 | | bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override |
524 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex, !m_tx_download_mutex); |
525 | | bool SendMessages(CNode* pto) override |
526 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, g_msgproc_mutex, !m_tx_download_mutex); |
527 | | |
528 | | /** Implement PeerManager */ |
529 | | void StartScheduledTasks(CScheduler& scheduler) override; |
530 | | void CheckForStaleTipAndEvictPeers() override; |
531 | | std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) override |
532 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
533 | | bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
534 | | std::vector<node::TxOrphanage::OrphanInfo> GetOrphanTransactions() override EXCLUSIVE_LOCKS_REQUIRED(!m_tx_download_mutex); |
535 | | PeerManagerInfo GetInfo() const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
536 | | void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
537 | | void RelayTransaction(const Txid& txid, const Wtxid& wtxid) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
538 | | void SetBestBlock(int height, std::chrono::seconds time) override |
539 | 26.6k | { |
540 | 26.6k | m_best_height = height; |
541 | 26.6k | m_best_block_time = time; |
542 | 26.6k | }; |
543 | 0 | void UnitTestMisbehaving(NodeId peer_id) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), ""); }; Line | Count | Source | 106 | 0 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
544 | | void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, |
545 | | const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override |
546 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex, !m_tx_download_mutex); |
547 | | void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override; |
548 | | ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const override; |
549 | | |
550 | | private: |
551 | | /** Consider evicting an outbound peer based on the amount of time they've been behind our tip */ |
552 | | void ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_msgproc_mutex); |
553 | | |
554 | | /** If we have extra outbound peers, try to disconnect the one with the oldest block announcement */ |
555 | | void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
556 | | |
557 | | /** Retrieve unbroadcast transactions from the mempool and reattempt sending to peers */ |
558 | | void ReattemptInitialBroadcast(CScheduler& scheduler) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
559 | | |
560 | | /** Get a shared pointer to the Peer object. |
561 | | * May return an empty shared_ptr if the Peer object can't be found. */ |
562 | | PeerRef GetPeerRef(NodeId id) const EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
563 | | |
564 | | /** Get a shared pointer to the Peer object and remove it from m_peer_map. |
565 | | * May return an empty shared_ptr if the Peer object can't be found. */ |
566 | | PeerRef RemovePeer(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
567 | | |
568 | | /** Mark a peer as misbehaving, which will cause it to be disconnected and its |
569 | | * address discouraged. */ |
570 | | void Misbehaving(Peer& peer, const std::string& message); |
571 | | |
572 | | /** |
573 | | * Potentially mark a node discouraged based on the contents of a BlockValidationState object |
574 | | * |
575 | | * @param[in] via_compact_block this bool is passed in because net_processing should |
576 | | * punish peers differently depending on whether the data was provided in a compact |
577 | | * block message or not. If the compact block had a valid header, but contained invalid |
578 | | * txs, the peer should not be punished. See BIP 152. |
579 | | */ |
580 | | void MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state, |
581 | | bool via_compact_block, const std::string& message = "") |
582 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
583 | | |
584 | | /** Maybe disconnect a peer and discourage future connections from its address. |
585 | | * |
586 | | * @param[in] pnode The node to check. |
587 | | * @param[in] peer The peer object to check. |
588 | | * @return True if the peer was marked for disconnection in this function |
589 | | */ |
590 | | bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer); |
591 | | |
592 | | /** Handle a transaction whose result was not MempoolAcceptResult::ResultType::VALID. |
593 | | * @param[in] first_time_failure Whether we should consider inserting into vExtraTxnForCompact, adding |
594 | | * a new orphan to resolve, or looking for a package to submit. |
595 | | * Set to true for transactions just received over p2p. |
596 | | * Set to false if the tx has already been rejected before, |
597 | | * e.g. is already in the orphanage, to avoid adding duplicate entries. |
598 | | * Updates m_txrequest, m_lazy_recent_rejects, m_lazy_recent_rejects_reconsiderable, m_orphanage, and vExtraTxnForCompact. |
599 | | * |
600 | | * @returns a PackageToValidate if this transaction has a reconsiderable failure and an eligible package was found, |
601 | | * or std::nullopt otherwise. |
602 | | */ |
603 | | std::optional<node::PackageToValidate> ProcessInvalidTx(NodeId nodeid, const CTransactionRef& tx, const TxValidationState& result, |
604 | | bool first_time_failure) |
605 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, m_tx_download_mutex); |
606 | | |
607 | | /** Handle a transaction whose result was MempoolAcceptResult::ResultType::VALID. |
608 | | * Updates m_txrequest, m_orphanage, and vExtraTxnForCompact. Also queues the tx for relay. */ |
609 | | void ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions) |
610 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, m_tx_download_mutex); |
611 | | |
612 | | /** Handle the results of package validation: calls ProcessValidTx and ProcessInvalidTx for |
613 | | * individual transactions, and caches rejection for the package as a group. |
614 | | */ |
615 | | void ProcessPackageResult(const node::PackageToValidate& package_to_validate, const PackageMempoolAcceptResult& package_result) |
616 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, m_tx_download_mutex); |
617 | | |
618 | | /** |
619 | | * Reconsider orphan transactions after a parent has been accepted to the mempool. |
620 | | * |
621 | | * @peer[in] peer The peer whose orphan transactions we will reconsider. Generally only |
622 | | * one orphan will be reconsidered on each call of this function. If an |
623 | | * accepted orphan has orphaned children, those will need to be |
624 | | * reconsidered, creating more work, possibly for other peers. |
625 | | * @return True if meaningful work was done (an orphan was accepted/rejected). |
626 | | * If no meaningful work was done, then the work set for this peer |
627 | | * will be empty. |
628 | | */ |
629 | | bool ProcessOrphanTx(Peer& peer) |
630 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, !m_tx_download_mutex); |
631 | | |
632 | | /** Process a single headers message from a peer. |
633 | | * |
634 | | * @param[in] pfrom CNode of the peer |
635 | | * @param[in] peer The peer sending us the headers |
636 | | * @param[in] headers The headers received. Note that this may be modified within ProcessHeadersMessage. |
637 | | * @param[in] via_compact_block Whether this header came in via compact block handling. |
638 | | */ |
639 | | void ProcessHeadersMessage(CNode& pfrom, Peer& peer, |
640 | | std::vector<CBlockHeader>&& headers, |
641 | | bool via_compact_block) |
642 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
643 | | /** Various helpers for headers processing, invoked by ProcessHeadersMessage() */ |
644 | | /** Return true if headers are continuous and have valid proof-of-work (DoS points assigned on failure) */ |
645 | | bool CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer); |
646 | | /** Calculate an anti-DoS work threshold for headers chains */ |
647 | | arith_uint256 GetAntiDoSWorkThreshold(); |
648 | | /** Deal with state tracking and headers sync for peers that send |
649 | | * non-connecting headers (this can happen due to BIP 130 headers |
650 | | * announcements for blocks interacting with the 2hr (MAX_FUTURE_BLOCK_TIME) rule). */ |
651 | | void HandleUnconnectingHeaders(CNode& pfrom, Peer& peer, const std::vector<CBlockHeader>& headers) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
652 | | /** Return true if the headers connect to each other, false otherwise */ |
653 | | bool CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const; |
654 | | /** Try to continue a low-work headers sync that has already begun. |
655 | | * Assumes the caller has already verified the headers connect, and has |
656 | | * checked that each header satisfies the proof-of-work target included in |
657 | | * the header. |
658 | | * @param[in] peer The peer we're syncing with. |
659 | | * @param[in] pfrom CNode of the peer |
660 | | * @param[in,out] headers The headers to be processed. |
661 | | * @return True if the passed in headers were successfully processed |
662 | | * as the continuation of a low-work headers sync in progress; |
663 | | * false otherwise. |
664 | | * If false, the passed in headers will be returned back to |
665 | | * the caller. |
666 | | * If true, the returned headers may be empty, indicating |
667 | | * there is no more work for the caller to do; or the headers |
668 | | * may be populated with entries that have passed anti-DoS |
669 | | * checks (and therefore may be validated for block index |
670 | | * acceptance by the caller). |
671 | | */ |
672 | | bool IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, |
673 | | std::vector<CBlockHeader>& headers) |
674 | | EXCLUSIVE_LOCKS_REQUIRED(peer.m_headers_sync_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
675 | | /** Check work on a headers chain to be processed, and if insufficient, |
676 | | * initiate our anti-DoS headers sync mechanism. |
677 | | * |
678 | | * @param[in] peer The peer whose headers we're processing. |
679 | | * @param[in] pfrom CNode of the peer |
680 | | * @param[in] chain_start_header Where these headers connect in our index. |
681 | | * @param[in,out] headers The headers to be processed. |
682 | | * |
683 | | * @return True if chain was low work (headers will be empty after |
684 | | * calling); false otherwise. |
685 | | */ |
686 | | bool TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, |
687 | | const CBlockIndex* chain_start_header, |
688 | | std::vector<CBlockHeader>& headers) |
689 | | EXCLUSIVE_LOCKS_REQUIRED(!peer.m_headers_sync_mutex, !m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
690 | | |
691 | | /** Return true if the given header is an ancestor of |
692 | | * m_chainman.m_best_header or our current tip */ |
693 | | bool IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
694 | | |
695 | | /** Request further headers from this peer with a given locator. |
696 | | * We don't issue a getheaders message if we have a recent one outstanding. |
697 | | * This returns true if a getheaders is actually sent, and false otherwise. |
698 | | */ |
699 | | bool MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
700 | | /** Potentially fetch blocks from this peer upon receipt of a new headers tip */ |
701 | | void HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header); |
702 | | /** Update peer state based on received headers message */ |
703 | | void UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers) |
704 | | EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
705 | | |
706 | | void SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req); |
707 | | |
708 | | /** Send a message to a peer */ |
709 | 5.61k | void PushMessage(CNode& node, CSerializedNetMsg&& msg) const { m_connman.PushMessage(&node, std::move(msg)); } |
710 | | template <typename... Args> |
711 | | void MakeAndPushMessage(CNode& node, std::string msg_type, Args&&... args) const |
712 | 1.14M | { |
713 | 1.14M | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); |
714 | 1.14M | } net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJbRKyEEEvR5CNodeNSt3__112basic_stringIcNS6_11char_traitsIcEENS6_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 78.0k | { | 713 | 78.0k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 78.0k | } |
net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRNSt3__16vectorI4CInvNS2_9allocatorIS4_EEEEEEEvR5CNodeNS2_12basic_stringIcNS2_11char_traitsIcEENS5_IcEEEEDpOT_ Line | Count | Source | 712 | 219k | { | 713 | 219k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 219k | } |
net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRKiRyRKxS4_13ParamsWrapperIN8CNetAddr9SerParamsE8CServiceES4_SB_S4_RNSt3__112basic_stringIcNSC_11char_traitsIcEENSC_9allocatorIcEEEES3_RKbEEEvR5CNodeSI_DpOT_ Line | Count | Source | 712 | 115k | { | 713 | 115k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 115k | } |
net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJEEEvR5CNodeNSt3__112basic_stringIcNS4_11char_traitsIcEENS4_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 424k | { | 713 | 424k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 424k | } |
Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRKjRKyEEEvR5CNodeNSt3__112basic_stringIcNS8_11char_traitsIcEENS8_9allocatorIcEEEEDpOT_ net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRKNSt3__15arrayISt4byteLm168EEEEEEvR5CNodeNS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 6.81k | { | 713 | 6.81k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 6.81k | } |
net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRK13CBlockLocator7uint256EEEvR5CNodeNSt3__112basic_stringIcNS8_11char_traitsIcEENS8_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 42.9k | { | 713 | 42.9k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 42.9k | } |
Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJ13ParamsWrapperI20TransactionSerParamsK12CTransactionEEEEvR5CNodeNSt3__112basic_stringIcNS9_11char_traitsIcEENS9_9allocatorIcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJNSt3__14spanISt4byteLm18446744073709551615EEEEEEvR5CNodeNS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJ13ParamsWrapperI20TransactionSerParamsK6CBlockEEEEvR5CNodeNSt3__112basic_stringIcNS9_11char_traitsIcEENS9_9allocatorIcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJR12CMerkleBlockEEEvR5CNodeNSt3__112basic_stringIcNS6_11char_traitsIcEENS6_9allocatorIcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRK25CBlockHeaderAndShortTxIDsEEEvR5CNodeNSt3__112basic_stringIcNS7_11char_traitsIcEENS7_9allocatorIcEEEEDpOT_ net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJR25CBlockHeaderAndShortTxIDsEEEvR5CNodeNSt3__112basic_stringIcNS6_11char_traitsIcEENS6_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 4.04k | { | 713 | 4.04k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 4.04k | } |
Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJR17BlockTransactionsEEEvR5CNodeNSt3__112basic_stringIcNS6_11char_traitsIcEENS6_9allocatorIcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJNSt3__16vectorI12CBlockHeaderNS2_9allocatorIS4_EEEEEEEvR5CNodeNS2_12basic_stringIcNS2_11char_traitsIcEENS5_IcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJ13ParamsWrapperI20TransactionSerParamsNSt3__16vectorI6CBlockNS4_9allocatorIS6_EEEEEEEEvR5CNodeNS4_12basic_stringIcNS4_11char_traitsIcEENS7_IcEEEEDpOT_ net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJR24BlockTransactionsRequestEEEvR5CNodeNSt3__112basic_stringIcNS6_11char_traitsIcEENS6_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 103k | { | 713 | 103k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 103k | } |
net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRyEEEvR5CNodeNSt3__112basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 76.1k | { | 713 | 76.1k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 76.1k | } |
Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRK11BlockFilterEEEvR5CNodeNSt3__112basic_stringIcNS7_11char_traitsIcEENS7_9allocatorIcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRh7uint256RS3_RNSt3__16vectorIS3_NS5_9allocatorIS3_EEEEEEEvR5CNodeNS5_12basic_stringIcNS5_11char_traitsIcEENS7_IcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRh7uint256RNSt3__16vectorIS3_NS4_9allocatorIS3_EEEEEEEvR5CNodeNS4_12basic_stringIcNS4_11char_traitsIcEENS6_IcEEEEDpOT_ Unexecuted instantiation: net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJ13ParamsWrapperIN8CAddress9SerParamsENSt3__16vectorIS3_NS5_9allocatorIS3_EEEEEEEEvR5CNodeNS5_12basic_stringIcNS5_11char_traitsIcEENS7_IcEEEEDpOT_ net_processing.cpp:_ZNK12_GLOBAL__N_115PeerManagerImpl18MakeAndPushMessageIJRxEEEvR5CNodeNSt3__112basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEEDpOT_ Line | Count | Source | 712 | 71.4k | { | 713 | 71.4k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 714 | 71.4k | } |
|
715 | | |
716 | | /** Send a version message to a peer */ |
717 | | void PushNodeVersion(CNode& pnode, const Peer& peer); |
718 | | |
719 | | /** Send a ping message every PING_INTERVAL or if requested via RPC. May |
720 | | * mark the peer to be disconnected if a ping has timed out. |
721 | | * We use mockable time for ping timeouts, so setmocktime may cause pings |
722 | | * to time out. */ |
723 | | void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now); |
724 | | |
725 | | /** Send `addr` messages on a regular schedule. */ |
726 | | void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
727 | | |
728 | | /** Send a single `sendheaders` message, after we have completed headers sync with a peer. */ |
729 | | void MaybeSendSendHeaders(CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
730 | | |
731 | | /** Relay (gossip) an address to a few randomly chosen nodes. |
732 | | * |
733 | | * @param[in] originator The id of the peer that sent us the address. We don't want to relay it back. |
734 | | * @param[in] addr Address to relay. |
735 | | * @param[in] fReachable Whether the address' network is reachable. We relay unreachable |
736 | | * addresses less. |
737 | | */ |
738 | | void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex); |
739 | | |
740 | | /** Send `feefilter` message. */ |
741 | | void MaybeSendFeefilter(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
742 | | |
743 | | FastRandomContext m_rng GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
744 | | |
745 | | FeeFilterRounder m_fee_filter_rounder GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
746 | | |
747 | | const CChainParams& m_chainparams; |
748 | | CConnman& m_connman; |
749 | | AddrMan& m_addrman; |
750 | | /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */ |
751 | | BanMan* const m_banman; |
752 | | ChainstateManager& m_chainman; |
753 | | CTxMemPool& m_mempool; |
754 | | |
755 | | /** Synchronizes tx download including TxRequestTracker, rejection filters, and TxOrphanage. |
756 | | * Lock invariants: |
757 | | * - A txhash (txid or wtxid) in m_txrequest is not also in m_orphanage. |
758 | | * - A txhash (txid or wtxid) in m_txrequest is not also in m_lazy_recent_rejects. |
759 | | * - A txhash (txid or wtxid) in m_txrequest is not also in m_lazy_recent_rejects_reconsiderable. |
760 | | * - A txhash (txid or wtxid) in m_txrequest is not also in m_lazy_recent_confirmed_transactions. |
761 | | * - Each data structure's limits hold (m_orphanage max size, m_txrequest per-peer limits, etc). |
762 | | */ |
763 | | Mutex m_tx_download_mutex ACQUIRED_BEFORE(m_mempool.cs); |
764 | | node::TxDownloadManager m_txdownloadman GUARDED_BY(m_tx_download_mutex); |
765 | | |
766 | | std::unique_ptr<TxReconciliationTracker> m_txreconciliation; |
767 | | |
768 | | /** The height of the best chain */ |
769 | | std::atomic<int> m_best_height{-1}; |
770 | | /** The time of the best chain tip block */ |
771 | | std::atomic<std::chrono::seconds> m_best_block_time{0s}; |
772 | | |
773 | | /** Next time to check for stale tip */ |
774 | | std::chrono::seconds m_stale_tip_check_time GUARDED_BY(cs_main){0s}; |
775 | | |
776 | | node::Warnings& m_warnings; |
777 | | TimeOffsets m_outbound_time_offsets{m_warnings}; |
778 | | |
779 | | const Options m_opts; |
780 | | |
781 | | bool RejectIncomingTxs(const CNode& peer) const; |
782 | | |
783 | | /** Whether we've completed initial sync yet, for determining when to turn |
784 | | * on extra block-relay-only peers. */ |
785 | | bool m_initial_sync_finished GUARDED_BY(cs_main){false}; |
786 | | |
787 | | /** Protects m_peer_map. This mutex must not be locked while holding a lock |
788 | | * on any of the mutexes inside a Peer object. */ |
789 | | mutable Mutex m_peer_mutex; |
790 | | /** |
791 | | * Map of all Peer objects, keyed by peer id. This map is protected |
792 | | * by the m_peer_mutex. Once a shared pointer reference is |
793 | | * taken, the lock may be released. Individual fields are protected by |
794 | | * their own locks. |
795 | | */ |
796 | | std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex); |
797 | | |
798 | | /** Map maintaining per-node state. */ |
799 | | std::map<NodeId, CNodeState> m_node_states GUARDED_BY(cs_main); |
800 | | |
801 | | /** Get a pointer to a const CNodeState, used when not mutating the CNodeState object. */ |
802 | | const CNodeState* State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
803 | | /** Get a pointer to a mutable CNodeState. */ |
804 | | CNodeState* State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
805 | | |
806 | | uint32_t GetFetchFlags(const Peer& peer) const; |
807 | | |
808 | | std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us}; |
809 | | |
810 | | /** Number of nodes with fSyncStarted. */ |
811 | | int nSyncStarted GUARDED_BY(cs_main) = 0; |
812 | | |
813 | | /** Hash of the last block we received via INV */ |
814 | | uint256 m_last_block_inv_triggering_headers_sync GUARDED_BY(g_msgproc_mutex){}; |
815 | | |
816 | | /** |
817 | | * Sources of received blocks, saved to be able punish them when processing |
818 | | * happens afterwards. |
819 | | * Set mapBlockSource[hash].second to false if the node should not be |
820 | | * punished if the block is invalid. |
821 | | */ |
822 | | std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main); |
823 | | |
824 | | /** Number of peers with wtxid relay. */ |
825 | | std::atomic<int> m_wtxid_relay_peers{0}; |
826 | | |
827 | | /** Number of outbound peers with m_chain_sync.m_protect. */ |
828 | | int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0; |
829 | | |
830 | | /** Number of preferable block download peers. */ |
831 | | int m_num_preferred_download_peers GUARDED_BY(cs_main){0}; |
832 | | |
833 | | /** Stalling timeout for blocks in IBD */ |
834 | | std::atomic<std::chrono::seconds> m_block_stalling_timeout{BLOCK_STALLING_TIMEOUT_DEFAULT}; |
835 | | |
836 | | /** |
837 | | * For sending `inv`s to inbound peers, we use a single (exponentially |
838 | | * distributed) timer for all peers. If we used a separate timer for each |
839 | | * peer, a spy node could make multiple inbound connections to us to |
840 | | * accurately determine when we received the transaction (and potentially |
841 | | * determine the transaction's origin). */ |
842 | | std::chrono::microseconds NextInvToInbounds(std::chrono::microseconds now, |
843 | | std::chrono::seconds average_interval) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
844 | | |
845 | | |
846 | | // All of the following cache a recent block, and are protected by m_most_recent_block_mutex |
847 | | Mutex m_most_recent_block_mutex; |
848 | | std::shared_ptr<const CBlock> m_most_recent_block GUARDED_BY(m_most_recent_block_mutex); |
849 | | std::shared_ptr<const CBlockHeaderAndShortTxIDs> m_most_recent_compact_block GUARDED_BY(m_most_recent_block_mutex); |
850 | | uint256 m_most_recent_block_hash GUARDED_BY(m_most_recent_block_mutex); |
851 | | std::unique_ptr<const std::map<GenTxid, CTransactionRef>> m_most_recent_block_txs GUARDED_BY(m_most_recent_block_mutex); |
852 | | |
853 | | // Data about the low-work headers synchronization, aggregated from all peers' HeadersSyncStates. |
854 | | /** Mutex guarding the other m_headers_presync_* variables. */ |
855 | | Mutex m_headers_presync_mutex; |
856 | | /** A type to represent statistics about a peer's low-work headers sync. |
857 | | * |
858 | | * - The first field is the total verified amount of work in that synchronization. |
859 | | * - The second is: |
860 | | * - nullopt: the sync is in REDOWNLOAD phase (phase 2). |
861 | | * - {height, timestamp}: the sync has the specified tip height and block timestamp (phase 1). |
862 | | */ |
863 | | using HeadersPresyncStats = std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>; |
864 | | /** Statistics for all peers in low-work headers sync. */ |
865 | | std::map<NodeId, HeadersPresyncStats> m_headers_presync_stats GUARDED_BY(m_headers_presync_mutex) {}; |
866 | | /** The peer with the most-work entry in m_headers_presync_stats. */ |
867 | | NodeId m_headers_presync_bestpeer GUARDED_BY(m_headers_presync_mutex) {-1}; |
868 | | /** The m_headers_presync_stats improved, and needs signalling. */ |
869 | | std::atomic_bool m_headers_presync_should_signal{false}; |
870 | | |
871 | | /** Height of the highest block announced using BIP 152 high-bandwidth mode. */ |
872 | | int m_highest_fast_announce GUARDED_BY(::cs_main){0}; |
873 | | |
874 | | /** Have we requested this block from a peer */ |
875 | | bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
876 | | |
877 | | /** Have we requested this block from an outbound peer */ |
878 | | bool IsBlockRequestedFromOutbound(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_peer_mutex); |
879 | | |
880 | | /** Remove this block from our tracked requested blocks. Called if: |
881 | | * - the block has been received from a peer |
882 | | * - the request for the block has timed out |
883 | | * If "from_peer" is specified, then only remove the block if it is in |
884 | | * flight from that peer (to avoid one peer's network traffic from |
885 | | * affecting another's state). |
886 | | */ |
887 | | void RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
888 | | |
889 | | /* Mark a block as in flight |
890 | | * Returns false, still setting pit, if the block was already in flight from the same peer |
891 | | * pit will only be valid as long as the same cs_main lock is being held |
892 | | */ |
893 | | bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
894 | | |
895 | | bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
896 | | |
897 | | /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has |
898 | | * at most count entries. |
899 | | */ |
900 | | void FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
901 | | |
902 | | /** Request blocks for the background chainstate, if one is in use. */ |
903 | | void TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex* from_tip, const CBlockIndex* target_block) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
904 | | |
905 | | /** |
906 | | * \brief Find next blocks to download from a peer after a starting block. |
907 | | * |
908 | | * \param vBlocks Vector of blocks to download which will be appended to. |
909 | | * \param peer Peer which blocks will be downloaded from. |
910 | | * \param state Pointer to the state of the peer. |
911 | | * \param pindexWalk Pointer to the starting block to add to vBlocks. |
912 | | * \param count Maximum number of blocks to allow in vBlocks. No more |
913 | | * blocks will be added if it reaches this size. |
914 | | * \param nWindowEnd Maximum height of blocks to allow in vBlocks. No |
915 | | * blocks will be added above this height. |
916 | | * \param activeChain Optional pointer to a chain to compare against. If |
917 | | * provided, any next blocks which are already contained |
918 | | * in this chain will not be appended to vBlocks, but |
919 | | * instead will be used to update the |
920 | | * state->pindexLastCommonBlock pointer. |
921 | | * \param nodeStaller Optional pointer to a NodeId variable that will receive |
922 | | * the ID of another peer that might be causing this peer |
923 | | * to stall. This is set to the ID of the peer which |
924 | | * first requested the first in-flight block in the |
925 | | * download window. It is only set if vBlocks is empty at |
926 | | * the end of this function call and if increasing |
927 | | * nWindowEnd by 1 would cause it to be non-empty (which |
928 | | * indicates the download might be stalled because every |
929 | | * block in the window is in flight and no other peer is |
930 | | * trying to download the next block). |
931 | | */ |
932 | | void FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain=nullptr, NodeId* nodeStaller=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
933 | | |
934 | | /* Multimap used to preserve insertion order */ |
935 | | typedef std::multimap<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator>> BlockDownloadMap; |
936 | | BlockDownloadMap mapBlocksInFlight GUARDED_BY(cs_main); |
937 | | |
938 | | /** When our tip was last updated. */ |
939 | | std::atomic<std::chrono::seconds> m_last_tip_update{0s}; |
940 | | |
941 | | /** Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). */ |
942 | | CTransactionRef FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid) |
943 | | EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, NetEventsInterface::g_msgproc_mutex); |
944 | | |
945 | | void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) |
946 | | EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex, NetEventsInterface::g_msgproc_mutex) |
947 | | LOCKS_EXCLUDED(::cs_main); |
948 | | |
949 | | /** Process a new block. Perform any post-processing housekeeping */ |
950 | | void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked); |
951 | | |
952 | | /** Process compact block txns */ |
953 | | void ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions) |
954 | | EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex, !m_most_recent_block_mutex); |
955 | | |
956 | | /** |
957 | | * When a peer sends us a valid block, instruct it to announce blocks to us |
958 | | * using CMPCTBLOCK if possible by adding its nodeid to the end of |
959 | | * lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by |
960 | | * removing the first element if necessary. |
961 | | */ |
962 | | void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_peer_mutex); |
963 | | |
964 | | /** Stack of nodes which we have set to announce using compact blocks */ |
965 | | std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main); |
966 | | |
967 | | /** Number of peers from which we're downloading blocks. */ |
968 | | int m_peers_downloading_from GUARDED_BY(cs_main) = 0; |
969 | | |
970 | | void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
971 | | |
972 | | /** Orphan/conflicted/etc transactions that are kept for compact block reconstruction. |
973 | | * The last -blockreconstructionextratxn/DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN of |
974 | | * these are kept in a ring buffer */ |
975 | | std::vector<std::pair<Wtxid, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_msgproc_mutex); |
976 | | /** Offset into vExtraTxnForCompact to insert the next tx */ |
977 | | size_t vExtraTxnForCompactIt GUARDED_BY(g_msgproc_mutex) = 0; |
978 | | |
979 | | /** Check whether the last unknown block a peer advertised is not yet known. */ |
980 | | void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
981 | | /** Update tracking information about which blocks a peer is assumed to have. */ |
982 | | void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
983 | | bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
984 | | |
985 | | /** |
986 | | * Estimates the distance, in blocks, between the best-known block and the network chain tip. |
987 | | * Utilizes the best-block time and the chainparams blocks spacing to approximate it. |
988 | | */ |
989 | | int64_t ApproximateBestBlockDepth() const; |
990 | | |
991 | | /** |
992 | | * To prevent fingerprinting attacks, only send blocks/headers outside of |
993 | | * the active chain if they are no more than a month older (both in time, |
994 | | * and in best equivalent proof of work) than the best header chain we know |
995 | | * about and we fully-validated them at some point. |
996 | | */ |
997 | | bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
998 | | bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
999 | | void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv) |
1000 | | EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex, !m_most_recent_block_mutex); |
1001 | | |
1002 | | /** |
1003 | | * Validation logic for compact filters request handling. |
1004 | | * |
1005 | | * May disconnect from the peer in the case of a bad request. |
1006 | | * |
1007 | | * @param[in] node The node that we received the request from |
1008 | | * @param[in] peer The peer that we received the request from |
1009 | | * @param[in] filter_type The filter type the request is for. Must be basic filters. |
1010 | | * @param[in] start_height The start height for the request |
1011 | | * @param[in] stop_hash The stop_hash for the request |
1012 | | * @param[in] max_height_diff The maximum number of items permitted to request, as specified in BIP 157 |
1013 | | * @param[out] stop_index The CBlockIndex for the stop_hash block, if the request can be serviced. |
1014 | | * @param[out] filter_index The filter index, if the request can be serviced. |
1015 | | * @return True if the request can be serviced. |
1016 | | */ |
1017 | | bool PrepareBlockFilterRequest(CNode& node, Peer& peer, |
1018 | | BlockFilterType filter_type, uint32_t start_height, |
1019 | | const uint256& stop_hash, uint32_t max_height_diff, |
1020 | | const CBlockIndex*& stop_index, |
1021 | | BlockFilterIndex*& filter_index); |
1022 | | |
1023 | | /** |
1024 | | * Handle a cfilters request. |
1025 | | * |
1026 | | * May disconnect from the peer in the case of a bad request. |
1027 | | * |
1028 | | * @param[in] node The node that we received the request from |
1029 | | * @param[in] peer The peer that we received the request from |
1030 | | * @param[in] vRecv The raw message received |
1031 | | */ |
1032 | | void ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv); |
1033 | | |
1034 | | /** |
1035 | | * Handle a cfheaders request. |
1036 | | * |
1037 | | * May disconnect from the peer in the case of a bad request. |
1038 | | * |
1039 | | * @param[in] node The node that we received the request from |
1040 | | * @param[in] peer The peer that we received the request from |
1041 | | * @param[in] vRecv The raw message received |
1042 | | */ |
1043 | | void ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv); |
1044 | | |
1045 | | /** |
1046 | | * Handle a getcfcheckpt request. |
1047 | | * |
1048 | | * May disconnect from the peer in the case of a bad request. |
1049 | | * |
1050 | | * @param[in] node The node that we received the request from |
1051 | | * @param[in] peer The peer that we received the request from |
1052 | | * @param[in] vRecv The raw message received |
1053 | | */ |
1054 | | void ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv); |
1055 | | |
1056 | | /** Checks if address relay is permitted with peer. If needed, initializes |
1057 | | * the m_addr_known bloom filter and sets m_addr_relay_enabled to true. |
1058 | | * |
1059 | | * @return True if address relay is enabled with peer |
1060 | | * False if address relay is disallowed |
1061 | | */ |
1062 | | bool SetupAddressRelay(const CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
1063 | | |
1064 | | void AddAddressKnown(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
1065 | | void PushAddress(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
1066 | | |
1067 | | void LogBlockHeader(const CBlockIndex& index, const CNode& peer, bool via_compact_block); |
1068 | | }; |
1069 | | |
1070 | | const CNodeState* PeerManagerImpl::State(NodeId pnode) const |
1071 | 36.1M | { |
1072 | 36.1M | std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode); |
1073 | 36.1M | if (it == m_node_states.end()) |
1074 | 0 | return nullptr; |
1075 | 36.1M | return &it->second; |
1076 | 36.1M | } |
1077 | | |
1078 | | CNodeState* PeerManagerImpl::State(NodeId pnode) |
1079 | 36.0M | { |
1080 | 36.0M | return const_cast<CNodeState*>(std::as_const(*this).State(pnode)); |
1081 | 36.0M | } |
1082 | | |
1083 | | /** |
1084 | | * Whether the peer supports the address. For example, a peer that does not |
1085 | | * implement BIP155 cannot receive Tor v3 addresses because it requires |
1086 | | * ADDRv2 (BIP155) encoding. |
1087 | | */ |
1088 | | static bool IsAddrCompatible(const Peer& peer, const CAddress& addr) |
1089 | 0 | { |
1090 | 0 | return peer.m_wants_addrv2 || addr.IsAddrV1Compatible(); |
1091 | 0 | } |
1092 | | |
1093 | | void PeerManagerImpl::AddAddressKnown(Peer& peer, const CAddress& addr) |
1094 | 0 | { |
1095 | 0 | assert(peer.m_addr_known); |
1096 | 0 | peer.m_addr_known->insert(addr.GetKey()); |
1097 | 0 | } |
1098 | | |
1099 | | void PeerManagerImpl::PushAddress(Peer& peer, const CAddress& addr) |
1100 | 0 | { |
1101 | | // Known checking here is only to save space from duplicates. |
1102 | | // Before sending, we'll filter it again for known addresses that were |
1103 | | // added after addresses were pushed. |
1104 | 0 | assert(peer.m_addr_known); |
1105 | 0 | if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) { |
1106 | 0 | if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) { |
1107 | 0 | peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] = addr; |
1108 | 0 | } else { |
1109 | 0 | peer.m_addrs_to_send.push_back(addr); |
1110 | 0 | } |
1111 | 0 | } |
1112 | 0 | } |
1113 | | |
1114 | | static void AddKnownTx(Peer& peer, const uint256& hash) |
1115 | 1.18M | { |
1116 | 1.18M | auto tx_relay = peer.GetTxRelay(); |
1117 | 1.18M | if (!tx_relay) return890k ; |
1118 | | |
1119 | 298k | LOCK(tx_relay->m_tx_inventory_mutex); Line | Count | Source | 259 | 298k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 298k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 298k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 298k | #define PASTE(x, y) x ## y |
|
|
|
|
1120 | 298k | tx_relay->m_tx_inventory_known_filter.insert(hash); |
1121 | 298k | } |
1122 | | |
1123 | | /** Whether this peer can serve us blocks. */ |
1124 | | static bool CanServeBlocks(const Peer& peer) |
1125 | 8.77M | { |
1126 | 8.77M | return peer.m_their_services & (NODE_NETWORK|NODE_NETWORK_LIMITED); |
1127 | 8.77M | } |
1128 | | |
1129 | | /** Whether this peer can only serve limited recent blocks (e.g. because |
1130 | | * it prunes old blocks) */ |
1131 | | static bool IsLimitedPeer(const Peer& peer) |
1132 | 8.01M | { |
1133 | 8.01M | return (!(peer.m_their_services & NODE_NETWORK) && |
1134 | 8.01M | (peer.m_their_services & NODE_NETWORK_LIMITED)7.36M ); |
1135 | 8.01M | } |
1136 | | |
1137 | | /** Whether this peer can serve us witness data */ |
1138 | | static bool CanServeWitnesses(const Peer& peer) |
1139 | 3.55M | { |
1140 | 3.55M | return peer.m_their_services & NODE_WITNESS; |
1141 | 3.55M | } |
1142 | | |
1143 | | std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now, |
1144 | | std::chrono::seconds average_interval) |
1145 | 28.4k | { |
1146 | 28.4k | if (m_next_inv_to_inbounds.load() < now) { |
1147 | | // If this function were called from multiple threads simultaneously |
1148 | | // it would possible that both update the next send variable, and return a different result to their caller. |
1149 | | // This is not possible in practice as only the net processing thread invokes this function. |
1150 | 27.8k | m_next_inv_to_inbounds = now + m_rng.rand_exp_duration(average_interval); |
1151 | 27.8k | } |
1152 | 28.4k | return m_next_inv_to_inbounds; |
1153 | 28.4k | } |
1154 | | |
1155 | | bool PeerManagerImpl::IsBlockRequested(const uint256& hash) |
1156 | 890k | { |
1157 | 890k | return mapBlocksInFlight.count(hash); |
1158 | 890k | } |
1159 | | |
1160 | | bool PeerManagerImpl::IsBlockRequestedFromOutbound(const uint256& hash) |
1161 | 1.28k | { |
1162 | 1.71k | for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++434 ) { |
1163 | 1.50k | auto [nodeid, block_it] = range.first->second; |
1164 | 1.50k | PeerRef peer{GetPeerRef(nodeid)}; |
1165 | 1.50k | if (peer && !peer->m_is_inbound) return true1.06k ; |
1166 | 1.50k | } |
1167 | | |
1168 | 217 | return false; |
1169 | 1.28k | } |
1170 | | |
1171 | | void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) |
1172 | 1.10M | { |
1173 | 1.10M | auto range = mapBlocksInFlight.equal_range(hash); |
1174 | 1.10M | if (range.first == range.second) { |
1175 | | // Block was not requested from any peer |
1176 | 454k | return; |
1177 | 454k | } |
1178 | | |
1179 | | // We should not have requested too many of this block |
1180 | 649k | Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK); Line | Count | Source | 118 | 649k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
1181 | | |
1182 | 1.51M | while (range.first != range.second) { |
1183 | 869k | const auto& [node_id, list_it]{range.first->second}; |
1184 | | |
1185 | 869k | if (from_peer && *from_peer != node_id845k ) { |
1186 | 441k | range.first++; |
1187 | 441k | continue; |
1188 | 441k | } |
1189 | | |
1190 | 428k | CNodeState& state = *Assert(State(node_id)); Line | Count | Source | 106 | 428k | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
1191 | | |
1192 | 428k | if (state.vBlocksInFlight.begin() == list_it) { |
1193 | | // First block on the queue was received, update the start download time for the next one |
1194 | 111k | state.m_downloading_since = std::max(state.m_downloading_since, GetTime<std::chrono::microseconds>()); |
1195 | 111k | } |
1196 | 428k | state.vBlocksInFlight.erase(list_it); |
1197 | | |
1198 | 428k | if (state.vBlocksInFlight.empty()) { |
1199 | | // Last validated block on the queue for this peer was received. |
1200 | 103k | m_peers_downloading_from--; |
1201 | 103k | } |
1202 | 428k | state.m_stalling_since = 0us; |
1203 | | |
1204 | 428k | range.first = mapBlocksInFlight.erase(range.first); |
1205 | 428k | } |
1206 | 649k | } |
1207 | | |
1208 | | bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit) |
1209 | 759k | { |
1210 | 759k | const uint256& hash{block.GetBlockHash()}; |
1211 | | |
1212 | 759k | CNodeState *state = State(nodeid); |
1213 | 759k | assert(state != nullptr); |
1214 | | |
1215 | 759k | Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK); Line | Count | Source | 118 | 759k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
1216 | | |
1217 | | // Short-circuit most stuff in case it is from the same node |
1218 | 998k | for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++238k ) { |
1219 | 498k | if (range.first->second.first == nodeid) { |
1220 | 260k | if (pit) { |
1221 | 260k | *pit = &range.first->second.second; |
1222 | 260k | } |
1223 | 260k | return false; |
1224 | 260k | } |
1225 | 498k | } |
1226 | | |
1227 | | // Make sure it's not being fetched already from same peer. |
1228 | 499k | RemoveBlockRequest(hash, nodeid); |
1229 | | |
1230 | 499k | std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), |
1231 | 499k | {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool)490k : nullptr9.34k )}); |
1232 | 499k | if (state->vBlocksInFlight.size() == 1) { |
1233 | | // We're starting a block download (batch) from this peer. |
1234 | 127k | state->m_downloading_since = GetTime<std::chrono::microseconds>(); |
1235 | 127k | m_peers_downloading_from++; |
1236 | 127k | } |
1237 | 499k | auto itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))); |
1238 | 499k | if (pit) { |
1239 | 490k | *pit = &itInFlight->second.second; |
1240 | 490k | } |
1241 | 499k | return true; |
1242 | 759k | } |
1243 | | |
1244 | | void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) |
1245 | 8.32k | { |
1246 | 8.32k | AssertLockHeld(cs_main); Line | Count | Source | 137 | 8.32k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
1247 | | |
1248 | | // When in -blocksonly mode, never request high-bandwidth mode from peers. Our |
1249 | | // mempool will not contain the transactions necessary to reconstruct the |
1250 | | // compact block. |
1251 | 8.32k | if (m_opts.ignore_incoming_txs) return0 ; |
1252 | | |
1253 | 8.32k | CNodeState* nodestate = State(nodeid); |
1254 | 8.32k | PeerRef peer{GetPeerRef(nodeid)}; |
1255 | 8.32k | if (!nodestate || !nodestate->m_provides_cmpctblocks) { |
1256 | | // Don't request compact blocks if the peer has not signalled support |
1257 | 4.48k | return; |
1258 | 4.48k | } |
1259 | | |
1260 | 3.84k | int num_outbound_hb_peers = 0; |
1261 | 5.25k | for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++1.41k ) { |
1262 | 3.26k | if (*it == nodeid) { |
1263 | 1.85k | lNodesAnnouncingHeaderAndIDs.erase(it); |
1264 | 1.85k | lNodesAnnouncingHeaderAndIDs.push_back(nodeid); |
1265 | 1.85k | return; |
1266 | 1.85k | } |
1267 | 1.41k | PeerRef peer_ref{GetPeerRef(*it)}; |
1268 | 1.41k | if (peer_ref && !peer_ref->m_is_inbound) ++num_outbound_hb_peers539 ; |
1269 | 1.41k | } |
1270 | 1.98k | if (peer && peer->m_is_inbound) { |
1271 | | // If we're adding an inbound HB peer, make sure we're not removing |
1272 | | // our last outbound HB peer in the process. |
1273 | 1.36k | if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 10 ) { |
1274 | 0 | PeerRef remove_peer{GetPeerRef(lNodesAnnouncingHeaderAndIDs.front())}; |
1275 | 0 | if (remove_peer && !remove_peer->m_is_inbound) { |
1276 | | // Put the HB outbound peer in the second slot, so that it |
1277 | | // doesn't get removed. |
1278 | 0 | std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin())); |
1279 | 0 | } |
1280 | 0 | } |
1281 | 1.36k | } |
1282 | 1.98k | m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
1283 | 1.98k | AssertLockHeld(::cs_main); Line | Count | Source | 137 | 1.98k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
1284 | 1.98k | if (lNodesAnnouncingHeaderAndIDs.size() >= 3) { |
1285 | | // As per BIP152, we only get 3 of our peers to announce |
1286 | | // blocks using compact encodings. |
1287 | 0 | m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this](CNode* pnodeStop){ |
1288 | 0 | MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION); |
1289 | | // save BIP152 bandwidth state: we select peer to be low-bandwidth |
1290 | 0 | pnodeStop->m_bip152_highbandwidth_to = false; |
1291 | 0 | return true; |
1292 | 0 | }); |
1293 | 0 | lNodesAnnouncingHeaderAndIDs.pop_front(); |
1294 | 0 | } |
1295 | 1.98k | MakeAndPushMessage(*pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/true, /*version=*/CMPCTBLOCKS_VERSION); |
1296 | | // save BIP152 bandwidth state: we select peer to be high-bandwidth |
1297 | 1.98k | pfrom->m_bip152_highbandwidth_to = true; |
1298 | 1.98k | lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId()); |
1299 | 1.98k | return true; |
1300 | 1.98k | }); |
1301 | 1.98k | } |
1302 | | |
1303 | | bool PeerManagerImpl::TipMayBeStale() |
1304 | 0 | { |
1305 | 0 | AssertLockHeld(cs_main); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
1306 | 0 | const Consensus::Params& consensusParams = m_chainparams.GetConsensus(); |
1307 | 0 | if (m_last_tip_update.load() == 0s) { |
1308 | 0 | m_last_tip_update = GetTime<std::chrono::seconds>(); |
1309 | 0 | } |
1310 | 0 | return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty(); |
1311 | 0 | } |
1312 | | |
1313 | | int64_t PeerManagerImpl::ApproximateBestBlockDepth() const |
1314 | 41.0k | { |
1315 | 41.0k | return (GetTime<std::chrono::seconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing; |
1316 | 41.0k | } |
1317 | | |
1318 | | bool PeerManagerImpl::CanDirectFetch() |
1319 | 1.39M | { |
1320 | 1.39M | return m_chainman.ActiveChain().Tip()->Time() > NodeClock::now() - m_chainparams.GetConsensus().PowTargetSpacing() * 20; |
1321 | 1.39M | } |
1322 | | |
1323 | | static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main) |
1324 | 97.2k | { |
1325 | 97.2k | if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)93.5k ) |
1326 | 44.7k | return true; |
1327 | 52.4k | if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)33.5k ) |
1328 | 4.96k | return true; |
1329 | 47.4k | return false; |
1330 | 52.4k | } |
1331 | | |
1332 | 12.2M | void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) { |
1333 | 12.2M | CNodeState *state = State(nodeid); |
1334 | 12.2M | assert(state != nullptr); |
1335 | | |
1336 | 12.2M | if (!state->hashLastUnknownBlock.IsNull()) { |
1337 | 90.7k | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock); |
1338 | 90.7k | if (pindex && pindex->nChainWork > 088 ) { |
1339 | 88 | if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork73 ) { |
1340 | 45 | state->pindexBestKnownBlock = pindex; |
1341 | 45 | } |
1342 | 88 | state->hashLastUnknownBlock.SetNull(); |
1343 | 88 | } |
1344 | 90.7k | } |
1345 | 12.2M | } |
1346 | | |
1347 | 2.24M | void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { |
1348 | 2.24M | CNodeState *state = State(nodeid); |
1349 | 2.24M | assert(state != nullptr); |
1350 | | |
1351 | 2.24M | ProcessBlockAvailability(nodeid); |
1352 | | |
1353 | 2.24M | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash); |
1354 | 2.24M | if (pindex && pindex->nChainWork > 02.22M ) { |
1355 | | // An actually better block was announced. |
1356 | 2.22M | if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork2.18M ) { |
1357 | 1.54M | state->pindexBestKnownBlock = pindex; |
1358 | 1.54M | } |
1359 | 2.22M | } else { |
1360 | | // An unknown block was announced; just assume that the latest one is the best one. |
1361 | 22.3k | state->hashLastUnknownBlock = hash; |
1362 | 22.3k | } |
1363 | 2.24M | } |
1364 | | |
1365 | | // Logic for calculating which blocks to download from a given peer, given our current tip. |
1366 | | void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) |
1367 | 4.08M | { |
1368 | 4.08M | if (count == 0) |
1369 | 0 | return; |
1370 | | |
1371 | 4.08M | vBlocks.reserve(vBlocks.size() + count); |
1372 | 4.08M | CNodeState *state = State(peer.m_id); |
1373 | 4.08M | assert(state != nullptr); |
1374 | | |
1375 | | // Make sure pindexBestKnownBlock is up to date, we'll need it. |
1376 | 4.08M | ProcessBlockAvailability(peer.m_id); |
1377 | | |
1378 | 4.08M | if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork3.62M || state->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()3.61M ) { |
1379 | | // This peer has nothing interesting. |
1380 | 467k | return; |
1381 | 467k | } |
1382 | | |
1383 | | // When we sync with AssumeUtxo and discover the snapshot is not in the peer's best chain, abort: |
1384 | | // We can't reorg to this chain due to missing undo data until the background sync has finished, |
1385 | | // so downloading blocks from it would be futile. |
1386 | 3.61M | const CBlockIndex* snap_base{m_chainman.GetSnapshotBaseBlock()}; |
1387 | 3.61M | if (snap_base && state->pindexBestKnownBlock->GetAncestor(snap_base->nHeight) != snap_base0 ) { |
1388 | 0 | LogDebug(BCLog::NET, "Not downloading blocks from peer=%d, which doesn't have the snapshot block in its best chain.\n", peer.m_id); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
1389 | 0 | return; |
1390 | 0 | } |
1391 | | |
1392 | | // Bootstrap quickly by guessing a parent of our best tip is the forking point. |
1393 | | // Guessing wrong in either direction is not a problem. |
1394 | | // Also reset pindexLastCommonBlock after a snapshot was loaded, so that blocks after the snapshot will be prioritised for download. |
1395 | 3.61M | if (state->pindexLastCommonBlock == nullptr || |
1396 | 3.61M | (3.59M snap_base3.59M && state->pindexLastCommonBlock->nHeight < snap_base->nHeight0 )) { |
1397 | 22.4k | state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())]; |
1398 | 22.4k | } |
1399 | | |
1400 | | // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor |
1401 | | // of its current tip anymore. Go back enough to fix that. |
1402 | 3.61M | state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); |
1403 | 3.61M | if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) |
1404 | 24.4k | return; |
1405 | | |
1406 | 3.58M | const CBlockIndex *pindexWalk = state->pindexLastCommonBlock; |
1407 | | // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last |
1408 | | // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to |
1409 | | // download that next block if the window were 1 larger. |
1410 | 3.58M | int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; |
1411 | | |
1412 | 3.58M | FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller); |
1413 | 3.58M | } |
1414 | | |
1415 | | void PeerManagerImpl::TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex *from_tip, const CBlockIndex* target_block) |
1416 | 0 | { |
1417 | 0 | Assert(from_tip); Line | Count | Source | 106 | 0 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
1418 | 0 | Assert(target_block); Line | Count | Source | 106 | 0 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
1419 | |
|
1420 | 0 | if (vBlocks.size() >= count) { |
1421 | 0 | return; |
1422 | 0 | } |
1423 | | |
1424 | 0 | vBlocks.reserve(count); |
1425 | 0 | CNodeState *state = Assert(State(peer.m_id)); Line | Count | Source | 106 | 0 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
1426 | |
|
1427 | 0 | if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->GetAncestor(target_block->nHeight) != target_block) { |
1428 | | // This peer can't provide us the complete series of blocks leading up to the |
1429 | | // assumeutxo snapshot base. |
1430 | | // |
1431 | | // Presumably this peer's chain has less work than our ActiveChain()'s tip, or else we |
1432 | | // will eventually crash when we try to reorg to it. Let other logic |
1433 | | // deal with whether we disconnect this peer. |
1434 | | // |
1435 | | // TODO at some point in the future, we might choose to request what blocks |
1436 | | // this peer does have from the historical chain, despite it not having a |
1437 | | // complete history beneath the snapshot base. |
1438 | 0 | return; |
1439 | 0 | } |
1440 | | |
1441 | 0 | FindNextBlocks(vBlocks, peer, state, from_tip, count, std::min<int>(from_tip->nHeight + BLOCK_DOWNLOAD_WINDOW, target_block->nHeight)); |
1442 | 0 | } |
1443 | | |
1444 | | void PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain, NodeId* nodeStaller) |
1445 | 3.58M | { |
1446 | 3.58M | std::vector<const CBlockIndex*> vToFetch; |
1447 | 3.58M | int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); |
1448 | 3.58M | bool is_limited_peer = IsLimitedPeer(peer); |
1449 | 3.58M | NodeId waitingfor = -1; |
1450 | 3.78M | while (pindexWalk->nHeight < nMaxHeight) { |
1451 | | // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards |
1452 | | // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive |
1453 | | // as iterating over ~100 CBlockIndex* entries anyway. |
1454 | 3.58M | int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128)); |
1455 | 3.58M | vToFetch.resize(nToFetch); |
1456 | 3.58M | pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); |
1457 | 3.58M | vToFetch[nToFetch - 1] = pindexWalk; |
1458 | 6.98M | for (unsigned int i = nToFetch - 1; i > 0; i--3.39M ) { |
1459 | 3.39M | vToFetch[i - 1] = vToFetch[i]->pprev; |
1460 | 3.39M | } |
1461 | | |
1462 | | // Iterate over those blocks in vToFetch (in forward direction), adding the ones that |
1463 | | // are not yet downloaded and not in flight to vBlocks. In the meantime, update |
1464 | | // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's |
1465 | | // already part of our chain (and therefore don't need it even if pruned). |
1466 | 3.63M | for (const CBlockIndex* pindex : vToFetch) { |
1467 | 3.63M | if (!pindex->IsValid(BLOCK_VALID_TREE)) { |
1468 | | // We consider the chain that this peer is on invalid. |
1469 | 480k | return; |
1470 | 480k | } |
1471 | | |
1472 | 3.14M | if (!CanServeWitnesses(peer) && DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)2.90M ) { |
1473 | | // We wouldn't download this block or its descendants from this peer. |
1474 | 2.90M | return; |
1475 | 2.90M | } |
1476 | | |
1477 | 240k | if (pindex->nStatus & BLOCK_HAVE_DATA || (215k activeChain215k && activeChain->Contains(pindex)215k )) { |
1478 | 24.6k | if (activeChain && pindex->HaveNumChainTxs()) { |
1479 | 5.13k | state->pindexLastCommonBlock = pindex; |
1480 | 5.13k | } |
1481 | 24.6k | continue; |
1482 | 24.6k | } |
1483 | | |
1484 | | // Is block in-flight? |
1485 | 215k | if (IsBlockRequested(pindex->GetBlockHash())) { |
1486 | 210k | if (waitingfor == -1) { |
1487 | | // This is the first already-in-flight block. |
1488 | 190k | waitingfor = mapBlocksInFlight.lower_bound(pindex->GetBlockHash())->second.first; |
1489 | 190k | } |
1490 | 210k | continue; |
1491 | 210k | } |
1492 | | |
1493 | | // The block is not already downloaded, and not yet in flight. |
1494 | 5.43k | if (pindex->nHeight > nWindowEnd) { |
1495 | | // We reached the end of the window. |
1496 | 0 | if (vBlocks.size() == 0 && waitingfor != peer.m_id) { |
1497 | | // We aren't able to fetch anything, but we would be if the download window was one larger. |
1498 | 0 | if (nodeStaller) *nodeStaller = waitingfor; |
1499 | 0 | } |
1500 | 0 | return; |
1501 | 0 | } |
1502 | | |
1503 | | // Don't request blocks that go further than what limited peers can provide |
1504 | 5.43k | if (is_limited_peer && (state->pindexBestKnownBlock->nHeight - pindex->nHeight >= static_cast<int>(NODE_NETWORK_LIMITED_MIN_BLOCKS) - 2 /* two blocks buffer for possible races */)357 ) { |
1505 | 0 | continue; |
1506 | 0 | } |
1507 | | |
1508 | 5.43k | vBlocks.push_back(pindex); |
1509 | 5.43k | if (vBlocks.size() == count) { |
1510 | 235 | return; |
1511 | 235 | } |
1512 | 5.43k | } |
1513 | 3.58M | } |
1514 | 3.58M | } |
1515 | | |
1516 | | } // namespace |
1517 | | |
1518 | | void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer) |
1519 | 115k | { |
1520 | 115k | uint64_t my_services{peer.m_our_services}; |
1521 | 115k | const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())}; |
1522 | 115k | uint64_t nonce = pnode.GetLocalNonce(); |
1523 | 115k | const int nNodeStartingHeight{m_best_height}; |
1524 | 115k | NodeId nodeid = pnode.GetId(); |
1525 | 115k | CAddress addr = pnode.addr; |
1526 | | |
1527 | 115k | CService addr_you = addr.IsRoutable() && !IsProxy(addr)71.7k && addr.IsAddrV1Compatible()71.7k ? addr35.4k : CService()80.2k ; |
1528 | 115k | uint64_t your_services{addr.nServices}; |
1529 | | |
1530 | 115k | const bool tx_relay{!RejectIncomingTxs(pnode)}; |
1531 | 115k | MakeAndPushMessage(pnode, NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime, |
1532 | 115k | your_services, CNetAddr::V1(addr_you), // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime) |
1533 | 115k | my_services, CNetAddr::V1(CService{}), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime) |
1534 | 115k | nonce, strSubVersion, nNodeStartingHeight, tx_relay); |
1535 | | |
1536 | 115k | if (fLogIPs) { |
1537 | 0 | LogDebug(BCLog::NET, "send version message: version %d, blocks=%d, them=%s, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addr_you.ToStringAddrPort(), tx_relay, nodeid); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
1538 | 115k | } else { |
1539 | 115k | LogDebug(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid); Line | Count | Source | 381 | 115k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 115k | do { \ | 374 | 115k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 115k | } while (0) |
|
|
1540 | 115k | } |
1541 | 115k | } |
1542 | | |
1543 | | void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) |
1544 | 0 | { |
1545 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
1546 | 0 | CNodeState *state = State(node); |
1547 | 0 | if (state) state->m_last_block_announcement = time_in_seconds; |
1548 | 0 | } |
1549 | | |
1550 | | void PeerManagerImpl::InitializeNode(const CNode& node, ServiceFlags our_services) |
1551 | 116k | { |
1552 | 116k | NodeId nodeid = node.GetId(); |
1553 | 116k | { |
1554 | 116k | LOCK(cs_main); // For m_node_states Line | Count | Source | 259 | 116k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 116k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 116k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 116k | #define PASTE(x, y) x ## y |
|
|
|
|
1555 | 116k | m_node_states.try_emplace(m_node_states.end(), nodeid); |
1556 | 116k | } |
1557 | 116k | WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty(nodeid)); Line | Count | Source | 290 | 116k | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
1558 | | |
1559 | 116k | if (NetPermissions::HasFlag(node.m_permission_flags, NetPermissionFlags::BloomFilter)) { |
1560 | 26.4k | our_services = static_cast<ServiceFlags>(our_services | NODE_BLOOM); |
1561 | 26.4k | } |
1562 | | |
1563 | 116k | PeerRef peer = std::make_shared<Peer>(nodeid, our_services, node.IsInboundConn()); |
1564 | 116k | { |
1565 | 116k | LOCK(m_peer_mutex); Line | Count | Source | 259 | 116k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 116k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 116k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 116k | #define PASTE(x, y) x ## y |
|
|
|
|
1566 | 116k | m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer); |
1567 | 116k | } |
1568 | 116k | } |
1569 | | |
1570 | | void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler) |
1571 | 0 | { |
1572 | 0 | std::set<Txid> unbroadcast_txids = m_mempool.GetUnbroadcastTxs(); |
1573 | |
|
1574 | 0 | for (const auto& txid : unbroadcast_txids) { |
1575 | 0 | CTransactionRef tx = m_mempool.get(txid); |
1576 | |
|
1577 | 0 | if (tx != nullptr) { |
1578 | 0 | RelayTransaction(txid, tx->GetWitnessHash()); |
1579 | 0 | } else { |
1580 | 0 | m_mempool.RemoveUnbroadcastTx(txid, true); |
1581 | 0 | } |
1582 | 0 | } |
1583 | | |
1584 | | // Schedule next run for 10-15 minutes in the future. |
1585 | | // We add randomness on every cycle to avoid the possibility of P2P fingerprinting. |
1586 | 0 | const auto delta = 10min + FastRandomContext().randrange<std::chrono::milliseconds>(5min); |
1587 | 0 | scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta); |
1588 | 0 | } |
1589 | | |
1590 | | void PeerManagerImpl::FinalizeNode(const CNode& node) |
1591 | 116k | { |
1592 | 116k | NodeId nodeid = node.GetId(); |
1593 | 116k | { |
1594 | 116k | LOCK(cs_main); Line | Count | Source | 259 | 116k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 116k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 116k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 116k | #define PASTE(x, y) x ## y |
|
|
|
|
1595 | 116k | { |
1596 | | // We remove the PeerRef from g_peer_map here, but we don't always |
1597 | | // destruct the Peer. Sometimes another thread is still holding a |
1598 | | // PeerRef, so the refcount is >= 1. Be careful not to do any |
1599 | | // processing here that assumes Peer won't be changed before it's |
1600 | | // destructed. |
1601 | 116k | PeerRef peer = RemovePeer(nodeid); |
1602 | 116k | assert(peer != nullptr); |
1603 | 116k | m_wtxid_relay_peers -= peer->m_wtxid_relay; |
1604 | 116k | assert(m_wtxid_relay_peers >= 0); |
1605 | 116k | } |
1606 | 116k | CNodeState *state = State(nodeid); |
1607 | 116k | assert(state != nullptr); |
1608 | | |
1609 | 116k | if (state->fSyncStarted) |
1610 | 38.6k | nSyncStarted--; |
1611 | | |
1612 | 116k | for (const QueuedBlock& entry : state->vBlocksInFlight) { |
1613 | 71.3k | auto range = mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash()); |
1614 | 143k | while (range.first != range.second) { |
1615 | 72.5k | auto [node_id, list_it] = range.first->second; |
1616 | 72.5k | if (node_id != nodeid) { |
1617 | 1.21k | range.first++; |
1618 | 71.3k | } else { |
1619 | 71.3k | range.first = mapBlocksInFlight.erase(range.first); |
1620 | 71.3k | } |
1621 | 72.5k | } |
1622 | 71.3k | } |
1623 | 116k | { |
1624 | 116k | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 116k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 116k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 116k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 116k | #define PASTE(x, y) x ## y |
|
|
|
|
1625 | 116k | m_txdownloadman.DisconnectedPeer(nodeid); |
1626 | 116k | } |
1627 | 116k | if (m_txreconciliation) m_txreconciliation->ForgetPeer(nodeid)0 ; |
1628 | 116k | m_num_preferred_download_peers -= state->fPreferredDownload; |
1629 | 116k | m_peers_downloading_from -= (!state->vBlocksInFlight.empty()); |
1630 | 116k | assert(m_peers_downloading_from >= 0); |
1631 | 116k | m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect; |
1632 | 116k | assert(m_outbound_peers_with_protect_from_disconnect >= 0); |
1633 | | |
1634 | 116k | m_node_states.erase(nodeid); |
1635 | | |
1636 | 116k | if (m_node_states.empty()) { |
1637 | | // Do a consistency check after the last peer is removed. |
1638 | 38.8k | assert(mapBlocksInFlight.empty()); |
1639 | 38.8k | assert(m_num_preferred_download_peers == 0); |
1640 | 38.8k | assert(m_peers_downloading_from == 0); |
1641 | 38.8k | assert(m_outbound_peers_with_protect_from_disconnect == 0); |
1642 | 38.8k | assert(m_wtxid_relay_peers == 0); |
1643 | 38.8k | WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty()); Line | Count | Source | 290 | 38.8k | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
1644 | 38.8k | } |
1645 | 116k | } // cs_main |
1646 | 116k | if (node.fSuccessfullyConnected && |
1647 | 116k | !node.IsBlockOnlyConn()77.0k && !node.IsInboundConn()76.3k ) { |
1648 | | // Only change visible addrman state for full outbound peers. We don't |
1649 | | // call Connected() for feeler connections since they don't have |
1650 | | // fSuccessfullyConnected set. |
1651 | 46.5k | m_addrman.Connected(node.addr); |
1652 | 46.5k | } |
1653 | 116k | { |
1654 | 116k | LOCK(m_headers_presync_mutex); Line | Count | Source | 259 | 116k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 116k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 116k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 116k | #define PASTE(x, y) x ## y |
|
|
|
|
1655 | 116k | m_headers_presync_stats.erase(nodeid); |
1656 | 116k | } |
1657 | 116k | LogDebug(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid); Line | Count | Source | 381 | 116k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 116k | do { \ | 374 | 116k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 116k | } while (0) |
|
|
1658 | 116k | } |
1659 | | |
1660 | | bool PeerManagerImpl::HasAllDesirableServiceFlags(ServiceFlags services) const |
1661 | 117k | { |
1662 | | // Shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services) |
1663 | 117k | return !(GetDesirableServiceFlags(services) & (~services)); |
1664 | 117k | } |
1665 | | |
1666 | | ServiceFlags PeerManagerImpl::GetDesirableServiceFlags(ServiceFlags services) const |
1667 | 117k | { |
1668 | 117k | if (services & NODE_NETWORK_LIMITED) { |
1669 | | // Limited peers are desirable when we are close to the tip. |
1670 | 41.0k | if (ApproximateBestBlockDepth() < NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS) { |
1671 | 0 | return ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS); |
1672 | 0 | } |
1673 | 41.0k | } |
1674 | 117k | return ServiceFlags(NODE_NETWORK | NODE_WITNESS); |
1675 | 117k | } |
1676 | | |
1677 | | PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const |
1678 | 21.4M | { |
1679 | 21.4M | LOCK(m_peer_mutex); Line | Count | Source | 259 | 21.4M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 21.4M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 21.4M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 21.4M | #define PASTE(x, y) x ## y |
|
|
|
|
1680 | 21.4M | auto it = m_peer_map.find(id); |
1681 | 21.4M | return it != m_peer_map.end() ? it->second : nullptr0 ; |
1682 | 21.4M | } |
1683 | | |
1684 | | PeerRef PeerManagerImpl::RemovePeer(NodeId id) |
1685 | 116k | { |
1686 | 116k | PeerRef ret; |
1687 | 116k | LOCK(m_peer_mutex); Line | Count | Source | 259 | 116k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 116k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 116k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 116k | #define PASTE(x, y) x ## y |
|
|
|
|
1688 | 116k | auto it = m_peer_map.find(id); |
1689 | 116k | if (it != m_peer_map.end()) { |
1690 | 116k | ret = std::move(it->second); |
1691 | 116k | m_peer_map.erase(it); |
1692 | 116k | } |
1693 | 116k | return ret; |
1694 | 116k | } |
1695 | | |
1696 | | bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const |
1697 | 84.1k | { |
1698 | 84.1k | { |
1699 | 84.1k | LOCK(cs_main); Line | Count | Source | 259 | 84.1k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 84.1k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 84.1k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 84.1k | #define PASTE(x, y) x ## y |
|
|
|
|
1700 | 84.1k | const CNodeState* state = State(nodeid); |
1701 | 84.1k | if (state == nullptr) |
1702 | 0 | return false; |
1703 | 84.1k | stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight0 : -1; |
1704 | 84.1k | stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight0 : -1; |
1705 | 84.1k | for (const QueuedBlock& queue : state->vBlocksInFlight) { |
1706 | 0 | if (queue.pindex) |
1707 | 0 | stats.vHeightInFlight.push_back(queue.pindex->nHeight); |
1708 | 0 | } |
1709 | 84.1k | } |
1710 | | |
1711 | 0 | PeerRef peer = GetPeerRef(nodeid); |
1712 | 84.1k | if (peer == nullptr) return false0 ; |
1713 | 84.1k | stats.their_services = peer->m_their_services; |
1714 | 84.1k | stats.m_starting_height = peer->m_starting_height; |
1715 | | // It is common for nodes with good ping times to suddenly become lagged, |
1716 | | // due to a new block arriving or other large transfer. |
1717 | | // Merely reporting pingtime might fool the caller into thinking the node was still responsive, |
1718 | | // since pingtime does not update until the ping is complete, which might take a while. |
1719 | | // So, if a ping is taking an unusually long time in flight, |
1720 | | // the caller can immediately detect that this is happening. |
1721 | 84.1k | auto ping_wait{0us}; |
1722 | 84.1k | if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())0 ) { |
1723 | 0 | ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load(); |
1724 | 0 | } |
1725 | | |
1726 | 84.1k | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { |
1727 | 55.9k | stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs); Line | Count | Source | 290 | 55.9k | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
1728 | 55.9k | stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load(); |
1729 | 55.9k | } else { |
1730 | 28.2k | stats.m_relay_txs = false; |
1731 | 28.2k | stats.m_fee_filter_received = 0; |
1732 | 28.2k | } |
1733 | | |
1734 | 84.1k | stats.m_ping_wait = ping_wait; |
1735 | 84.1k | stats.m_addr_processed = peer->m_addr_processed.load(); |
1736 | 84.1k | stats.m_addr_rate_limited = peer->m_addr_rate_limited.load(); |
1737 | 84.1k | stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load(); |
1738 | 84.1k | { |
1739 | 84.1k | LOCK(peer->m_headers_sync_mutex); Line | Count | Source | 259 | 84.1k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 84.1k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 84.1k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 84.1k | #define PASTE(x, y) x ## y |
|
|
|
|
1740 | 84.1k | if (peer->m_headers_sync) { |
1741 | 0 | stats.presync_height = peer->m_headers_sync->GetPresyncHeight(); |
1742 | 0 | } |
1743 | 84.1k | } |
1744 | 84.1k | stats.time_offset = peer->m_time_offset; |
1745 | | |
1746 | 84.1k | return true; |
1747 | 84.1k | } |
1748 | | |
1749 | | std::vector<node::TxOrphanage::OrphanInfo> PeerManagerImpl::GetOrphanTransactions() |
1750 | 0 | { |
1751 | 0 | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
1752 | 0 | return m_txdownloadman.GetOrphanTransactions(); |
1753 | 0 | } |
1754 | | |
1755 | | PeerManagerInfo PeerManagerImpl::GetInfo() const |
1756 | 0 | { |
1757 | 0 | return PeerManagerInfo{ |
1758 | 0 | .median_outbound_time_offset = m_outbound_time_offsets.Median(), |
1759 | 0 | .ignores_incoming_txs = m_opts.ignore_incoming_txs, |
1760 | 0 | }; |
1761 | 0 | } |
1762 | | |
1763 | | void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx) |
1764 | 195k | { |
1765 | 195k | if (m_opts.max_extra_txs <= 0) |
1766 | 0 | return; |
1767 | 195k | if (!vExtraTxnForCompact.size()) |
1768 | 21.2k | vExtraTxnForCompact.resize(m_opts.max_extra_txs); |
1769 | 195k | vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx); |
1770 | 195k | vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs; |
1771 | 195k | } |
1772 | | |
1773 | | void PeerManagerImpl::Misbehaving(Peer& peer, const std::string& message) |
1774 | 1.52M | { |
1775 | 1.52M | LOCK(peer.m_misbehavior_mutex); Line | Count | Source | 259 | 1.52M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 1.52M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 1.52M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 1.52M | #define PASTE(x, y) x ## y |
|
|
|
|
1776 | | |
1777 | 1.52M | const std::string message_prefixed = message.empty() ? ""0 : (": " + message); |
1778 | 1.52M | peer.m_should_discourage = true; |
1779 | 1.52M | LogDebug(BCLog::NET, "Misbehaving: peer=%d%s\n", peer.m_id, message_prefixed); Line | Count | Source | 381 | 1.52M | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 1.52M | do { \ | 374 | 1.52M | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 1.52M | } while (0) |
|
|
1780 | 1.52M | TRACEPOINT(net, misbehaving_connection, |
1781 | 1.52M | peer.m_id, |
1782 | 1.52M | message.c_str() |
1783 | 1.52M | ); |
1784 | 1.52M | } |
1785 | | |
1786 | | void PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state, |
1787 | | bool via_compact_block, const std::string& message) |
1788 | 2.03M | { |
1789 | 2.03M | PeerRef peer{GetPeerRef(nodeid)}; |
1790 | 2.03M | switch (state.GetResult()) { |
1791 | 0 | case BlockValidationResult::BLOCK_RESULT_UNSET: |
1792 | 0 | break; |
1793 | 0 | case BlockValidationResult::BLOCK_HEADER_LOW_WORK: |
1794 | | // We didn't try to process the block because the header chain may have |
1795 | | // too little work. |
1796 | 0 | break; |
1797 | | // The node is providing invalid data: |
1798 | 162k | case BlockValidationResult::BLOCK_CONSENSUS: |
1799 | 162k | case BlockValidationResult::BLOCK_MUTATED: |
1800 | 162k | if (!via_compact_block) { |
1801 | 0 | if (peer) Misbehaving(*peer, message); |
1802 | 0 | return; |
1803 | 0 | } |
1804 | 162k | break; |
1805 | 1.01M | case BlockValidationResult::BLOCK_CACHED_INVALID: |
1806 | 1.01M | { |
1807 | | // Discourage outbound (but not inbound) peers if on an invalid chain. |
1808 | | // Exempt HB compact block peers. Manual connections are always protected from discouragement. |
1809 | 1.01M | if (peer && !via_compact_block && !peer->m_is_inbound504k ) { |
1810 | 492k | if (peer) Misbehaving(*peer, message); |
1811 | 492k | return; |
1812 | 492k | } |
1813 | 517k | break; |
1814 | 1.01M | } |
1815 | 826k | case BlockValidationResult::BLOCK_INVALID_HEADER: |
1816 | 840k | case BlockValidationResult::BLOCK_INVALID_PREV: |
1817 | 840k | if (peer) Misbehaving(*peer, message); |
1818 | 840k | return; |
1819 | | // Conflicting (but not necessarily invalid) data or different policy: |
1820 | 0 | case BlockValidationResult::BLOCK_MISSING_PREV: |
1821 | 0 | if (peer) Misbehaving(*peer, message); |
1822 | 0 | return; |
1823 | 16.9k | case BlockValidationResult::BLOCK_TIME_FUTURE: |
1824 | 16.9k | break; |
1825 | 2.03M | } |
1826 | 697k | if (message != "") { |
1827 | 534k | LogDebug(BCLog::NET, "peer=%d: %s\n", nodeid, message); Line | Count | Source | 381 | 534k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 534k | do { \ | 374 | 534k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 534k | } while (0) |
|
|
1828 | 534k | } |
1829 | 697k | } |
1830 | | |
1831 | | bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex) |
1832 | 0 | { |
1833 | 0 | AssertLockHeld(cs_main); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
1834 | 0 | if (m_chainman.ActiveChain().Contains(pindex)) return true; |
1835 | 0 | return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (m_chainman.m_best_header != nullptr) && |
1836 | 0 | (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) && |
1837 | 0 | (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT); |
1838 | 0 | } |
1839 | | |
1840 | | std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index) |
1841 | 0 | { |
1842 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) return "Loading blocks ..."; |
1843 | | |
1844 | | // Ensure this peer exists and hasn't been disconnected |
1845 | 0 | PeerRef peer = GetPeerRef(peer_id); |
1846 | 0 | if (peer == nullptr) return "Peer does not exist"; |
1847 | | |
1848 | | // Ignore pre-segwit peers |
1849 | 0 | if (!CanServeWitnesses(*peer)) return "Pre-SegWit peer"; |
1850 | | |
1851 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
1852 | | |
1853 | | // Forget about all prior requests |
1854 | 0 | RemoveBlockRequest(block_index.GetBlockHash(), std::nullopt); |
1855 | | |
1856 | | // Mark block as in-flight |
1857 | 0 | if (!BlockRequested(peer_id, block_index)) return "Already requested from this peer"; |
1858 | | |
1859 | | // Construct message to request the block |
1860 | 0 | const uint256& hash{block_index.GetBlockHash()}; |
1861 | 0 | std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)}; |
1862 | | |
1863 | | // Send block request message to the peer |
1864 | 0 | bool success = m_connman.ForNode(peer_id, [this, &invs](CNode* node) { |
1865 | 0 | this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs); |
1866 | 0 | return true; |
1867 | 0 | }); |
1868 | |
|
1869 | 0 | if (!success) return "Peer not fully connected"; |
1870 | | |
1871 | 0 | LogDebug(BCLog::NET, "Requesting block %s from peer=%d\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
1872 | 0 | hash.ToString(), peer_id); |
1873 | 0 | return std::nullopt; |
1874 | 0 | } |
1875 | | |
1876 | | std::unique_ptr<PeerManager> PeerManager::make(CConnman& connman, AddrMan& addrman, |
1877 | | BanMan* banman, ChainstateManager& chainman, |
1878 | | CTxMemPool& pool, node::Warnings& warnings, Options opts) |
1879 | 38.8k | { |
1880 | 38.8k | return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman, pool, warnings, opts); |
1881 | 38.8k | } |
1882 | | |
1883 | | PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman, |
1884 | | BanMan* banman, ChainstateManager& chainman, |
1885 | | CTxMemPool& pool, node::Warnings& warnings, Options opts) |
1886 | 38.8k | : m_rng{opts.deterministic_rng}, |
1887 | 38.8k | m_fee_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}, m_rng}, |
1888 | 38.8k | m_chainparams(chainman.GetParams()), |
1889 | 38.8k | m_connman(connman), |
1890 | 38.8k | m_addrman(addrman), |
1891 | 38.8k | m_banman(banman), |
1892 | 38.8k | m_chainman(chainman), |
1893 | 38.8k | m_mempool(pool), |
1894 | 38.8k | m_txdownloadman(node::TxDownloadOptions{pool, m_rng, opts.deterministic_rng}), |
1895 | 38.8k | m_warnings{warnings}, |
1896 | 38.8k | m_opts{opts} |
1897 | 38.8k | { |
1898 | | // While Erlay support is incomplete, it must be enabled explicitly via -txreconciliation. |
1899 | | // This argument can go away after Erlay support is complete. |
1900 | 38.8k | if (opts.reconcile_txs) { |
1901 | 0 | m_txreconciliation = std::make_unique<TxReconciliationTracker>(TXRECONCILIATION_VERSION); |
1902 | 0 | } |
1903 | 38.8k | } |
1904 | | |
1905 | | void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler) |
1906 | 0 | { |
1907 | | // Stale tip checking and peer eviction are on two different timers, but we |
1908 | | // don't want them to get out of sync due to drift in the scheduler, so we |
1909 | | // combine them in one function and schedule at the quicker (peer-eviction) |
1910 | | // timer. |
1911 | 0 | static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer"); |
1912 | 0 | scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL}); |
1913 | | |
1914 | | // schedule next run for 10-15 minutes in the future |
1915 | 0 | const auto delta = 10min + FastRandomContext().randrange<std::chrono::milliseconds>(5min); |
1916 | 0 | scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta); |
1917 | 0 | } |
1918 | | |
1919 | | void PeerManagerImpl::ActiveTipChange(const CBlockIndex& new_tip, bool is_ibd) |
1920 | 188k | { |
1921 | | // Ensure mempool mutex was released, otherwise deadlock may occur if another thread holding |
1922 | | // m_tx_download_mutex waits on the mempool mutex. |
1923 | 188k | AssertLockNotHeld(m_mempool.cs); Line | Count | Source | 142 | 188k | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
1924 | 188k | AssertLockNotHeld(m_tx_download_mutex); Line | Count | Source | 142 | 188k | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
1925 | | |
1926 | 188k | if (!is_ibd) { |
1927 | 188k | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 188k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 188k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 188k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 188k | #define PASTE(x, y) x ## y |
|
|
|
|
1928 | | // If the chain tip has changed, previously rejected transactions might now be valid, e.g. due |
1929 | | // to a timelock. Reset the rejection filters to give those transactions another chance if we |
1930 | | // see them again. |
1931 | 188k | m_txdownloadman.ActiveTipChange(); |
1932 | 188k | } |
1933 | 188k | } |
1934 | | |
1935 | | /** |
1936 | | * Evict orphan txn pool entries based on a newly connected |
1937 | | * block, remember the recently confirmed transactions, and delete tracked |
1938 | | * announcements for them. Also save the time of the last tip update and |
1939 | | * possibly reduce dynamic block stalling timeout. |
1940 | | */ |
1941 | | void PeerManagerImpl::BlockConnected( |
1942 | | ChainstateRole role, |
1943 | | const std::shared_ptr<const CBlock>& pblock, |
1944 | | const CBlockIndex* pindex) |
1945 | 31.4k | { |
1946 | | // Update this for all chainstate roles so that we don't mistakenly see peers |
1947 | | // helping us do background IBD as having a stale tip. |
1948 | 31.4k | m_last_tip_update = GetTime<std::chrono::seconds>(); |
1949 | | |
1950 | | // In case the dynamic timeout was doubled once or more, reduce it slowly back to its default value |
1951 | 31.4k | auto stalling_timeout = m_block_stalling_timeout.load(); |
1952 | 31.4k | Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT); Line | Count | Source | 118 | 31.4k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
1953 | 31.4k | if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) { |
1954 | 0 | const auto new_timeout = std::max(std::chrono::duration_cast<std::chrono::seconds>(stalling_timeout * 0.85), BLOCK_STALLING_TIMEOUT_DEFAULT); |
1955 | 0 | if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { |
1956 | 0 | LogDebug(BCLog::NET, "Decreased stalling timeout to %d seconds\n", count_seconds(new_timeout)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
1957 | 0 | } |
1958 | 0 | } |
1959 | | |
1960 | | // The following task can be skipped since we don't maintain a mempool for |
1961 | | // the ibd/background chainstate. |
1962 | 31.4k | if (role == ChainstateRole::BACKGROUND) { |
1963 | 0 | return; |
1964 | 0 | } |
1965 | 31.4k | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 31.4k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 31.4k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 31.4k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 31.4k | #define PASTE(x, y) x ## y |
|
|
|
|
1966 | 31.4k | m_txdownloadman.BlockConnected(pblock); |
1967 | 31.4k | } |
1968 | | |
1969 | | void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) |
1970 | 4.80k | { |
1971 | 4.80k | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 4.80k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 4.80k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 4.80k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 4.80k | #define PASTE(x, y) x ## y |
|
|
|
|
1972 | 4.80k | m_txdownloadman.BlockDisconnected(); |
1973 | 4.80k | } |
1974 | | |
1975 | | /** |
1976 | | * Maintain state about the best-seen block and fast-announce a compact block |
1977 | | * to compatible peers. |
1978 | | */ |
1979 | | void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) |
1980 | 184k | { |
1981 | 184k | auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock, FastRandomContext().rand64()); |
1982 | | |
1983 | 184k | LOCK(cs_main); Line | Count | Source | 259 | 184k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 184k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 184k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 184k | #define PASTE(x, y) x ## y |
|
|
|
|
1984 | | |
1985 | 184k | if (pindex->nHeight <= m_highest_fast_announce) |
1986 | 153k | return; |
1987 | 30.7k | m_highest_fast_announce = pindex->nHeight; |
1988 | | |
1989 | 30.7k | if (!DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) return0 ; |
1990 | | |
1991 | 30.7k | uint256 hashBlock(pblock->GetHash()); |
1992 | 30.7k | const std::shared_future<CSerializedNetMsg> lazy_ser{ |
1993 | 30.7k | std::async(std::launch::deferred, [&] { return NetMsg::Make(NetMsgType::CMPCTBLOCK, *pcmpctblock); }5.25k )}; |
1994 | | |
1995 | 30.7k | { |
1996 | 30.7k | auto most_recent_block_txs = std::make_unique<std::map<GenTxid, CTransactionRef>>(); |
1997 | 59.2k | for (const auto& tx : pblock->vtx) { |
1998 | 59.2k | most_recent_block_txs->emplace(tx->GetHash(), tx); |
1999 | 59.2k | most_recent_block_txs->emplace(tx->GetWitnessHash(), tx); |
2000 | 59.2k | } |
2001 | | |
2002 | 30.7k | LOCK(m_most_recent_block_mutex); Line | Count | Source | 259 | 30.7k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 30.7k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 30.7k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 30.7k | #define PASTE(x, y) x ## y |
|
|
|
|
2003 | 30.7k | m_most_recent_block_hash = hashBlock; |
2004 | 30.7k | m_most_recent_block = pblock; |
2005 | 30.7k | m_most_recent_compact_block = pcmpctblock; |
2006 | 30.7k | m_most_recent_block_txs = std::move(most_recent_block_txs); |
2007 | 30.7k | } |
2008 | | |
2009 | 61.0k | m_connman.ForEachNode([this, pindex, &lazy_ser, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
2010 | 61.0k | AssertLockHeld(::cs_main); Line | Count | Source | 137 | 61.0k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
2011 | | |
2012 | 61.0k | if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect60.7k ) |
2013 | 257 | return; |
2014 | 60.7k | ProcessBlockAvailability(pnode->GetId()); |
2015 | 60.7k | CNodeState &state = *State(pnode->GetId()); |
2016 | | // If the peer has, or we announced to them the previous block already, |
2017 | | // but we don't think they have this one, go ahead and announce it |
2018 | 60.7k | if (state.m_requested_hb_cmpctblocks && !PeerHasHeader(&state, pindex)28.4k && PeerHasHeader(&state, pindex->pprev)14.4k ) { |
2019 | | |
2020 | 5.35k | LogDebug(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock", Line | Count | Source | 381 | 5.35k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 5.35k | do { \ | 374 | 5.35k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 5.35k | } while (0) |
|
|
2021 | 5.35k | hashBlock.ToString(), pnode->GetId()); |
2022 | | |
2023 | 5.35k | const CSerializedNetMsg& ser_cmpctblock{lazy_ser.get()}; |
2024 | 5.35k | PushMessage(*pnode, ser_cmpctblock.Copy()); |
2025 | 5.35k | state.pindexBestHeaderSent = pindex; |
2026 | 5.35k | } |
2027 | 60.7k | }); |
2028 | 30.7k | } |
2029 | | |
2030 | | /** |
2031 | | * Update our best height and announce any block hashes which weren't previously |
2032 | | * in m_chainman.ActiveChain() to our peers. |
2033 | | */ |
2034 | | void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) |
2035 | 26.6k | { |
2036 | 26.6k | SetBestBlock(pindexNew->nHeight, std::chrono::seconds{pindexNew->GetBlockTime()}); |
2037 | | |
2038 | | // Don't relay inventory during initial block download. |
2039 | 26.6k | if (fInitialDownload) return449 ; |
2040 | | |
2041 | | // Find the hashes of all blocks that weren't previously in the best chain. |
2042 | 26.1k | std::vector<uint256> vHashes; |
2043 | 26.1k | const CBlockIndex *pindexToAnnounce = pindexNew; |
2044 | 52.6k | while (pindexToAnnounce != pindexFork) { |
2045 | 26.4k | vHashes.push_back(pindexToAnnounce->GetBlockHash()); |
2046 | 26.4k | pindexToAnnounce = pindexToAnnounce->pprev; |
2047 | 26.4k | if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) { |
2048 | | // Limit announcements in case of a huge reorganization. |
2049 | | // Rely on the peer's synchronization mechanism in that case. |
2050 | 0 | break; |
2051 | 0 | } |
2052 | 26.4k | } |
2053 | | |
2054 | 26.1k | { |
2055 | 26.1k | LOCK(m_peer_mutex); Line | Count | Source | 259 | 26.1k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 26.1k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 26.1k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 26.1k | #define PASTE(x, y) x ## y |
|
|
|
|
2056 | 78.4k | for (auto& it : m_peer_map) { |
2057 | 78.4k | Peer& peer = *it.second; |
2058 | 78.4k | LOCK(peer.m_block_inv_mutex); Line | Count | Source | 259 | 78.4k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 78.4k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 78.4k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 78.4k | #define PASTE(x, y) x ## y |
|
|
|
|
2059 | 79.3k | for (const uint256& hash : vHashes | std::views::reverse) { |
2060 | 79.3k | peer.m_blocks_for_headers_relay.push_back(hash); |
2061 | 79.3k | } |
2062 | 78.4k | } |
2063 | 26.1k | } |
2064 | | |
2065 | 26.1k | m_connman.WakeMessageHandler(); |
2066 | 26.1k | } |
2067 | | |
2068 | | /** |
2069 | | * Handle invalid block rejection and consequent peer discouragement, maintain which |
2070 | | * peers announce compact blocks. |
2071 | | */ |
2072 | | void PeerManagerImpl::BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) |
2073 | 193k | { |
2074 | 193k | LOCK(cs_main); Line | Count | Source | 259 | 193k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 193k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 193k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 193k | #define PASTE(x, y) x ## y |
|
|
|
|
2075 | | |
2076 | 193k | const uint256 hash(block->GetHash()); |
2077 | 193k | std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash); |
2078 | | |
2079 | | // If the block failed validation, we know where it came from and we're still connected |
2080 | | // to that peer, maybe punish. |
2081 | 193k | if (state.IsInvalid() && |
2082 | 193k | it != mapBlockSource.end()162k && |
2083 | 193k | State(it->second.first)162k ) { |
2084 | 162k | MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second); |
2085 | 162k | } |
2086 | | // Check that: |
2087 | | // 1. The block is valid |
2088 | | // 2. We're not in initial block download |
2089 | | // 3. This is currently the best block we're aware of. We haven't updated |
2090 | | // the tip yet so we have no way to check this directly here. Instead we |
2091 | | // just check that there are currently no other blocks in flight. |
2092 | 31.4k | else if (state.IsValid() && |
2093 | 31.4k | !m_chainman.IsInitialBlockDownload() && |
2094 | 31.4k | mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()30.9k ) { |
2095 | 9.88k | if (it != mapBlockSource.end()) { |
2096 | 8.32k | MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first); |
2097 | 8.32k | } |
2098 | 9.88k | } |
2099 | 193k | if (it != mapBlockSource.end()) |
2100 | 190k | mapBlockSource.erase(it); |
2101 | 193k | } |
2102 | | |
2103 | | ////////////////////////////////////////////////////////////////////////////// |
2104 | | // |
2105 | | // Messages |
2106 | | // |
2107 | | |
2108 | | bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash) |
2109 | 0 | { |
2110 | 0 | return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr; |
2111 | 0 | } |
2112 | | |
2113 | | void PeerManagerImpl::SendPings() |
2114 | 0 | { |
2115 | 0 | LOCK(m_peer_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2116 | 0 | for(auto& it : m_peer_map) it.second->m_ping_queued = true; |
2117 | 0 | } |
2118 | | |
2119 | | void PeerManagerImpl::RelayTransaction(const Txid& txid, const Wtxid& wtxid) |
2120 | 759k | { |
2121 | 759k | LOCK(m_peer_mutex); Line | Count | Source | 259 | 759k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 759k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 759k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 759k | #define PASTE(x, y) x ## y |
|
|
|
|
2122 | 2.27M | for(auto& it : m_peer_map) { |
2123 | 2.27M | Peer& peer = *it.second; |
2124 | 2.27M | auto tx_relay = peer.GetTxRelay(); |
2125 | 2.27M | if (!tx_relay) continue831k ; |
2126 | | |
2127 | 1.44M | LOCK(tx_relay->m_tx_inventory_mutex); Line | Count | Source | 259 | 1.44M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 1.44M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 1.44M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 1.44M | #define PASTE(x, y) x ## y |
|
|
|
|
2128 | | // Only queue transactions for announcement once the version handshake |
2129 | | // is completed. The time of arrival for these transactions is |
2130 | | // otherwise at risk of leaking to a spy, if the spy is able to |
2131 | | // distinguish transactions received during the handshake from the rest |
2132 | | // in the announcement. |
2133 | 1.44M | if (tx_relay->m_next_inv_send_time == 0s) continue2.02k ; |
2134 | | |
2135 | 1.44M | const uint256& hash{peer.m_wtxid_relay ? wtxid.ToUint256()0 : txid.ToUint256()}; |
2136 | 1.44M | if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) { |
2137 | 1.09M | tx_relay->m_tx_inventory_to_send.insert(wtxid); |
2138 | 1.09M | } |
2139 | 1.44M | } |
2140 | 759k | } |
2141 | | |
2142 | | void PeerManagerImpl::RelayAddress(NodeId originator, |
2143 | | const CAddress& addr, |
2144 | | bool fReachable) |
2145 | 0 | { |
2146 | | // We choose the same nodes within a given 24h window (if the list of connected |
2147 | | // nodes does not change) and we don't relay to nodes that already know an |
2148 | | // address. So within 24h we will likely relay a given address once. This is to |
2149 | | // prevent a peer from unjustly giving their address better propagation by sending |
2150 | | // it to us repeatedly. |
2151 | |
|
2152 | 0 | if (!fReachable && !addr.IsRelayable()) return; |
2153 | | |
2154 | | // Relay to a limited number of other nodes |
2155 | | // Use deterministic randomness to send to the same nodes for 24 hours |
2156 | | // at a time so the m_addr_knowns of the chosen nodes prevent repeats |
2157 | 0 | const uint64_t hash_addr{CServiceHash(0, 0)(addr)}; |
2158 | 0 | const auto current_time{GetTime<std::chrono::seconds>()}; |
2159 | | // Adding address hash makes exact rotation time different per address, while preserving periodicity. |
2160 | 0 | const uint64_t time_addr{(static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) / count_seconds(ROTATE_ADDR_RELAY_DEST_INTERVAL)}; |
2161 | 0 | const CSipHasher hasher{m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY) |
2162 | 0 | .Write(hash_addr) |
2163 | 0 | .Write(time_addr)}; |
2164 | | |
2165 | | // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers. |
2166 | 0 | unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1; |
2167 | |
|
2168 | 0 | std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}}; |
2169 | 0 | assert(nRelayNodes <= best.size()); |
2170 | | |
2171 | 0 | LOCK(m_peer_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2172 | |
|
2173 | 0 | for (auto& [id, peer] : m_peer_map) { |
2174 | 0 | if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) { |
2175 | 0 | uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize(); |
2176 | 0 | for (unsigned int i = 0; i < nRelayNodes; i++) { |
2177 | 0 | if (hashKey > best[i].first) { |
2178 | 0 | std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1); |
2179 | 0 | best[i] = std::make_pair(hashKey, peer.get()); |
2180 | 0 | break; |
2181 | 0 | } |
2182 | 0 | } |
2183 | 0 | } |
2184 | 0 | }; |
2185 | |
|
2186 | 0 | for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) { |
2187 | 0 | PushAddress(*best[i].second, addr); |
2188 | 0 | } |
2189 | 0 | } |
2190 | | |
2191 | | void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv) |
2192 | 0 | { |
2193 | 0 | std::shared_ptr<const CBlock> a_recent_block; |
2194 | 0 | std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block; |
2195 | 0 | { |
2196 | 0 | LOCK(m_most_recent_block_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2197 | 0 | a_recent_block = m_most_recent_block; |
2198 | 0 | a_recent_compact_block = m_most_recent_compact_block; |
2199 | 0 | } |
2200 | |
|
2201 | 0 | bool need_activate_chain = false; |
2202 | 0 | { |
2203 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2204 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash); |
2205 | 0 | if (pindex) { |
2206 | 0 | if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) && |
2207 | 0 | pindex->IsValid(BLOCK_VALID_TREE)) { |
2208 | | // If we have the block and all of its parents, but have not yet validated it, |
2209 | | // we might be in the middle of connecting it (ie in the unlock of cs_main |
2210 | | // before ActivateBestChain but after AcceptBlock). |
2211 | | // In this case, we need to run ActivateBestChain prior to checking the relay |
2212 | | // conditions below. |
2213 | 0 | need_activate_chain = true; |
2214 | 0 | } |
2215 | 0 | } |
2216 | 0 | } // release cs_main before calling ActivateBestChain |
2217 | 0 | if (need_activate_chain) { |
2218 | 0 | BlockValidationState state; |
2219 | 0 | if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) { |
2220 | 0 | LogDebug(BCLog::NET, "failed to activate chain (%s)\n", state.ToString()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2221 | 0 | } |
2222 | 0 | } |
2223 | |
|
2224 | 0 | const CBlockIndex* pindex{nullptr}; |
2225 | 0 | const CBlockIndex* tip{nullptr}; |
2226 | 0 | bool can_direct_fetch{false}; |
2227 | 0 | FlatFilePos block_pos{}; |
2228 | 0 | { |
2229 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2230 | 0 | pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash); |
2231 | 0 | if (!pindex) { |
2232 | 0 | return; |
2233 | 0 | } |
2234 | 0 | if (!BlockRequestAllowed(pindex)) { |
2235 | 0 | LogDebug(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2236 | 0 | return; |
2237 | 0 | } |
2238 | | // disconnect node in case we have reached the outbound limit for serving historical blocks |
2239 | 0 | if (m_connman.OutboundTargetReached(true) && |
2240 | 0 | (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) && |
2241 | 0 | !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target |
2242 | 0 | ) { |
2243 | 0 | LogDebug(BCLog::NET, "historical block serving limit reached, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2244 | 0 | pfrom.fDisconnect = true; |
2245 | 0 | return; |
2246 | 0 | } |
2247 | 0 | tip = m_chainman.ActiveChain().Tip(); |
2248 | | // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold |
2249 | 0 | if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && ( |
2250 | 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 */) ) |
2251 | 0 | )) { |
2252 | 0 | LogDebug(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2253 | | //disconnect node and prevent it from stalling (would otherwise wait for the missing block) |
2254 | 0 | pfrom.fDisconnect = true; |
2255 | 0 | return; |
2256 | 0 | } |
2257 | | // Pruned nodes may have deleted the block, so check whether |
2258 | | // it's available before trying to send. |
2259 | 0 | if (!(pindex->nStatus & BLOCK_HAVE_DATA)) { |
2260 | 0 | return; |
2261 | 0 | } |
2262 | 0 | can_direct_fetch = CanDirectFetch(); |
2263 | 0 | block_pos = pindex->GetBlockPos(); |
2264 | 0 | } |
2265 | | |
2266 | 0 | std::shared_ptr<const CBlock> pblock; |
2267 | 0 | if (a_recent_block && a_recent_block->GetHash() == inv.hash) { |
2268 | 0 | pblock = a_recent_block; |
2269 | 0 | } else if (inv.IsMsgWitnessBlk()) { |
2270 | | // Fast-path: in this case it is possible to serve the block directly from disk, |
2271 | | // as the network format matches the format on disk |
2272 | 0 | std::vector<std::byte> block_data; |
2273 | 0 | if (!m_chainman.m_blockman.ReadRawBlock(block_data, block_pos)) { |
2274 | 0 | if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) { Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
2275 | 0 | LogDebug(BCLog::NET, "Block was pruned before it could be read, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2276 | 0 | } else { |
2277 | 0 | LogError("Cannot load block from disk, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 358 | 0 | #define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
2278 | 0 | } |
2279 | 0 | pfrom.fDisconnect = true; |
2280 | 0 | return; |
2281 | 0 | } |
2282 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, std::span{block_data}); |
2283 | | // Don't set pblock as we've sent the block |
2284 | 0 | } else { |
2285 | | // Send block from disk |
2286 | 0 | std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>(); |
2287 | 0 | if (!m_chainman.m_blockman.ReadBlock(*pblockRead, block_pos, inv.hash)) { |
2288 | 0 | if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) { Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
2289 | 0 | LogDebug(BCLog::NET, "Block was pruned before it could be read, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2290 | 0 | } else { |
2291 | 0 | LogError("Cannot load block from disk, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 358 | 0 | #define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
2292 | 0 | } |
2293 | 0 | pfrom.fDisconnect = true; |
2294 | 0 | return; |
2295 | 0 | } |
2296 | 0 | pblock = pblockRead; |
2297 | 0 | } |
2298 | 0 | if (pblock) { |
2299 | 0 | if (inv.IsMsgBlk()) { |
2300 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_NO_WITNESS(*pblock)); |
2301 | 0 | } else if (inv.IsMsgWitnessBlk()) { |
2302 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock)); |
2303 | 0 | } else if (inv.IsMsgFilteredBlk()) { |
2304 | 0 | bool sendMerkleBlock = false; |
2305 | 0 | CMerkleBlock merkleBlock; |
2306 | 0 | if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) { |
2307 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2308 | 0 | if (tx_relay->m_bloom_filter) { |
2309 | 0 | sendMerkleBlock = true; |
2310 | 0 | merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter); |
2311 | 0 | } |
2312 | 0 | } |
2313 | 0 | if (sendMerkleBlock) { |
2314 | 0 | MakeAndPushMessage(pfrom, NetMsgType::MERKLEBLOCK, merkleBlock); |
2315 | | // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see |
2316 | | // This avoids hurting performance by pointlessly requiring a round-trip |
2317 | | // Note that there is currently no way for a node to request any single transactions we didn't send here - |
2318 | | // they must either disconnect and retry or request the full block. |
2319 | | // Thus, the protocol spec specified allows for us to provide duplicate txn here, |
2320 | | // however we MUST always provide at least what the remote peer needs |
2321 | 0 | for (const auto& [tx_idx, _] : merkleBlock.vMatchedTxn) |
2322 | 0 | MakeAndPushMessage(pfrom, NetMsgType::TX, TX_NO_WITNESS(*pblock->vtx[tx_idx])); |
2323 | 0 | } |
2324 | | // else |
2325 | | // no response |
2326 | 0 | } else if (inv.IsMsgCmpctBlk()) { |
2327 | | // If a peer is asking for old blocks, we're almost guaranteed |
2328 | | // they won't have a useful mempool to match against a compact block, |
2329 | | // and we don't feel like constructing the object for them, so |
2330 | | // instead we respond with the full, non-compact block. |
2331 | 0 | if (can_direct_fetch && pindex->nHeight >= tip->nHeight - MAX_CMPCTBLOCK_DEPTH) { |
2332 | 0 | if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == inv.hash) { |
2333 | 0 | MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, *a_recent_compact_block); |
2334 | 0 | } else { |
2335 | 0 | CBlockHeaderAndShortTxIDs cmpctblock{*pblock, m_rng.rand64()}; |
2336 | 0 | MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, cmpctblock); |
2337 | 0 | } |
2338 | 0 | } else { |
2339 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock)); |
2340 | 0 | } |
2341 | 0 | } |
2342 | 0 | } |
2343 | |
|
2344 | 0 | { |
2345 | 0 | LOCK(peer.m_block_inv_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2346 | | // Trigger the peer node to send a getblocks request for the next batch of inventory |
2347 | 0 | if (inv.hash == peer.m_continuation_block) { |
2348 | | // Send immediately. This must send even if redundant, |
2349 | | // and we want it right after the last block so they don't |
2350 | | // wait for other stuff first. |
2351 | 0 | std::vector<CInv> vInv; |
2352 | 0 | vInv.emplace_back(MSG_BLOCK, tip->GetBlockHash()); |
2353 | 0 | MakeAndPushMessage(pfrom, NetMsgType::INV, vInv); |
2354 | 0 | peer.m_continuation_block.SetNull(); |
2355 | 0 | } |
2356 | 0 | } |
2357 | 0 | } |
2358 | | |
2359 | | CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid) |
2360 | 0 | { |
2361 | | // If a tx was in the mempool prior to the last INV for this peer, permit the request. |
2362 | 0 | auto txinfo{std::visit( |
2363 | 0 | [&](const auto& id) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex) { |
2364 | 0 | return m_mempool.info_for_relay(id, tx_relay.m_last_inv_sequence); |
2365 | 0 | }, Unexecuted instantiation: net_processing.cpp:_ZZN12_GLOBAL__N_115PeerManagerImpl16FindTxForGetDataERKNS_4Peer7TxRelayERK7GenTxidENK3$_0clI22transaction_identifierILb0EEEEDaRKT_ Unexecuted instantiation: net_processing.cpp:_ZZN12_GLOBAL__N_115PeerManagerImpl16FindTxForGetDataERKNS_4Peer7TxRelayERK7GenTxidENK3$_0clI22transaction_identifierILb1EEEEDaRKT_ |
2366 | 0 | gtxid)}; |
2367 | 0 | if (txinfo.tx) { |
2368 | 0 | return std::move(txinfo.tx); |
2369 | 0 | } |
2370 | | |
2371 | | // Or it might be from the most recent block |
2372 | 0 | { |
2373 | 0 | LOCK(m_most_recent_block_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2374 | 0 | if (m_most_recent_block_txs != nullptr) { |
2375 | 0 | auto it = m_most_recent_block_txs->find(gtxid); |
2376 | 0 | if (it != m_most_recent_block_txs->end()) return it->second; |
2377 | 0 | } |
2378 | 0 | } |
2379 | | |
2380 | 0 | return {}; |
2381 | 0 | } |
2382 | | |
2383 | | void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) |
2384 | 0 | { |
2385 | 0 | AssertLockNotHeld(cs_main); Line | Count | Source | 142 | 0 | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
2386 | |
|
2387 | 0 | auto tx_relay = peer.GetTxRelay(); |
2388 | |
|
2389 | 0 | std::deque<CInv>::iterator it = peer.m_getdata_requests.begin(); |
2390 | 0 | std::vector<CInv> vNotFound; |
2391 | | |
2392 | | // Process as many TX items from the front of the getdata queue as |
2393 | | // possible, since they're common and it's efficient to batch process |
2394 | | // them. |
2395 | 0 | while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) { |
2396 | 0 | if (interruptMsgProc) return; |
2397 | | // The send buffer provides backpressure. If there's no space in |
2398 | | // the buffer, pause processing until the next call. |
2399 | 0 | if (pfrom.fPauseSend) break; |
2400 | | |
2401 | 0 | const CInv &inv = *it++; |
2402 | |
|
2403 | 0 | if (tx_relay == nullptr) { |
2404 | | // Ignore GETDATA requests for transactions from block-relay-only |
2405 | | // peers and peers that asked us not to announce transactions. |
2406 | 0 | continue; |
2407 | 0 | } |
2408 | | |
2409 | 0 | if (auto tx{FindTxForGetData(*tx_relay, ToGenTxid(inv))}) { |
2410 | | // WTX and WITNESS_TX imply we serialize with witness |
2411 | 0 | const auto maybe_with_witness = (inv.IsMsgTx() ? TX_NO_WITNESS : TX_WITH_WITNESS); |
2412 | 0 | MakeAndPushMessage(pfrom, NetMsgType::TX, maybe_with_witness(*tx)); |
2413 | 0 | m_mempool.RemoveUnbroadcastTx(tx->GetHash()); |
2414 | 0 | } else { |
2415 | 0 | vNotFound.push_back(inv); |
2416 | 0 | } |
2417 | 0 | } |
2418 | | |
2419 | | // Only process one BLOCK item per call, since they're uncommon and can be |
2420 | | // expensive to process. |
2421 | 0 | if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) { |
2422 | 0 | const CInv &inv = *it++; |
2423 | 0 | if (inv.IsGenBlkMsg()) { |
2424 | 0 | ProcessGetBlockData(pfrom, peer, inv); |
2425 | 0 | } |
2426 | | // else: If the first item on the queue is an unknown type, we erase it |
2427 | | // and continue processing the queue on the next call. |
2428 | | // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could |
2429 | | // result in never making progress and this thread using 100% allocated CPU. See |
2430 | | // https://bitcoincore.org/en/2024/07/03/disclose-getdata-cpu. |
2431 | 0 | } |
2432 | |
|
2433 | 0 | peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it); |
2434 | |
|
2435 | 0 | if (!vNotFound.empty()) { |
2436 | | // Let the peer know that we didn't find what it asked for, so it doesn't |
2437 | | // have to wait around forever. |
2438 | | // SPV clients care about this message: it's needed when they are |
2439 | | // recursively walking the dependencies of relevant unconfirmed |
2440 | | // transactions. SPV clients want to do that because they want to know |
2441 | | // about (and store and rebroadcast and risk analyze) the dependencies |
2442 | | // of transactions relevant to them, without having to download the |
2443 | | // entire memory pool. |
2444 | | // Also, other nodes can use these messages to automatically request a |
2445 | | // transaction from some other peer that announced it, and stop |
2446 | | // waiting for us to respond. |
2447 | | // In normal operation, we often send NOTFOUND messages for parents of |
2448 | | // transactions that we relay; if a peer is missing a parent, they may |
2449 | | // assume we have them and request the parents from us. |
2450 | 0 | MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound); |
2451 | 0 | } |
2452 | 0 | } |
2453 | | |
2454 | | uint32_t PeerManagerImpl::GetFetchFlags(const Peer& peer) const |
2455 | 175k | { |
2456 | 175k | uint32_t nFetchFlags = 0; |
2457 | 175k | if (CanServeWitnesses(peer)) { |
2458 | 48.1k | nFetchFlags |= MSG_WITNESS_FLAG; |
2459 | 48.1k | } |
2460 | 175k | return nFetchFlags; |
2461 | 175k | } |
2462 | | |
2463 | | void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req) |
2464 | 0 | { |
2465 | 0 | BlockTransactions resp(req); |
2466 | 0 | unsigned int tx_requested_size = 0; |
2467 | 0 | for (size_t i = 0; i < req.indexes.size(); i++) { |
2468 | 0 | if (req.indexes[i] >= block.vtx.size()) { |
2469 | 0 | Misbehaving(peer, "getblocktxn with out-of-bounds tx indices"); |
2470 | 0 | return; |
2471 | 0 | } |
2472 | 0 | resp.txn[i] = block.vtx[req.indexes[i]]; |
2473 | 0 | tx_requested_size += resp.txn[i]->GetTotalSize(); |
2474 | 0 | } |
2475 | | |
2476 | 0 | LogDebug(BCLog::CMPCTBLOCK, "Peer %d sent us a GETBLOCKTXN for block %s, sending a BLOCKTXN with %u txns. (%u bytes)\n", pfrom.GetId(), block.GetHash().ToString(), resp.txn.size(), tx_requested_size); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2477 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCKTXN, resp); |
2478 | 0 | } |
2479 | | |
2480 | | bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer) |
2481 | 1.83M | { |
2482 | | // Do these headers have proof-of-work matching what's claimed? |
2483 | 1.83M | if (!HasValidProofOfWork(headers, consensusParams)) { |
2484 | 178k | Misbehaving(peer, "header with invalid proof of work"); |
2485 | 178k | return false; |
2486 | 178k | } |
2487 | | |
2488 | | // Are these headers connected to each other? |
2489 | 1.65M | if (!CheckHeadersAreContinuous(headers)) { |
2490 | 0 | Misbehaving(peer, "non-continuous headers sequence"); |
2491 | 0 | return false; |
2492 | 0 | } |
2493 | 1.65M | return true; |
2494 | 1.65M | } |
2495 | | |
2496 | | arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold() |
2497 | 2.88M | { |
2498 | 2.88M | arith_uint256 near_chaintip_work = 0; |
2499 | 2.88M | LOCK(cs_main); Line | Count | Source | 259 | 2.88M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 2.88M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 2.88M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 2.88M | #define PASTE(x, y) x ## y |
|
|
|
|
2500 | 2.88M | if (m_chainman.ActiveChain().Tip() != nullptr) { |
2501 | 2.88M | const CBlockIndex *tip = m_chainman.ActiveChain().Tip(); |
2502 | | // Use a 144 block buffer, so that we'll accept headers that fork from |
2503 | | // near our tip. |
2504 | 2.88M | near_chaintip_work = tip->nChainWork - std::min<arith_uint256>(144*GetBlockProof(*tip), tip->nChainWork); |
2505 | 2.88M | } |
2506 | 2.88M | return std::max(near_chaintip_work, m_chainman.MinimumChainWork()); |
2507 | 2.88M | } |
2508 | | |
2509 | | /** |
2510 | | * Special handling for unconnecting headers that might be part of a block |
2511 | | * announcement. |
2512 | | * |
2513 | | * We'll send a getheaders message in response to try to connect the chain. |
2514 | | */ |
2515 | | void PeerManagerImpl::HandleUnconnectingHeaders(CNode& pfrom, Peer& peer, |
2516 | | const std::vector<CBlockHeader>& headers) |
2517 | 22.3k | { |
2518 | | // Try to fill in the missing headers. |
2519 | 22.3k | const CBlockIndex* best_header{WITH_LOCK(cs_main, return m_chainman.m_best_header)}; Line | Count | Source | 290 | 22.3k | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
2520 | 22.3k | if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) { |
2521 | 1.01k | LogDebug(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d)\n", Line | Count | Source | 381 | 1.01k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 1.01k | do { \ | 374 | 1.01k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 1.01k | } while (0) |
|
|
2522 | 1.01k | headers[0].GetHash().ToString(), |
2523 | 1.01k | headers[0].hashPrevBlock.ToString(), |
2524 | 1.01k | best_header->nHeight, |
2525 | 1.01k | pfrom.GetId()); |
2526 | 1.01k | } |
2527 | | |
2528 | | // Set hashLastUnknownBlock for this peer, so that if we |
2529 | | // eventually get the headers - even from a different peer - |
2530 | | // we can use this peer to download. |
2531 | 22.3k | WITH_LOCK(cs_main, UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash())); Line | Count | Source | 290 | 22.3k | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
2532 | 22.3k | } |
2533 | | |
2534 | | bool PeerManagerImpl::CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const |
2535 | 1.65M | { |
2536 | 1.65M | uint256 hashLastBlock; |
2537 | 1.65M | for (const CBlockHeader& header : headers) { |
2538 | 1.65M | if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock0 ) { |
2539 | 0 | return false; |
2540 | 0 | } |
2541 | 1.65M | hashLastBlock = header.GetHash(); |
2542 | 1.65M | } |
2543 | 1.65M | return true; |
2544 | 1.65M | } |
2545 | | |
2546 | | bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers) |
2547 | 1.65M | { |
2548 | 1.65M | if (peer.m_headers_sync) { |
2549 | 0 | auto result = peer.m_headers_sync->ProcessNextHeaders(headers, headers.size() == m_opts.max_headers_result); |
2550 | | // If it is a valid continuation, we should treat the existing getheaders request as responded to. |
2551 | 0 | if (result.success) peer.m_last_getheaders_timestamp = {}; |
2552 | 0 | if (result.request_more) { |
2553 | 0 | auto locator = peer.m_headers_sync->NextHeadersRequestLocator(); |
2554 | | // If we were instructed to ask for a locator, it should not be empty. |
2555 | 0 | Assume(!locator.vHave.empty()); Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
2556 | | // We can only be instructed to request more if processing was successful. |
2557 | 0 | Assume(result.success); Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
2558 | 0 | if (!locator.vHave.empty()) { |
2559 | | // It should be impossible for the getheaders request to fail, |
2560 | | // because we just cleared the last getheaders timestamp. |
2561 | 0 | bool sent_getheaders = MaybeSendGetHeaders(pfrom, locator, peer); |
2562 | 0 | Assume(sent_getheaders); Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
2563 | 0 | LogDebug(BCLog::NET, "more getheaders (from %s) to peer=%d\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2564 | 0 | locator.vHave.front().ToString(), pfrom.GetId()); |
2565 | 0 | } |
2566 | 0 | } |
2567 | |
|
2568 | 0 | if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) { |
2569 | 0 | peer.m_headers_sync.reset(nullptr); |
2570 | | |
2571 | | // Delete this peer's entry in m_headers_presync_stats. |
2572 | | // If this is m_headers_presync_bestpeer, it will be replaced later |
2573 | | // by the next peer that triggers the else{} branch below. |
2574 | 0 | LOCK(m_headers_presync_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2575 | 0 | m_headers_presync_stats.erase(pfrom.GetId()); |
2576 | 0 | } else { |
2577 | | // Build statistics for this peer's sync. |
2578 | 0 | HeadersPresyncStats stats; |
2579 | 0 | stats.first = peer.m_headers_sync->GetPresyncWork(); |
2580 | 0 | if (peer.m_headers_sync->GetState() == HeadersSyncState::State::PRESYNC) { |
2581 | 0 | stats.second = {peer.m_headers_sync->GetPresyncHeight(), |
2582 | 0 | peer.m_headers_sync->GetPresyncTime()}; |
2583 | 0 | } |
2584 | | |
2585 | | // Update statistics in stats. |
2586 | 0 | LOCK(m_headers_presync_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2587 | 0 | m_headers_presync_stats[pfrom.GetId()] = stats; |
2588 | 0 | auto best_it = m_headers_presync_stats.find(m_headers_presync_bestpeer); |
2589 | 0 | bool best_updated = false; |
2590 | 0 | if (best_it == m_headers_presync_stats.end()) { |
2591 | | // If the cached best peer is outdated, iterate over all remaining ones (including |
2592 | | // newly updated one) to find the best one. |
2593 | 0 | NodeId peer_best{-1}; |
2594 | 0 | const HeadersPresyncStats* stat_best{nullptr}; |
2595 | 0 | for (const auto& [peer, stat] : m_headers_presync_stats) { |
2596 | 0 | if (!stat_best || stat > *stat_best) { |
2597 | 0 | peer_best = peer; |
2598 | 0 | stat_best = &stat; |
2599 | 0 | } |
2600 | 0 | } |
2601 | 0 | m_headers_presync_bestpeer = peer_best; |
2602 | 0 | best_updated = (peer_best == pfrom.GetId()); |
2603 | 0 | } else if (best_it->first == pfrom.GetId() || stats > best_it->second) { |
2604 | | // pfrom was and remains the best peer, or pfrom just became best. |
2605 | 0 | m_headers_presync_bestpeer = pfrom.GetId(); |
2606 | 0 | best_updated = true; |
2607 | 0 | } |
2608 | 0 | if (best_updated && stats.second.has_value()) { |
2609 | | // If the best peer updated, and it is in its first phase, signal. |
2610 | 0 | m_headers_presync_should_signal = true; |
2611 | 0 | } |
2612 | 0 | } |
2613 | |
|
2614 | 0 | if (result.success) { |
2615 | | // We only overwrite the headers passed in if processing was |
2616 | | // successful. |
2617 | 0 | headers.swap(result.pow_validated_headers); |
2618 | 0 | } |
2619 | |
|
2620 | 0 | return result.success; |
2621 | 0 | } |
2622 | | // Either we didn't have a sync in progress, or something went wrong |
2623 | | // processing these headers, or we are returning headers to the caller to |
2624 | | // process. |
2625 | 1.65M | return false; |
2626 | 1.65M | } |
2627 | | |
2628 | | bool PeerManagerImpl::TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex* chain_start_header, std::vector<CBlockHeader>& headers) |
2629 | 428k | { |
2630 | | // Calculate the claimed total work on this chain. |
2631 | 428k | arith_uint256 total_work = chain_start_header->nChainWork + CalculateClaimedHeadersWork(headers); |
2632 | | |
2633 | | // Our dynamic anti-DoS threshold (minimum work required on a headers chain |
2634 | | // before we'll store it) |
2635 | 428k | arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold(); |
2636 | | |
2637 | | // Avoid DoS via low-difficulty-headers by only processing if the headers |
2638 | | // are part of a chain with sufficient work. |
2639 | 428k | if (total_work < minimum_chain_work) { |
2640 | | // Only try to sync with this peer if their headers message was full; |
2641 | | // otherwise they don't have more headers after this so no point in |
2642 | | // trying to sync their too-little-work chain. |
2643 | 0 | if (headers.size() == m_opts.max_headers_result) { |
2644 | | // Note: we could advance to the last header in this set that is |
2645 | | // known to us, rather than starting at the first header (which we |
2646 | | // may already have); however this is unlikely to matter much since |
2647 | | // ProcessHeadersMessage() already handles the case where all |
2648 | | // headers in a received message are already known and are |
2649 | | // ancestors of m_best_header or chainActive.Tip(), by skipping |
2650 | | // this logic in that case. So even if the first header in this set |
2651 | | // of headers is known, some header in this set must be new, so |
2652 | | // advancing to the first unknown header would be a small effect. |
2653 | 0 | LOCK(peer.m_headers_sync_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2654 | 0 | peer.m_headers_sync.reset(new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(), |
2655 | 0 | chain_start_header, minimum_chain_work)); |
2656 | | |
2657 | | // Now a HeadersSyncState object for tracking this synchronization |
2658 | | // is created, process the headers using it as normal. Failures are |
2659 | | // handled inside of IsContinuationOfLowWorkHeadersSync. |
2660 | 0 | (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers); |
2661 | 0 | } else { |
2662 | 0 | LogDebug(BCLog::NET, "Ignoring low-work chain (height=%u) from peer=%d\n", chain_start_header->nHeight + headers.size(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2663 | 0 | } |
2664 | | |
2665 | | // The peer has not yet given us a chain that meets our work threshold, |
2666 | | // so we want to prevent further processing of the headers in any case. |
2667 | 0 | headers = {}; |
2668 | 0 | return true; |
2669 | 0 | } |
2670 | | |
2671 | 428k | return false; |
2672 | 428k | } |
2673 | | |
2674 | | bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) |
2675 | 1.63M | { |
2676 | 1.63M | if (header == nullptr) { |
2677 | 191k | return false; |
2678 | 1.43M | } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) { |
2679 | 325k | return true; |
2680 | 1.11M | } else if (m_chainman.ActiveChain().Contains(header)) { |
2681 | 11.5k | return true; |
2682 | 11.5k | } |
2683 | 1.10M | return false; |
2684 | 1.63M | } |
2685 | | |
2686 | | bool PeerManagerImpl::MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) |
2687 | 81.8k | { |
2688 | 81.8k | const auto current_time = NodeClock::now(); |
2689 | | |
2690 | | // Only allow a new getheaders message to go out if we don't have a recent |
2691 | | // one already in-flight |
2692 | 81.8k | if (current_time - peer.m_last_getheaders_timestamp > HEADERS_RESPONSE_TIME) { |
2693 | 42.9k | MakeAndPushMessage(pfrom, NetMsgType::GETHEADERS, locator, uint256()); |
2694 | 42.9k | peer.m_last_getheaders_timestamp = current_time; |
2695 | 42.9k | return true; |
2696 | 42.9k | } |
2697 | 38.8k | return false; |
2698 | 81.8k | } |
2699 | | |
2700 | | /* |
2701 | | * Given a new headers tip ending in last_header, potentially request blocks towards that tip. |
2702 | | * We require that the given tip have at least as much work as our tip, and for |
2703 | | * our current tip to be "close to synced" (see CanDirectFetch()). |
2704 | | */ |
2705 | | void PeerManagerImpl::HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header) |
2706 | 949k | { |
2707 | 949k | LOCK(cs_main); Line | Count | Source | 259 | 949k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 949k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 949k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 949k | #define PASTE(x, y) x ## y |
|
|
|
|
2708 | 949k | CNodeState *nodestate = State(pfrom.GetId()); |
2709 | | |
2710 | 949k | if (CanDirectFetch() && last_header.IsValid(BLOCK_VALID_TREE)916k && m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork916k ) { |
2711 | 677k | std::vector<const CBlockIndex*> vToFetch; |
2712 | 677k | const CBlockIndex* pindexWalk{&last_header}; |
2713 | | // Calculate all the blocks we'd need to switch to last_header, up to a limit. |
2714 | 1.38M | while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER702k ) { |
2715 | 702k | if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) && |
2716 | 702k | !IsBlockRequested(pindexWalk->GetBlockHash())675k && |
2717 | 702k | (228k !DeploymentActiveAt(*pindexWalk, m_chainman, Consensus::DEPLOYMENT_SEGWIT)228k || CanServeWitnesses(peer)228k )) { |
2718 | | // We don't have this block, and it's not yet in flight. |
2719 | 17.9k | vToFetch.push_back(pindexWalk); |
2720 | 17.9k | } |
2721 | 702k | pindexWalk = pindexWalk->pprev; |
2722 | 702k | } |
2723 | | // If pindexWalk still isn't on our main chain, we're looking at a |
2724 | | // very large reorg at a time we think we're close to caught up to |
2725 | | // the main chain -- this shouldn't really happen. Bail out on the |
2726 | | // direct fetch and rely on parallel download instead. |
2727 | 677k | if (!m_chainman.ActiveChain().Contains(pindexWalk)) { |
2728 | 0 | LogDebug(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2729 | 0 | last_header.GetBlockHash().ToString(), |
2730 | 0 | last_header.nHeight); |
2731 | 677k | } else { |
2732 | 677k | std::vector<CInv> vGetData; |
2733 | | // Download as much as possible, from earliest to latest. |
2734 | 677k | for (const CBlockIndex* pindex : vToFetch | std::views::reverse) { |
2735 | 14.3k | if (nodestate->vBlocksInFlight.size() >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { |
2736 | | // Can't download any more from this peer |
2737 | 10.4k | break; |
2738 | 10.4k | } |
2739 | 3.91k | uint32_t nFetchFlags = GetFetchFlags(peer); |
2740 | 3.91k | vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()); |
2741 | 3.91k | BlockRequested(pfrom.GetId(), *pindex); |
2742 | 3.91k | LogDebug(BCLog::NET, "Requesting block %s from peer=%d\n", Line | Count | Source | 381 | 3.91k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 3.91k | do { \ | 374 | 3.91k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 3.91k | } while (0) |
|
|
2743 | 3.91k | pindex->GetBlockHash().ToString(), pfrom.GetId()); |
2744 | 3.91k | } |
2745 | 677k | if (vGetData.size() > 1) { |
2746 | 42 | LogDebug(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n", Line | Count | Source | 381 | 42 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 42 | do { \ | 374 | 42 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 42 | } while (0) |
|
|
2747 | 42 | last_header.GetBlockHash().ToString(), |
2748 | 42 | last_header.nHeight); |
2749 | 42 | } |
2750 | 677k | if (vGetData.size() > 0) { |
2751 | 3.85k | if (!m_opts.ignore_incoming_txs && |
2752 | 3.85k | nodestate->m_provides_cmpctblocks && |
2753 | 3.85k | vGetData.size() == 1956 && |
2754 | 3.85k | mapBlocksInFlight.size() == 1933 && |
2755 | 3.85k | last_header.pprev->IsValid(BLOCK_VALID_CHAIN)104 ) { |
2756 | | // In any case, we want to download using a compact block, not a regular one |
2757 | 99 | vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash); |
2758 | 99 | } |
2759 | 3.85k | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vGetData); |
2760 | 3.85k | } |
2761 | 677k | } |
2762 | 677k | } |
2763 | 949k | } |
2764 | | |
2765 | | /** |
2766 | | * Given receipt of headers from a peer ending in last_header, along with |
2767 | | * whether that header was new and whether the headers message was full, |
2768 | | * update the state we keep for the peer. |
2769 | | */ |
2770 | | void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, |
2771 | | const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers) |
2772 | 949k | { |
2773 | 949k | LOCK(cs_main); Line | Count | Source | 259 | 949k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 949k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 949k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 949k | #define PASTE(x, y) x ## y |
|
|
|
|
2774 | 949k | CNodeState *nodestate = State(pfrom.GetId()); |
2775 | | |
2776 | 949k | UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash()); |
2777 | | |
2778 | | // From here, pindexBestKnownBlock should be guaranteed to be non-null, |
2779 | | // because it is set in UpdateBlockAvailability. Some nullptr checks |
2780 | | // are still present, however, as belt-and-suspenders. |
2781 | | |
2782 | 949k | if (received_new_header && last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork15.4k ) { |
2783 | 13.3k | nodestate->m_last_block_announcement = GetTime(); |
2784 | 13.3k | } |
2785 | | |
2786 | | // If we're in IBD, we want outbound peers that will serve us a useful |
2787 | | // chain. Disconnect peers that are on chains with insufficient work. |
2788 | 949k | if (m_chainman.IsInitialBlockDownload() && !may_have_more_headers25.5k ) { |
2789 | | // If the peer has no more headers to give us, then we know we have |
2790 | | // their tip. |
2791 | 25.5k | if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) { |
2792 | | // This peer has too little work on their headers chain to help |
2793 | | // us sync -- disconnect if it is an outbound disconnection |
2794 | | // candidate. |
2795 | | // Note: We compare their tip to the minimum chain work (rather than |
2796 | | // m_chainman.ActiveChain().Tip()) because we won't start block download |
2797 | | // until we have a headers chain that has at least |
2798 | | // the minimum chain work, even if a peer has a chain past our tip, |
2799 | | // as an anti-DoS measure. |
2800 | 0 | if (pfrom.IsOutboundOrBlockRelayConn()) { |
2801 | 0 | LogInfo("outbound peer headers chain has insufficient work, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 356 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
2802 | 0 | pfrom.fDisconnect = true; |
2803 | 0 | } |
2804 | 0 | } |
2805 | 25.5k | } |
2806 | | |
2807 | | // If this is an outbound full-relay peer, check to see if we should protect |
2808 | | // it from the bad/lagging chain logic. |
2809 | | // Note that outbound block-relay peers are excluded from this protection, and |
2810 | | // thus always subject to eviction under the bad/lagging chain logic. |
2811 | | // See ChainSyncTimeoutState. |
2812 | 949k | if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr9.58k ) { |
2813 | 9.58k | 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_protect9.45k ) { |
2814 | 243 | LogDebug(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId()); Line | Count | Source | 381 | 243 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 243 | do { \ | 374 | 243 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 243 | } while (0) |
|
|
2815 | 243 | nodestate->m_chain_sync.m_protect = true; |
2816 | 243 | ++m_outbound_peers_with_protect_from_disconnect; |
2817 | 243 | } |
2818 | 9.58k | } |
2819 | 949k | } |
2820 | | |
2821 | | void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, Peer& peer, |
2822 | | std::vector<CBlockHeader>&& headers, |
2823 | | bool via_compact_block) |
2824 | 1.83M | { |
2825 | 1.83M | size_t nCount = headers.size(); |
2826 | | |
2827 | 1.83M | if (nCount == 0) { |
2828 | | // Nothing interesting. Stop asking this peers for more headers. |
2829 | | // If we were in the middle of headers sync, receiving an empty headers |
2830 | | // message suggests that the peer suddenly has nothing to give us |
2831 | | // (perhaps it reorged to our chain). Clear download state for this peer. |
2832 | 0 | LOCK(peer.m_headers_sync_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2833 | 0 | if (peer.m_headers_sync) { |
2834 | 0 | peer.m_headers_sync.reset(nullptr); |
2835 | 0 | LOCK(m_headers_presync_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
2836 | 0 | m_headers_presync_stats.erase(pfrom.GetId()); |
2837 | 0 | } |
2838 | | // A headers message with no headers cannot be an announcement, so assume |
2839 | | // it is a response to our last getheaders request, if there is one. |
2840 | 0 | peer.m_last_getheaders_timestamp = {}; |
2841 | 0 | return; |
2842 | 0 | } |
2843 | | |
2844 | | // Before we do any processing, make sure these pass basic sanity checks. |
2845 | | // We'll rely on headers having valid proof-of-work further down, as an |
2846 | | // anti-DoS criteria (note: this check is required before passing any |
2847 | | // headers into HeadersSyncState). |
2848 | 1.83M | if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) { |
2849 | | // Misbehaving() calls are handled within CheckHeadersPoW(), so we can |
2850 | | // just return. (Note that even if a header is announced via compact |
2851 | | // block, the header itself should be valid, so this type of error can |
2852 | | // always be punished.) |
2853 | 178k | return; |
2854 | 178k | } |
2855 | | |
2856 | 1.65M | const CBlockIndex *pindexLast = nullptr; |
2857 | | |
2858 | | // We'll set already_validated_work to true if these headers are |
2859 | | // successfully processed as part of a low-work headers sync in progress |
2860 | | // (either in PRESYNC or REDOWNLOAD phase). |
2861 | | // If true, this will mean that any headers returned to us (ie during |
2862 | | // REDOWNLOAD) can be validated without further anti-DoS checks. |
2863 | 1.65M | bool already_validated_work = false; |
2864 | | |
2865 | | // If we're in the middle of headers sync, let it do its magic. |
2866 | 1.65M | bool have_headers_sync = false; |
2867 | 1.65M | { |
2868 | 1.65M | LOCK(peer.m_headers_sync_mutex); Line | Count | Source | 259 | 1.65M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 1.65M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 1.65M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 1.65M | #define PASTE(x, y) x ## y |
|
|
|
|
2869 | | |
2870 | 1.65M | already_validated_work = IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers); |
2871 | | |
2872 | | // The headers we passed in may have been: |
2873 | | // - untouched, perhaps if no headers-sync was in progress, or some |
2874 | | // failure occurred |
2875 | | // - erased, such as if the headers were successfully processed and no |
2876 | | // additional headers processing needs to take place (such as if we |
2877 | | // are still in PRESYNC) |
2878 | | // - replaced with headers that are now ready for validation, such as |
2879 | | // during the REDOWNLOAD phase of a low-work headers sync. |
2880 | | // So just check whether we still have headers that we need to process, |
2881 | | // or not. |
2882 | 1.65M | if (headers.empty()) { |
2883 | 0 | return; |
2884 | 0 | } |
2885 | | |
2886 | 1.65M | have_headers_sync = !!peer.m_headers_sync; |
2887 | 1.65M | } |
2888 | | |
2889 | | // Do these headers connect to something in our block index? |
2890 | 1.65M | const CBlockIndex *chain_start_header{WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock))}; Line | Count | Source | 290 | 1.65M | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
2891 | 1.65M | bool headers_connect_blockindex{chain_start_header != nullptr}; |
2892 | | |
2893 | 1.65M | if (!headers_connect_blockindex) { |
2894 | | // This could be a BIP 130 block announcement, use |
2895 | | // special logic for handling headers that don't connect, as this |
2896 | | // could be benign. |
2897 | 22.3k | HandleUnconnectingHeaders(pfrom, peer, headers); |
2898 | 22.3k | return; |
2899 | 22.3k | } |
2900 | | |
2901 | | // If headers connect, assume that this is in response to any outstanding getheaders |
2902 | | // request we may have sent, and clear out the time of our last request. Non-connecting |
2903 | | // headers cannot be a response to a getheaders request. |
2904 | 1.63M | peer.m_last_getheaders_timestamp = {}; |
2905 | | |
2906 | | // If the headers we received are already in memory and an ancestor of |
2907 | | // m_best_header or our tip, skip anti-DoS checks. These headers will not |
2908 | | // use any more memory (and we are not leaking information that could be |
2909 | | // used to fingerprint us). |
2910 | 1.63M | const CBlockIndex *last_received_header{nullptr}; |
2911 | 1.63M | { |
2912 | 1.63M | LOCK(cs_main); Line | Count | Source | 259 | 1.63M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 1.63M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 1.63M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 1.63M | #define PASTE(x, y) x ## y |
|
|
|
|
2913 | 1.63M | last_received_header = m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash()); |
2914 | 1.63M | if (IsAncestorOfBestHeaderOrTip(last_received_header)) { |
2915 | 337k | already_validated_work = true; |
2916 | 337k | } |
2917 | 1.63M | } |
2918 | | |
2919 | | // If our peer has NetPermissionFlags::NoBan privileges, then bypass our |
2920 | | // anti-DoS logic (this saves bandwidth when we connect to a trusted peer |
2921 | | // on startup). |
2922 | 1.63M | if (pfrom.HasPermission(NetPermissionFlags::NoBan)) { |
2923 | 1.08M | already_validated_work = true; |
2924 | 1.08M | } |
2925 | | |
2926 | | // At this point, the headers connect to something in our block index. |
2927 | | // Do anti-DoS checks to determine if we should process or store for later |
2928 | | // processing. |
2929 | 1.63M | if (!already_validated_work && TryLowWorkHeadersSync(peer, pfrom, |
2930 | 428k | chain_start_header, headers)) { |
2931 | | // If we successfully started a low-work headers sync, then there |
2932 | | // should be no headers to process any further. |
2933 | 0 | Assume(headers.empty()); Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
2934 | 0 | return; |
2935 | 0 | } |
2936 | | |
2937 | | // At this point, we have a set of headers with sufficient work on them |
2938 | | // which can be processed. |
2939 | | |
2940 | | // If we don't have the last header, then this peer will have given us |
2941 | | // something new (if these headers are valid). |
2942 | 1.63M | bool received_new_header{last_received_header == nullptr}; |
2943 | | |
2944 | | // Now process all the headers. |
2945 | 1.63M | BlockValidationState state; |
2946 | 1.63M | const bool processed{m_chainman.ProcessNewBlockHeaders(headers, |
2947 | 1.63M | /*min_pow_checked=*/true, |
2948 | 1.63M | state, &pindexLast)}; |
2949 | 1.63M | if (!processed) { |
2950 | 680k | if (state.IsInvalid()) { |
2951 | 680k | MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received"); |
2952 | 680k | return; |
2953 | 680k | } |
2954 | 680k | } |
2955 | 949k | assert(pindexLast); |
2956 | | |
2957 | 949k | if (processed && received_new_header) { |
2958 | 15.4k | LogBlockHeader(*pindexLast, pfrom, /*via_compact_block=*/false); |
2959 | 15.4k | } |
2960 | | |
2961 | | // Consider fetching more headers if we are not using our headers-sync mechanism. |
2962 | 949k | if (nCount == m_opts.max_headers_result && !have_headers_sync0 ) { |
2963 | | // Headers message had its maximum size; the peer may have more headers. |
2964 | 0 | if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) { |
2965 | 0 | LogDebug(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
2966 | 0 | pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height); |
2967 | 0 | } |
2968 | 0 | } |
2969 | | |
2970 | 949k | UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast, received_new_header, nCount == m_opts.max_headers_result); |
2971 | | |
2972 | | // Consider immediately downloading blocks. |
2973 | 949k | HeadersDirectFetchBlocks(pfrom, peer, *pindexLast); |
2974 | | |
2975 | 949k | return; |
2976 | 949k | } |
2977 | | |
2978 | | std::optional<node::PackageToValidate> PeerManagerImpl::ProcessInvalidTx(NodeId nodeid, const CTransactionRef& ptx, const TxValidationState& state, |
2979 | | bool first_time_failure) |
2980 | 195k | { |
2981 | 195k | AssertLockNotHeld(m_peer_mutex); Line | Count | Source | 142 | 195k | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
2982 | 195k | AssertLockHeld(g_msgproc_mutex); Line | Count | Source | 137 | 195k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
2983 | 195k | AssertLockHeld(m_tx_download_mutex); Line | Count | Source | 137 | 195k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
2984 | | |
2985 | 195k | PeerRef peer{GetPeerRef(nodeid)}; |
2986 | | |
2987 | 195k | LogDebug(BCLog::MEMPOOLREJ, "%s (wtxid=%s) from peer=%d was not accepted: %s\n", Line | Count | Source | 381 | 195k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 195k | do { \ | 374 | 195k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 195k | } while (0) |
|
|
2988 | 195k | ptx->GetHash().ToString(), |
2989 | 195k | ptx->GetWitnessHash().ToString(), |
2990 | 195k | nodeid, |
2991 | 195k | state.ToString()); |
2992 | | |
2993 | 195k | const auto& [add_extra_compact_tx, unique_parents, package_to_validate] = m_txdownloadman.MempoolRejectedTx(ptx, state, nodeid, first_time_failure); |
2994 | | |
2995 | 195k | if (add_extra_compact_tx && RecursiveDynamicUsage(*ptx) < 100000) { |
2996 | 195k | AddToCompactExtraTransactions(ptx); |
2997 | 195k | } |
2998 | 195k | for (const Txid& parent_txid : unique_parents) { |
2999 | 0 | if (peer) AddKnownTx(*peer, parent_txid.ToUint256()); |
3000 | 0 | } |
3001 | | |
3002 | 195k | return package_to_validate; |
3003 | 195k | } |
3004 | | |
3005 | | void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions) |
3006 | 258k | { |
3007 | 258k | AssertLockNotHeld(m_peer_mutex); Line | Count | Source | 142 | 258k | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
3008 | 258k | AssertLockHeld(g_msgproc_mutex); Line | Count | Source | 137 | 258k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
3009 | 258k | AssertLockHeld(m_tx_download_mutex); Line | Count | Source | 137 | 258k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
3010 | | |
3011 | 258k | m_txdownloadman.MempoolAcceptedTx(tx); |
3012 | | |
3013 | 258k | LogDebug(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (wtxid=%s) (poolsz %u txn, %u kB)\n", Line | Count | Source | 381 | 258k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 258k | do { \ | 374 | 258k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 258k | } while (0) |
|
|
3014 | 258k | nodeid, |
3015 | 258k | tx->GetHash().ToString(), |
3016 | 258k | tx->GetWitnessHash().ToString(), |
3017 | 258k | m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000); |
3018 | | |
3019 | 258k | RelayTransaction(tx->GetHash(), tx->GetWitnessHash()); |
3020 | | |
3021 | 258k | for (const CTransactionRef& removedTx : replaced_transactions) { |
3022 | 0 | AddToCompactExtraTransactions(removedTx); |
3023 | 0 | } |
3024 | 258k | } |
3025 | | |
3026 | | void PeerManagerImpl::ProcessPackageResult(const node::PackageToValidate& package_to_validate, const PackageMempoolAcceptResult& package_result) |
3027 | 0 | { |
3028 | 0 | AssertLockNotHeld(m_peer_mutex); Line | Count | Source | 142 | 0 | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
3029 | 0 | AssertLockHeld(g_msgproc_mutex); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
3030 | 0 | AssertLockHeld(m_tx_download_mutex); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
3031 | |
|
3032 | 0 | const auto& package = package_to_validate.m_txns; |
3033 | 0 | const auto& senders = package_to_validate.m_senders; |
3034 | |
|
3035 | 0 | if (package_result.m_state.IsInvalid()) { |
3036 | 0 | m_txdownloadman.MempoolRejectedPackage(package); |
3037 | 0 | } |
3038 | | // We currently only expect to process 1-parent-1-child packages. Remove if this changes. |
3039 | 0 | if (!Assume(package.size() == 2)) return; Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
3040 | | |
3041 | | // Iterate backwards to erase in-package descendants from the orphanage before they become |
3042 | | // relevant in AddChildrenToWorkSet. |
3043 | 0 | auto package_iter = package.rbegin(); |
3044 | 0 | auto senders_iter = senders.rbegin(); |
3045 | 0 | while (package_iter != package.rend()) { |
3046 | 0 | const auto& tx = *package_iter; |
3047 | 0 | const NodeId nodeid = *senders_iter; |
3048 | 0 | const auto it_result{package_result.m_tx_results.find(tx->GetWitnessHash())}; |
3049 | | |
3050 | | // It is not guaranteed that a result exists for every transaction. |
3051 | 0 | if (it_result != package_result.m_tx_results.end()) { |
3052 | 0 | const auto& tx_result = it_result->second; |
3053 | 0 | switch (tx_result.m_result_type) { |
3054 | 0 | case MempoolAcceptResult::ResultType::VALID: |
3055 | 0 | { |
3056 | 0 | ProcessValidTx(nodeid, tx, tx_result.m_replaced_transactions); |
3057 | 0 | break; |
3058 | 0 | } |
3059 | 0 | case MempoolAcceptResult::ResultType::INVALID: |
3060 | 0 | case MempoolAcceptResult::ResultType::DIFFERENT_WITNESS: |
3061 | 0 | { |
3062 | | // Don't add to vExtraTxnForCompact, as these transactions should have already been |
3063 | | // added there when added to the orphanage or rejected for TX_RECONSIDERABLE. |
3064 | | // This should be updated if package submission is ever used for transactions |
3065 | | // that haven't already been validated before. |
3066 | 0 | ProcessInvalidTx(nodeid, tx, tx_result.m_state, /*first_time_failure=*/false); |
3067 | 0 | break; |
3068 | 0 | } |
3069 | 0 | case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY: |
3070 | 0 | { |
3071 | | // AlreadyHaveTx() should be catching transactions that are already in mempool. |
3072 | 0 | Assume(false); Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
3073 | 0 | break; |
3074 | 0 | } |
3075 | 0 | } |
3076 | 0 | } |
3077 | 0 | package_iter++; |
3078 | 0 | senders_iter++; |
3079 | 0 | } |
3080 | 0 | } |
3081 | | |
3082 | | // NOTE: the orphan processing used to be uninterruptible and quadratic, which could allow a peer to stall the node for |
3083 | | // hours with specially crafted transactions. See https://bitcoincore.org/en/2024/07/03/disclose-orphan-dos. |
3084 | | bool PeerManagerImpl::ProcessOrphanTx(Peer& peer) |
3085 | 6.47M | { |
3086 | 6.47M | AssertLockHeld(g_msgproc_mutex); Line | Count | Source | 137 | 6.47M | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
3087 | 6.47M | LOCK2(::cs_main, m_tx_download_mutex); Line | Count | Source | 261 | 6.47M | UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \ | 262 | 6.47M | UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__) |
|
3088 | | |
3089 | 6.47M | CTransactionRef porphanTx = nullptr; |
3090 | | |
3091 | 6.47M | while (CTransactionRef porphanTx = m_txdownloadman.GetTxToReconsider(peer.m_id)) { |
3092 | 0 | const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx); |
3093 | 0 | const TxValidationState& state = result.m_state; |
3094 | 0 | const Txid& orphanHash = porphanTx->GetHash(); |
3095 | 0 | const Wtxid& orphan_wtxid = porphanTx->GetWitnessHash(); |
3096 | |
|
3097 | 0 | if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) { |
3098 | 0 | LogDebug(BCLog::TXPACKAGES, " accepted orphan tx %s (wtxid=%s)\n", orphanHash.ToString(), orphan_wtxid.ToString()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3099 | 0 | ProcessValidTx(peer.m_id, porphanTx, result.m_replaced_transactions); |
3100 | 0 | return true; |
3101 | 0 | } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) { |
3102 | 0 | LogDebug(BCLog::TXPACKAGES, " invalid orphan tx %s (wtxid=%s) from peer=%d. %s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3103 | 0 | orphanHash.ToString(), |
3104 | 0 | orphan_wtxid.ToString(), |
3105 | 0 | peer.m_id, |
3106 | 0 | state.ToString()); |
3107 | |
|
3108 | 0 | if (Assume(state.IsInvalid() && Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
3109 | 0 | state.GetResult() != TxValidationResult::TX_UNKNOWN && |
3110 | 0 | state.GetResult() != TxValidationResult::TX_NO_MEMPOOL && |
3111 | 0 | state.GetResult() != TxValidationResult::TX_RESULT_UNSET)) { |
3112 | 0 | ProcessInvalidTx(peer.m_id, porphanTx, state, /*first_time_failure=*/false); |
3113 | 0 | } |
3114 | 0 | return true; |
3115 | 0 | } |
3116 | 0 | } |
3117 | | |
3118 | 6.47M | return false; |
3119 | 6.47M | } |
3120 | | |
3121 | | bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& node, Peer& peer, |
3122 | | BlockFilterType filter_type, uint32_t start_height, |
3123 | | const uint256& stop_hash, uint32_t max_height_diff, |
3124 | | const CBlockIndex*& stop_index, |
3125 | | BlockFilterIndex*& filter_index) |
3126 | 0 | { |
3127 | 0 | const bool supported_filter_type = |
3128 | 0 | (filter_type == BlockFilterType::BASIC && |
3129 | 0 | (peer.m_our_services & NODE_COMPACT_FILTERS)); |
3130 | 0 | if (!supported_filter_type) { |
3131 | 0 | LogDebug(BCLog::NET, "peer requested unsupported block filter type: %d, %s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3132 | 0 | static_cast<uint8_t>(filter_type), node.DisconnectMsg(fLogIPs)); |
3133 | 0 | node.fDisconnect = true; |
3134 | 0 | return false; |
3135 | 0 | } |
3136 | | |
3137 | 0 | { |
3138 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
3139 | 0 | stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash); |
3140 | | |
3141 | | // Check that the stop block exists and the peer would be allowed to fetch it. |
3142 | 0 | if (!stop_index || !BlockRequestAllowed(stop_index)) { |
3143 | 0 | LogDebug(BCLog::NET, "peer requested invalid block hash: %s, %s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3144 | 0 | stop_hash.ToString(), node.DisconnectMsg(fLogIPs)); |
3145 | 0 | node.fDisconnect = true; |
3146 | 0 | return false; |
3147 | 0 | } |
3148 | 0 | } |
3149 | | |
3150 | 0 | uint32_t stop_height = stop_index->nHeight; |
3151 | 0 | if (start_height > stop_height) { |
3152 | 0 | LogDebug(BCLog::NET, "peer sent invalid getcfilters/getcfheaders with " Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3153 | 0 | "start height %d and stop height %d, %s\n", |
3154 | 0 | start_height, stop_height, node.DisconnectMsg(fLogIPs)); |
3155 | 0 | node.fDisconnect = true; |
3156 | 0 | return false; |
3157 | 0 | } |
3158 | 0 | if (stop_height - start_height >= max_height_diff) { |
3159 | 0 | LogDebug(BCLog::NET, "peer requested too many cfilters/cfheaders: %d / %d, %s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3160 | 0 | stop_height - start_height + 1, max_height_diff, node.DisconnectMsg(fLogIPs)); |
3161 | 0 | node.fDisconnect = true; |
3162 | 0 | return false; |
3163 | 0 | } |
3164 | | |
3165 | 0 | filter_index = GetBlockFilterIndex(filter_type); |
3166 | 0 | if (!filter_index) { |
3167 | 0 | LogDebug(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3168 | 0 | return false; |
3169 | 0 | } |
3170 | | |
3171 | 0 | return true; |
3172 | 0 | } |
3173 | | |
3174 | | void PeerManagerImpl::ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv) |
3175 | 0 | { |
3176 | 0 | uint8_t filter_type_ser; |
3177 | 0 | uint32_t start_height; |
3178 | 0 | uint256 stop_hash; |
3179 | |
|
3180 | 0 | vRecv >> filter_type_ser >> start_height >> stop_hash; |
3181 | |
|
3182 | 0 | const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); |
3183 | |
|
3184 | 0 | const CBlockIndex* stop_index; |
3185 | 0 | BlockFilterIndex* filter_index; |
3186 | 0 | if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash, |
3187 | 0 | MAX_GETCFILTERS_SIZE, stop_index, filter_index)) { |
3188 | 0 | return; |
3189 | 0 | } |
3190 | | |
3191 | 0 | std::vector<BlockFilter> filters; |
3192 | 0 | if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) { |
3193 | 0 | LogDebug(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3194 | 0 | BlockFilterTypeName(filter_type), start_height, stop_hash.ToString()); |
3195 | 0 | return; |
3196 | 0 | } |
3197 | | |
3198 | 0 | for (const auto& filter : filters) { |
3199 | 0 | MakeAndPushMessage(node, NetMsgType::CFILTER, filter); |
3200 | 0 | } |
3201 | 0 | } |
3202 | | |
3203 | | void PeerManagerImpl::ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv) |
3204 | 0 | { |
3205 | 0 | uint8_t filter_type_ser; |
3206 | 0 | uint32_t start_height; |
3207 | 0 | uint256 stop_hash; |
3208 | |
|
3209 | 0 | vRecv >> filter_type_ser >> start_height >> stop_hash; |
3210 | |
|
3211 | 0 | const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); |
3212 | |
|
3213 | 0 | const CBlockIndex* stop_index; |
3214 | 0 | BlockFilterIndex* filter_index; |
3215 | 0 | if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash, |
3216 | 0 | MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) { |
3217 | 0 | return; |
3218 | 0 | } |
3219 | | |
3220 | 0 | uint256 prev_header; |
3221 | 0 | if (start_height > 0) { |
3222 | 0 | const CBlockIndex* const prev_block = |
3223 | 0 | stop_index->GetAncestor(static_cast<int>(start_height - 1)); |
3224 | 0 | if (!filter_index->LookupFilterHeader(prev_block, prev_header)) { |
3225 | 0 | LogDebug(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3226 | 0 | BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString()); |
3227 | 0 | return; |
3228 | 0 | } |
3229 | 0 | } |
3230 | | |
3231 | 0 | std::vector<uint256> filter_hashes; |
3232 | 0 | if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) { |
3233 | 0 | LogDebug(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3234 | 0 | BlockFilterTypeName(filter_type), start_height, stop_hash.ToString()); |
3235 | 0 | return; |
3236 | 0 | } |
3237 | | |
3238 | 0 | MakeAndPushMessage(node, NetMsgType::CFHEADERS, |
3239 | 0 | filter_type_ser, |
3240 | 0 | stop_index->GetBlockHash(), |
3241 | 0 | prev_header, |
3242 | 0 | filter_hashes); |
3243 | 0 | } |
3244 | | |
3245 | | void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv) |
3246 | 0 | { |
3247 | 0 | uint8_t filter_type_ser; |
3248 | 0 | uint256 stop_hash; |
3249 | |
|
3250 | 0 | vRecv >> filter_type_ser >> stop_hash; |
3251 | |
|
3252 | 0 | const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); |
3253 | |
|
3254 | 0 | const CBlockIndex* stop_index; |
3255 | 0 | BlockFilterIndex* filter_index; |
3256 | 0 | if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash, |
3257 | 0 | /*max_height_diff=*/std::numeric_limits<uint32_t>::max(), |
3258 | 0 | stop_index, filter_index)) { |
3259 | 0 | return; |
3260 | 0 | } |
3261 | | |
3262 | 0 | std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL); |
3263 | | |
3264 | | // Populate headers. |
3265 | 0 | const CBlockIndex* block_index = stop_index; |
3266 | 0 | for (int i = headers.size() - 1; i >= 0; i--) { |
3267 | 0 | int height = (i + 1) * CFCHECKPT_INTERVAL; |
3268 | 0 | block_index = block_index->GetAncestor(height); |
3269 | |
|
3270 | 0 | if (!filter_index->LookupFilterHeader(block_index, headers[i])) { |
3271 | 0 | LogDebug(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3272 | 0 | BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString()); |
3273 | 0 | return; |
3274 | 0 | } |
3275 | 0 | } |
3276 | | |
3277 | 0 | MakeAndPushMessage(node, NetMsgType::CFCHECKPT, |
3278 | 0 | filter_type_ser, |
3279 | 0 | stop_index->GetBlockHash(), |
3280 | 0 | headers); |
3281 | 0 | } |
3282 | | |
3283 | | void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked) |
3284 | 200k | { |
3285 | 200k | bool new_block{false}; |
3286 | 200k | m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block); |
3287 | 200k | if (new_block) { |
3288 | 199k | node.m_last_block_time = GetTime<std::chrono::seconds>(); |
3289 | | // In case this block came from a different peer than we requested |
3290 | | // from, we can erase the block request now anyway (as we just stored |
3291 | | // this block to disk). |
3292 | 199k | LOCK(cs_main); Line | Count | Source | 259 | 199k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 199k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 199k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 199k | #define PASTE(x, y) x ## y |
|
|
|
|
3293 | 199k | RemoveBlockRequest(block->GetHash(), std::nullopt); |
3294 | 199k | } else { |
3295 | 454 | LOCK(cs_main); Line | Count | Source | 259 | 454 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 454 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 454 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 454 | #define PASTE(x, y) x ## y |
|
|
|
|
3296 | 454 | mapBlockSource.erase(block->GetHash()); |
3297 | 454 | } |
3298 | 200k | } |
3299 | | |
3300 | | void PeerManagerImpl::ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions) |
3301 | 368k | { |
3302 | 368k | std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); |
3303 | 368k | bool fBlockRead{false}; |
3304 | 368k | { |
3305 | 368k | LOCK(cs_main); Line | Count | Source | 259 | 368k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 368k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 368k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 368k | #define PASTE(x, y) x ## y |
|
|
|
|
3306 | | |
3307 | 368k | auto range_flight = mapBlocksInFlight.equal_range(block_transactions.blockhash); |
3308 | 368k | size_t already_in_flight = std::distance(range_flight.first, range_flight.second); |
3309 | 368k | bool requested_block_from_this_peer{false}; |
3310 | | |
3311 | | // Multimap ensures ordering of outstanding requests. It's either empty or first in line. |
3312 | 368k | bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId())223k ; |
3313 | | |
3314 | 407k | while (range_flight.first != range_flight.second) { |
3315 | 247k | auto [node_id, block_it] = range_flight.first->second; |
3316 | 247k | if (node_id == pfrom.GetId() && block_it->partialBlock210k ) { |
3317 | 208k | requested_block_from_this_peer = true; |
3318 | 208k | break; |
3319 | 208k | } |
3320 | 39.5k | range_flight.first++; |
3321 | 39.5k | } |
3322 | | |
3323 | 368k | if (!requested_block_from_this_peer) { |
3324 | 160k | LogDebug(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId()); Line | Count | Source | 381 | 160k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 160k | do { \ | 374 | 160k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 160k | } while (0) |
|
|
3325 | 160k | return; |
3326 | 160k | } |
3327 | | |
3328 | 208k | PartiallyDownloadedBlock& partialBlock = *range_flight.first->second.second->partialBlock; |
3329 | | |
3330 | | // We should not have gotten this far in compact block processing unless it's attached to a known header |
3331 | 208k | const CBlockIndex* prev_block{m_chainman.m_blockman.LookupBlockIndex(partialBlock.header.hashPrevBlock)}; |
3332 | 208k | ReadStatus status = partialBlock.FillBlock(*pblock, block_transactions.txn, |
3333 | 208k | /*segwit_active=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT)); |
3334 | 208k | if (status == READ_STATUS_INVALID) { |
3335 | 11.2k | RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect |
3336 | 11.2k | Misbehaving(peer, "invalid compact block/non-matching block transactions"); |
3337 | 11.2k | return; |
3338 | 196k | } else if (status == READ_STATUS_FAILED) { |
3339 | 207 | if (first_in_flight) { |
3340 | | // Might have collided, fall back to getdata now :( |
3341 | 174 | std::vector<CInv> invs; |
3342 | 174 | invs.emplace_back(MSG_BLOCK | GetFetchFlags(peer), block_transactions.blockhash); |
3343 | 174 | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, invs); |
3344 | 174 | } else { |
3345 | 33 | RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); |
3346 | 33 | LogDebug(BCLog::NET, "Peer %d sent us a compact block but it failed to reconstruct, waiting on first download to complete\n", pfrom.GetId()); Line | Count | Source | 381 | 33 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 33 | do { \ | 374 | 33 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 33 | } while (0) |
|
|
3347 | 33 | return; |
3348 | 33 | } |
3349 | 196k | } else { |
3350 | | // Block is okay for further processing |
3351 | 196k | RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // it is now an empty pointer |
3352 | 196k | fBlockRead = true; |
3353 | | // mapBlockSource is used for potentially punishing peers and |
3354 | | // updating which peers send us compact blocks, so the race |
3355 | | // between here and cs_main in ProcessNewBlock is fine. |
3356 | | // BIP 152 permits peers to relay compact blocks after validating |
3357 | | // the header only; we should not punish peers if the block turns |
3358 | | // out to be invalid. |
3359 | 196k | mapBlockSource.emplace(block_transactions.blockhash, std::make_pair(pfrom.GetId(), false)); |
3360 | 196k | } |
3361 | 208k | } // Don't hold cs_main when we call into ProcessNewBlock |
3362 | 196k | if (fBlockRead) { |
3363 | | // Since we requested this block (it was in mapBlocksInFlight), force it to be processed, |
3364 | | // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc) |
3365 | | // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent |
3366 | | // disk-space attacks), but this should be safe due to the |
3367 | | // protections in the compact block handler -- see related comment |
3368 | | // in compact block optimistic reconstruction handling. |
3369 | 196k | ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true); |
3370 | 196k | } |
3371 | 196k | return; |
3372 | 208k | } |
3373 | | |
3374 | 302k | void PeerManagerImpl::LogBlockHeader(const CBlockIndex& index, const CNode& peer, bool via_compact_block) { |
3375 | | // To prevent log spam, this function should only be called after it was determined that a |
3376 | | // header is both new and valid. |
3377 | | // |
3378 | | // These messages are valuable for detecting potential selfish mining behavior; |
3379 | | // if multiple displacing headers are seen near simultaneously across many |
3380 | | // nodes in the network, this might be an indication of selfish mining. |
3381 | | // In addition it can be used to identify peers which send us a header, but |
3382 | | // don't followup with a complete and valid (compact) block. |
3383 | | // Having this log by default when not in IBD ensures broad availability of |
3384 | | // this data in case investigation is merited. |
3385 | 302k | const auto msg = strprintf( Line | Count | Source | 1172 | 302k | #define strprintf tfm::format |
|
3386 | 302k | "Saw new %sheader hash=%s height=%d peer=%d%s", |
3387 | 302k | via_compact_block ? "cmpctblock "286k : ""15.4k , |
3388 | 302k | index.GetBlockHash().ToString(), |
3389 | 302k | index.nHeight, |
3390 | 302k | peer.GetId(), |
3391 | 302k | peer.LogIP(fLogIPs) |
3392 | 302k | ); |
3393 | 302k | if (m_chainman.IsInitialBlockDownload()) { |
3394 | 11.0k | LogDebug(BCLog::VALIDATION, "%s", msg); Line | Count | Source | 381 | 11.0k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 11.0k | do { \ | 374 | 11.0k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 11.0k | } while (0) |
|
|
3395 | 291k | } else { |
3396 | 291k | LogInfo("%s", msg); Line | Count | Source | 356 | 291k | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 291k | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
3397 | 291k | } |
3398 | 302k | } |
3399 | | |
3400 | | void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, |
3401 | | const std::chrono::microseconds time_received, |
3402 | | const std::atomic<bool>& interruptMsgProc) |
3403 | 6.02M | { |
3404 | 6.02M | AssertLockHeld(g_msgproc_mutex); Line | Count | Source | 137 | 6.02M | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
3405 | | |
3406 | 6.02M | LogDebug(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId()); Line | Count | Source | 381 | 6.02M | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 6.02M | do { \ | 374 | 6.02M | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 6.02M | } while (0) |
|
|
3407 | | |
3408 | 6.02M | PeerRef peer = GetPeerRef(pfrom.GetId()); |
3409 | 6.02M | if (peer == nullptr) return0 ; |
3410 | | |
3411 | 6.02M | if (msg_type == NetMsgType::VERSION) { |
3412 | 115k | if (pfrom.nVersion != 0) { |
3413 | 0 | LogDebug(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3414 | 0 | return; |
3415 | 0 | } |
3416 | | |
3417 | 115k | int64_t nTime; |
3418 | 115k | CService addrMe; |
3419 | 115k | uint64_t nNonce = 1; |
3420 | 115k | ServiceFlags nServices; |
3421 | 115k | int nVersion; |
3422 | 115k | std::string cleanSubVer; |
3423 | 115k | int starting_height = -1; |
3424 | 115k | bool fRelay = true; |
3425 | | |
3426 | 115k | vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime; |
3427 | 115k | if (nTime < 0) { |
3428 | 0 | nTime = 0; |
3429 | 0 | } |
3430 | 115k | vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer |
3431 | 115k | vRecv >> CNetAddr::V1(addrMe); |
3432 | 115k | if (!pfrom.IsInboundConn()) |
3433 | 76.4k | { |
3434 | | // Overwrites potentially existing services. In contrast to this, |
3435 | | // unvalidated services received via gossip relay in ADDR/ADDRV2 |
3436 | | // messages are only ever added but cannot replace existing ones. |
3437 | 76.4k | m_addrman.SetServices(pfrom.addr, nServices); |
3438 | 76.4k | } |
3439 | 115k | if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices)8.79k ) |
3440 | 6.04k | { |
3441 | 6.04k | LogDebug(BCLog::NET, "peer does not offer the expected services (%08x offered, %08x expected), %s\n", Line | Count | Source | 381 | 6.04k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 6.04k | do { \ | 374 | 6.04k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 6.04k | } while (0) |
|
|
3442 | 6.04k | nServices, |
3443 | 6.04k | GetDesirableServiceFlags(nServices), |
3444 | 6.04k | pfrom.DisconnectMsg(fLogIPs)); |
3445 | 6.04k | pfrom.fDisconnect = true; |
3446 | 6.04k | return; |
3447 | 6.04k | } |
3448 | | |
3449 | 109k | if (nVersion < MIN_PEER_PROTO_VERSION) { |
3450 | | // disconnect from peers older than this proto version |
3451 | 0 | LogDebug(BCLog::NET, "peer using obsolete version %i, %s\n", nVersion, pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3452 | 0 | pfrom.fDisconnect = true; |
3453 | 0 | return; |
3454 | 0 | } |
3455 | | |
3456 | 109k | if (!vRecv.empty()) { |
3457 | | // The version message includes information about the sending node which we don't use: |
3458 | | // - 8 bytes (service bits) |
3459 | | // - 16 bytes (ipv6 address) |
3460 | | // - 2 bytes (port) |
3461 | 109k | vRecv.ignore(26); |
3462 | 109k | vRecv >> nNonce; |
3463 | 109k | } |
3464 | 109k | if (!vRecv.empty()) { |
3465 | 109k | std::string strSubVer; |
3466 | 109k | vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH); Line | Count | Source | 493 | 109k | #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj) |
|
3467 | 109k | cleanSubVer = SanitizeString(strSubVer); |
3468 | 109k | } |
3469 | 109k | if (!vRecv.empty()) { |
3470 | 109k | vRecv >> starting_height; |
3471 | 109k | } |
3472 | 109k | if (!vRecv.empty()) |
3473 | 109k | vRecv >> fRelay; |
3474 | | // Disconnect if we connected to ourself |
3475 | 109k | if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce)39.4k ) |
3476 | 973 | { |
3477 | 973 | LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToStringAddrPort()); Line | Count | Source | 361 | 973 | #define LogPrintf(...) LogInfo(__VA_ARGS__) Line | Count | Source | 356 | 973 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 973 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
|
3478 | 973 | pfrom.fDisconnect = true; |
3479 | 973 | return; |
3480 | 973 | } |
3481 | | |
3482 | 108k | if (pfrom.IsInboundConn() && addrMe.IsRoutable()38.4k ) |
3483 | 0 | { |
3484 | 0 | SeenLocal(addrMe); |
3485 | 0 | } |
3486 | | |
3487 | | // Inbound peers send us their version message when they connect. |
3488 | | // We send our version message in response. |
3489 | 108k | if (pfrom.IsInboundConn()) { |
3490 | 38.4k | PushNodeVersion(pfrom, *peer); |
3491 | 38.4k | } |
3492 | | |
3493 | | // Change version |
3494 | 108k | const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION); |
3495 | 108k | pfrom.SetCommonVersion(greatest_common_version); |
3496 | 108k | pfrom.nVersion = nVersion; |
3497 | | |
3498 | 108k | if (greatest_common_version >= WTXID_RELAY_VERSION) { |
3499 | 102k | MakeAndPushMessage(pfrom, NetMsgType::WTXIDRELAY); |
3500 | 102k | } |
3501 | | |
3502 | | // Signal ADDRv2 support (BIP155). |
3503 | 108k | if (greatest_common_version >= 70016) { |
3504 | | // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some |
3505 | | // implementations reject messages they don't know. As a courtesy, don't send |
3506 | | // it to nodes with a version before 70016, as no software is known to support |
3507 | | // BIP155 that doesn't announce at least that protocol version number. |
3508 | 102k | MakeAndPushMessage(pfrom, NetMsgType::SENDADDRV2); |
3509 | 102k | } |
3510 | | |
3511 | 108k | pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices); |
3512 | 108k | peer->m_their_services = nServices; |
3513 | 108k | pfrom.SetAddrLocal(addrMe); |
3514 | 108k | { |
3515 | 108k | LOCK(pfrom.m_subver_mutex); Line | Count | Source | 259 | 108k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 108k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 108k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 108k | #define PASTE(x, y) x ## y |
|
|
|
|
3516 | 108k | pfrom.cleanSubVer = cleanSubVer; |
3517 | 108k | } |
3518 | 108k | peer->m_starting_height = starting_height; |
3519 | | |
3520 | | // Only initialize the Peer::TxRelay m_relay_txs data structure if: |
3521 | | // - this isn't an outbound block-relay-only connection, and |
3522 | | // - this isn't an outbound feeler connection, and |
3523 | | // - fRelay=true (the peer wishes to receive transaction announcements) |
3524 | | // or we're offering NODE_BLOOM to this peer. NODE_BLOOM means that |
3525 | | // the peer may turn on transaction relay later. |
3526 | 108k | if (!pfrom.IsBlockOnlyConn() && |
3527 | 108k | !pfrom.IsFeelerConn()108k && |
3528 | 108k | (88.1k fRelay88.1k || (peer->m_our_services & NODE_BLOOM)51.1k )) { |
3529 | 56.3k | auto* const tx_relay = peer->SetTxRelay(); |
3530 | 56.3k | { |
3531 | 56.3k | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 56.3k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 56.3k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 56.3k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 56.3k | #define PASTE(x, y) x ## y |
|
|
|
|
3532 | 56.3k | tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message |
3533 | 56.3k | } |
3534 | 56.3k | if (fRelay) pfrom.m_relays_txs = true37.0k ; |
3535 | 56.3k | } |
3536 | | |
3537 | 108k | if (greatest_common_version >= WTXID_RELAY_VERSION && m_txreconciliation102k ) { |
3538 | | // Per BIP-330, we announce txreconciliation support if: |
3539 | | // - protocol version per the peer's VERSION message supports WTXID_RELAY; |
3540 | | // - transaction relay is supported per the peer's VERSION message |
3541 | | // - this is not a block-relay-only connection and not a feeler |
3542 | | // - this is not an addr fetch connection; |
3543 | | // - we are not in -blocksonly mode. |
3544 | 0 | const auto* tx_relay = peer->GetTxRelay(); |
3545 | 0 | if (tx_relay && WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs) && Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
3546 | 0 | !pfrom.IsAddrFetchConn() && !m_opts.ignore_incoming_txs) { |
3547 | 0 | const uint64_t recon_salt = m_txreconciliation->PreRegisterPeer(pfrom.GetId()); |
3548 | 0 | MakeAndPushMessage(pfrom, NetMsgType::SENDTXRCNCL, |
3549 | 0 | TXRECONCILIATION_VERSION, recon_salt); |
3550 | 0 | } |
3551 | 0 | } |
3552 | | |
3553 | 108k | MakeAndPushMessage(pfrom, NetMsgType::VERACK); |
3554 | | |
3555 | | // Potentially mark this peer as a preferred download peer. |
3556 | 108k | { |
3557 | 108k | LOCK(cs_main); Line | Count | Source | 259 | 108k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 108k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 108k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 108k | #define PASTE(x, y) x ## y |
|
|
|
|
3558 | 108k | CNodeState* state = State(pfrom.GetId()); |
3559 | 108k | state->fPreferredDownload = (!pfrom.IsInboundConn() || pfrom.HasPermission(NetPermissionFlags::NoBan)38.4k ) && !pfrom.IsAddrFetchConn()83.0k && CanServeBlocks(*peer)82.7k ; |
3560 | 108k | m_num_preferred_download_peers += state->fPreferredDownload; |
3561 | 108k | } |
3562 | | |
3563 | | // Attempt to initialize address relay for outbound peers and use result |
3564 | | // to decide whether to send GETADDR, so that we don't send it to |
3565 | | // inbound or outbound block-relay-only peers. |
3566 | 108k | bool send_getaddr{false}; |
3567 | 108k | if (!pfrom.IsInboundConn()) { |
3568 | 70.4k | send_getaddr = SetupAddressRelay(pfrom, *peer); |
3569 | 70.4k | } |
3570 | 108k | if (send_getaddr) { |
3571 | | // Do a one-time address fetch to help populate/update our addrman. |
3572 | | // If we're starting up for the first time, our addrman may be pretty |
3573 | | // empty, so this mechanism is important to help us connect to the network. |
3574 | | // We skip this for block-relay-only peers. We want to avoid |
3575 | | // potentially leaking addr information and we do not want to |
3576 | | // indicate to the peer that we will participate in addr relay. |
3577 | 69.5k | MakeAndPushMessage(pfrom, NetMsgType::GETADDR); |
3578 | 69.5k | peer->m_getaddr_sent = true; |
3579 | | // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response |
3580 | | // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit). |
3581 | 69.5k | peer->m_addr_token_bucket += MAX_ADDR_TO_SEND; |
3582 | 69.5k | } |
3583 | | |
3584 | 108k | if (!pfrom.IsInboundConn()) { |
3585 | | // For non-inbound connections, we update the addrman to record |
3586 | | // connection success so that addrman will have an up-to-date |
3587 | | // notion of which peers are online and available. |
3588 | | // |
3589 | | // While we strive to not leak information about block-relay-only |
3590 | | // connections via the addrman, not moving an address to the tried |
3591 | | // table is also potentially detrimental because new-table entries |
3592 | | // are subject to eviction in the event of addrman collisions. We |
3593 | | // mitigate the information-leak by never calling |
3594 | | // AddrMan::Connected() on block-relay-only peers; see |
3595 | | // FinalizeNode(). |
3596 | | // |
3597 | | // This moves an address from New to Tried table in Addrman, |
3598 | | // resolves tried-table collisions, etc. |
3599 | 70.4k | m_addrman.Good(pfrom.addr); |
3600 | 70.4k | } |
3601 | | |
3602 | 108k | const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)}; |
3603 | 108k | LogDebug(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s%s\n", Line | Count | Source | 381 | 108k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 108k | do { \ | 374 | 108k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 108k | } while (0) |
|
|
3604 | 108k | cleanSubVer, pfrom.nVersion, |
3605 | 108k | peer->m_starting_height, addrMe.ToStringAddrPort(), fRelay, pfrom.GetId(), |
3606 | 108k | pfrom.LogIP(fLogIPs), (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : "")); |
3607 | | |
3608 | 108k | peer->m_time_offset = NodeSeconds{std::chrono::seconds{nTime}} - Now<NodeSeconds>(); |
3609 | 108k | if (!pfrom.IsInboundConn()) { |
3610 | | // Don't use timedata samples from inbound peers to make it |
3611 | | // harder for others to create false warnings about our clock being out of sync. |
3612 | 70.4k | m_outbound_time_offsets.Add(peer->m_time_offset); |
3613 | 70.4k | m_outbound_time_offsets.WarnIfOutOfSync(); |
3614 | 70.4k | } |
3615 | | |
3616 | | // If the peer is old enough to have the old alert system, send it the final alert. |
3617 | 108k | if (greatest_common_version <= 70012) { |
3618 | 6.81k | constexpr auto finalAlert{"60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"_hex}; |
3619 | 6.81k | MakeAndPushMessage(pfrom, "alert", finalAlert); |
3620 | 6.81k | } |
3621 | | |
3622 | | // Feeler connections exist only to verify if address is online. |
3623 | 108k | if (pfrom.IsFeelerConn()) { |
3624 | 19.8k | LogDebug(BCLog::NET, "feeler connection completed, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 19.8k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 19.8k | do { \ | 374 | 19.8k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 19.8k | } while (0) |
|
|
3625 | 19.8k | pfrom.fDisconnect = true; |
3626 | 19.8k | } |
3627 | 108k | return; |
3628 | 109k | } |
3629 | | |
3630 | 5.90M | if (pfrom.nVersion == 0) { |
3631 | | // Must have a version message before anything else |
3632 | 0 | LogDebug(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3633 | 0 | return; |
3634 | 0 | } |
3635 | | |
3636 | 5.90M | if (msg_type == NetMsgType::VERACK) { |
3637 | 77.0k | if (pfrom.fSuccessfullyConnected) { |
3638 | 0 | LogDebug(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3639 | 0 | return; |
3640 | 0 | } |
3641 | | |
3642 | | // Log successful connections unconditionally for outbound, but not for inbound as those |
3643 | | // can be triggered by an attacker at high rate. |
3644 | 77.0k | if (!pfrom.IsInboundConn() || LogAcceptCategory(BCLog::NET, BCLog::Level::Debug)29.7k ) { |
3645 | 47.3k | const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)}; |
3646 | 47.3k | LogPrintf("New %s %s peer connected: version: %d, blocks=%d, peer=%d%s%s\n", Line | Count | Source | 361 | 47.3k | #define LogPrintf(...) LogInfo(__VA_ARGS__) Line | Count | Source | 356 | 47.3k | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 94.6k | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, 47.3k __VA_ARGS__) |
|
|
|
3647 | 47.3k | pfrom.ConnectionTypeAsString(), |
3648 | 47.3k | TransportTypeAsString(pfrom.m_transport->GetInfo().transport_type), |
3649 | 47.3k | pfrom.nVersion.load(), peer->m_starting_height, |
3650 | 47.3k | pfrom.GetId(), pfrom.LogIP(fLogIPs), |
3651 | 47.3k | (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : "")); |
3652 | 47.3k | } |
3653 | | |
3654 | 77.0k | if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) { |
3655 | | // Tell our peer we are willing to provide version 2 cmpctblocks. |
3656 | | // However, we do not request new block announcements using |
3657 | | // cmpctblock messages. |
3658 | | // We send this to non-NODE NETWORK peers as well, because |
3659 | | // they may wish to request compact blocks from us |
3660 | 76.1k | MakeAndPushMessage(pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION); |
3661 | 76.1k | } |
3662 | | |
3663 | 77.0k | if (m_txreconciliation) { |
3664 | 0 | if (!peer->m_wtxid_relay || !m_txreconciliation->IsPeerRegistered(pfrom.GetId())) { |
3665 | | // We could have optimistically pre-registered/registered the peer. In that case, |
3666 | | // we should forget about the reconciliation state here if this wasn't followed |
3667 | | // by WTXIDRELAY (since WTXIDRELAY can't be announced later). |
3668 | 0 | m_txreconciliation->ForgetPeer(pfrom.GetId()); |
3669 | 0 | } |
3670 | 0 | } |
3671 | | |
3672 | 77.0k | if (auto tx_relay = peer->GetTxRelay()) { |
3673 | | // `TxRelay::m_tx_inventory_to_send` must be empty before the |
3674 | | // version handshake is completed as |
3675 | | // `TxRelay::m_next_inv_send_time` is first initialised in |
3676 | | // `SendMessages` after the verack is received. Any transactions |
3677 | | // received during the version handshake would otherwise |
3678 | | // immediately be advertised without random delay, potentially |
3679 | | // leaking the time of arrival to a spy. |
3680 | 51.0k | Assume(WITH_LOCK( Line | Count | Source | 118 | 51.0k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
3681 | 51.0k | tx_relay->m_tx_inventory_mutex, |
3682 | 51.0k | return tx_relay->m_tx_inventory_to_send.empty() && |
3683 | 51.0k | tx_relay->m_next_inv_send_time == 0s)); |
3684 | 51.0k | } |
3685 | | |
3686 | 77.0k | { |
3687 | 77.0k | LOCK2(::cs_main, m_tx_download_mutex); Line | Count | Source | 261 | 77.0k | UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \ | 262 | 77.0k | UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__) |
|
3688 | 77.0k | const CNodeState* state = State(pfrom.GetId()); |
3689 | 77.0k | m_txdownloadman.ConnectedPeer(pfrom.GetId(), node::TxDownloadConnectionInfo { |
3690 | 77.0k | .m_preferred = state->fPreferredDownload, |
3691 | 77.0k | .m_relay_permissions = pfrom.HasPermission(NetPermissionFlags::Relay), |
3692 | 77.0k | .m_wtxid_relay = peer->m_wtxid_relay, |
3693 | 77.0k | }); |
3694 | 77.0k | } |
3695 | | |
3696 | 77.0k | pfrom.fSuccessfullyConnected = true; |
3697 | 77.0k | return; |
3698 | 77.0k | } |
3699 | | |
3700 | 5.82M | if (msg_type == NetMsgType::SENDHEADERS) { |
3701 | 0 | peer->m_prefers_headers = true; |
3702 | 0 | return; |
3703 | 0 | } |
3704 | | |
3705 | 5.82M | if (msg_type == NetMsgType::SENDCMPCT) { |
3706 | 126k | bool sendcmpct_hb{false}; |
3707 | 126k | uint64_t sendcmpct_version{0}; |
3708 | 126k | vRecv >> sendcmpct_hb >> sendcmpct_version; |
3709 | | |
3710 | | // Only support compact block relay with witnesses |
3711 | 126k | if (sendcmpct_version != CMPCTBLOCKS_VERSION) return0 ; |
3712 | | |
3713 | 126k | LOCK(cs_main); Line | Count | Source | 259 | 126k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 126k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 126k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 126k | #define PASTE(x, y) x ## y |
|
|
|
|
3714 | 126k | CNodeState* nodestate = State(pfrom.GetId()); |
3715 | 126k | nodestate->m_provides_cmpctblocks = true; |
3716 | 126k | nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb; |
3717 | | // save whether peer selects us as BIP152 high-bandwidth peer |
3718 | | // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth) |
3719 | 126k | pfrom.m_bip152_highbandwidth_from = sendcmpct_hb; |
3720 | 126k | return; |
3721 | 126k | } |
3722 | | |
3723 | | // BIP339 defines feature negotiation of wtxidrelay, which must happen between |
3724 | | // VERSION and VERACK to avoid relay problems from switching after a connection is up. |
3725 | 5.70M | if (msg_type == NetMsgType::WTXIDRELAY) { |
3726 | 0 | if (pfrom.fSuccessfullyConnected) { |
3727 | | // Disconnect peers that send a wtxidrelay message after VERACK. |
3728 | 0 | LogDebug(BCLog::NET, "wtxidrelay received after verack, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3729 | 0 | pfrom.fDisconnect = true; |
3730 | 0 | return; |
3731 | 0 | } |
3732 | 0 | if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) { |
3733 | 0 | if (!peer->m_wtxid_relay) { |
3734 | 0 | peer->m_wtxid_relay = true; |
3735 | 0 | m_wtxid_relay_peers++; |
3736 | 0 | } else { |
3737 | 0 | LogDebug(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3738 | 0 | } |
3739 | 0 | } else { |
3740 | 0 | LogDebug(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3741 | 0 | } |
3742 | 0 | return; |
3743 | 0 | } |
3744 | | |
3745 | | // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen |
3746 | | // between VERSION and VERACK. |
3747 | 5.70M | if (msg_type == NetMsgType::SENDADDRV2) { |
3748 | 0 | if (pfrom.fSuccessfullyConnected) { |
3749 | | // Disconnect peers that send a SENDADDRV2 message after VERACK. |
3750 | 0 | LogDebug(BCLog::NET, "sendaddrv2 received after verack, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3751 | 0 | pfrom.fDisconnect = true; |
3752 | 0 | return; |
3753 | 0 | } |
3754 | 0 | peer->m_wants_addrv2 = true; |
3755 | 0 | return; |
3756 | 0 | } |
3757 | | |
3758 | | // Received from a peer demonstrating readiness to announce transactions via reconciliations. |
3759 | | // This feature negotiation must happen between VERSION and VERACK to avoid relay problems |
3760 | | // from switching announcement protocols after the connection is up. |
3761 | 5.70M | if (msg_type == NetMsgType::SENDTXRCNCL) { |
3762 | 0 | if (!m_txreconciliation) { |
3763 | 0 | LogDebug(BCLog::NET, "sendtxrcncl from peer=%d ignored, as our node does not have txreconciliation enabled\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3764 | 0 | return; |
3765 | 0 | } |
3766 | | |
3767 | 0 | if (pfrom.fSuccessfullyConnected) { |
3768 | 0 | LogDebug(BCLog::NET, "sendtxrcncl received after verack, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3769 | 0 | pfrom.fDisconnect = true; |
3770 | 0 | return; |
3771 | 0 | } |
3772 | | |
3773 | | // Peer must not offer us reconciliations if we specified no tx relay support in VERSION. |
3774 | 0 | if (RejectIncomingTxs(pfrom)) { |
3775 | 0 | LogDebug(BCLog::NET, "sendtxrcncl received to which we indicated no tx relay, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3776 | 0 | pfrom.fDisconnect = true; |
3777 | 0 | return; |
3778 | 0 | } |
3779 | | |
3780 | | // Peer must not offer us reconciliations if they specified no tx relay support in VERSION. |
3781 | | // This flag might also be false in other cases, but the RejectIncomingTxs check above |
3782 | | // eliminates them, so that this flag fully represents what we are looking for. |
3783 | 0 | const auto* tx_relay = peer->GetTxRelay(); |
3784 | 0 | if (!tx_relay || !WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs)) { Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
3785 | 0 | LogDebug(BCLog::NET, "sendtxrcncl received which indicated no tx relay to us, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3786 | 0 | pfrom.fDisconnect = true; |
3787 | 0 | return; |
3788 | 0 | } |
3789 | | |
3790 | 0 | uint32_t peer_txreconcl_version; |
3791 | 0 | uint64_t remote_salt; |
3792 | 0 | vRecv >> peer_txreconcl_version >> remote_salt; |
3793 | |
|
3794 | 0 | const ReconciliationRegisterResult result = m_txreconciliation->RegisterPeer(pfrom.GetId(), pfrom.IsInboundConn(), |
3795 | 0 | peer_txreconcl_version, remote_salt); |
3796 | 0 | switch (result) { |
3797 | 0 | case ReconciliationRegisterResult::NOT_FOUND: |
3798 | 0 | LogDebug(BCLog::NET, "Ignore unexpected txreconciliation signal from peer=%d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3799 | 0 | break; |
3800 | 0 | case ReconciliationRegisterResult::SUCCESS: |
3801 | 0 | break; |
3802 | 0 | case ReconciliationRegisterResult::ALREADY_REGISTERED: |
3803 | 0 | LogDebug(BCLog::NET, "txreconciliation protocol violation (sendtxrcncl received from already registered peer), %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3804 | 0 | pfrom.fDisconnect = true; |
3805 | 0 | return; |
3806 | 0 | case ReconciliationRegisterResult::PROTOCOL_VIOLATION: |
3807 | 0 | LogDebug(BCLog::NET, "txreconciliation protocol violation, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3808 | 0 | pfrom.fDisconnect = true; |
3809 | 0 | return; |
3810 | 0 | } |
3811 | 0 | return; |
3812 | 0 | } |
3813 | | |
3814 | 5.70M | if (!pfrom.fSuccessfullyConnected) { |
3815 | 17.6k | LogDebug(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); Line | Count | Source | 381 | 17.6k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 17.6k | do { \ | 374 | 17.6k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 17.6k | } while (0) |
|
|
3816 | 17.6k | return; |
3817 | 17.6k | } |
3818 | | |
3819 | 5.68M | if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) { |
3820 | 0 | const auto ser_params{ |
3821 | 0 | msg_type == NetMsgType::ADDRV2 ? |
3822 | | // Set V2 param so that the CNetAddr and CAddress |
3823 | | // unserialize methods know that an address in v2 format is coming. |
3824 | 0 | CAddress::V2_NETWORK : |
3825 | 0 | CAddress::V1_NETWORK, |
3826 | 0 | }; |
3827 | |
|
3828 | 0 | std::vector<CAddress> vAddr; |
3829 | |
|
3830 | 0 | vRecv >> ser_params(vAddr); |
3831 | |
|
3832 | 0 | if (!SetupAddressRelay(pfrom, *peer)) { |
3833 | 0 | LogDebug(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3834 | 0 | return; |
3835 | 0 | } |
3836 | | |
3837 | 0 | if (vAddr.size() > MAX_ADDR_TO_SEND) |
3838 | 0 | { |
3839 | 0 | Misbehaving(*peer, strprintf("%s message size = %u", msg_type, vAddr.size())); Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
3840 | 0 | return; |
3841 | 0 | } |
3842 | | |
3843 | | // Store the new addresses |
3844 | 0 | std::vector<CAddress> vAddrOk; |
3845 | 0 | const auto current_a_time{Now<NodeSeconds>()}; |
3846 | | |
3847 | | // Update/increment addr rate limiting bucket. |
3848 | 0 | const auto current_time{GetTime<std::chrono::microseconds>()}; |
3849 | 0 | if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) { |
3850 | | // Don't increment bucket if it's already full |
3851 | 0 | const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us); |
3852 | 0 | const double increment = Ticks<SecondsDouble>(time_diff) * MAX_ADDR_RATE_PER_SECOND; |
3853 | 0 | peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET); |
3854 | 0 | } |
3855 | 0 | peer->m_addr_token_timestamp = current_time; |
3856 | |
|
3857 | 0 | const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr); |
3858 | 0 | uint64_t num_proc = 0; |
3859 | 0 | uint64_t num_rate_limit = 0; |
3860 | 0 | std::shuffle(vAddr.begin(), vAddr.end(), m_rng); |
3861 | 0 | for (CAddress& addr : vAddr) |
3862 | 0 | { |
3863 | 0 | if (interruptMsgProc) |
3864 | 0 | return; |
3865 | | |
3866 | | // Apply rate limiting. |
3867 | 0 | if (peer->m_addr_token_bucket < 1.0) { |
3868 | 0 | if (rate_limited) { |
3869 | 0 | ++num_rate_limit; |
3870 | 0 | continue; |
3871 | 0 | } |
3872 | 0 | } else { |
3873 | 0 | peer->m_addr_token_bucket -= 1.0; |
3874 | 0 | } |
3875 | | // We only bother storing full nodes, though this may include |
3876 | | // things which we would not make an outbound connection to, in |
3877 | | // part because we may make feeler connections to them. |
3878 | 0 | if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices)) |
3879 | 0 | continue; |
3880 | | |
3881 | 0 | if (addr.nTime <= NodeSeconds{100000000s} || addr.nTime > current_a_time + 10min) { |
3882 | 0 | addr.nTime = current_a_time - 5 * 24h; |
3883 | 0 | } |
3884 | 0 | AddAddressKnown(*peer, addr); |
3885 | 0 | if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) { |
3886 | | // Do not process banned/discouraged addresses beyond remembering we received them |
3887 | 0 | continue; |
3888 | 0 | } |
3889 | 0 | ++num_proc; |
3890 | 0 | const bool reachable{g_reachable_nets.Contains(addr)}; |
3891 | 0 | if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) { |
3892 | | // Relay to a limited number of other nodes |
3893 | 0 | RelayAddress(pfrom.GetId(), addr, reachable); |
3894 | 0 | } |
3895 | | // Do not store addresses outside our network |
3896 | 0 | if (reachable) { |
3897 | 0 | vAddrOk.push_back(addr); |
3898 | 0 | } |
3899 | 0 | } |
3900 | 0 | peer->m_addr_processed += num_proc; |
3901 | 0 | peer->m_addr_rate_limited += num_rate_limit; |
3902 | 0 | LogDebug(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3903 | 0 | vAddr.size(), num_proc, num_rate_limit, pfrom.GetId()); |
3904 | |
|
3905 | 0 | m_addrman.Add(vAddrOk, pfrom.addr, 2h); |
3906 | 0 | if (vAddr.size() < 1000) peer->m_getaddr_sent = false; |
3907 | | |
3908 | | // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements |
3909 | 0 | if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) { |
3910 | 0 | LogDebug(BCLog::NET, "addrfetch connection completed, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3911 | 0 | pfrom.fDisconnect = true; |
3912 | 0 | } |
3913 | 0 | return; |
3914 | 0 | } |
3915 | | |
3916 | 5.68M | if (msg_type == NetMsgType::INV) { |
3917 | 0 | std::vector<CInv> vInv; |
3918 | 0 | vRecv >> vInv; |
3919 | 0 | if (vInv.size() > MAX_INV_SZ) |
3920 | 0 | { |
3921 | 0 | Misbehaving(*peer, strprintf("inv message size = %u", vInv.size())); Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
3922 | 0 | return; |
3923 | 0 | } |
3924 | | |
3925 | 0 | const bool reject_tx_invs{RejectIncomingTxs(pfrom)}; |
3926 | |
|
3927 | 0 | LOCK2(cs_main, m_tx_download_mutex); Line | Count | Source | 261 | 0 | UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \ | 262 | 0 | UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__) |
|
3928 | |
|
3929 | 0 | const auto current_time{GetTime<std::chrono::microseconds>()}; |
3930 | 0 | uint256* best_block{nullptr}; |
3931 | |
|
3932 | 0 | for (CInv& inv : vInv) { |
3933 | 0 | if (interruptMsgProc) return; |
3934 | | |
3935 | | // Ignore INVs that don't match wtxidrelay setting. |
3936 | | // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting. |
3937 | | // This is fine as no INV messages are involved in that process. |
3938 | 0 | if (peer->m_wtxid_relay) { |
3939 | 0 | if (inv.IsMsgTx()) continue; |
3940 | 0 | } else { |
3941 | 0 | if (inv.IsMsgWtx()) continue; |
3942 | 0 | } |
3943 | | |
3944 | 0 | if (inv.IsMsgBlk()) { |
3945 | 0 | const bool fAlreadyHave = AlreadyHaveBlock(inv.hash); |
3946 | 0 | LogDebug(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3947 | |
|
3948 | 0 | UpdateBlockAvailability(pfrom.GetId(), inv.hash); |
3949 | 0 | if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() && !IsBlockRequested(inv.hash)) { |
3950 | | // Headers-first is the primary method of announcement on |
3951 | | // the network. If a node fell back to sending blocks by |
3952 | | // inv, it may be for a re-org, or because we haven't |
3953 | | // completed initial headers sync. The final block hash |
3954 | | // provided should be the highest, so send a getheaders and |
3955 | | // then fetch the blocks we need to catch up. |
3956 | 0 | best_block = &inv.hash; |
3957 | 0 | } |
3958 | 0 | } else if (inv.IsGenTxMsg()) { |
3959 | 0 | if (reject_tx_invs) { |
3960 | 0 | LogDebug(BCLog::NET, "transaction (%s) inv sent in violation of protocol, %s\n", inv.hash.ToString(), pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3961 | 0 | pfrom.fDisconnect = true; |
3962 | 0 | return; |
3963 | 0 | } |
3964 | 0 | const GenTxid gtxid = ToGenTxid(inv); |
3965 | 0 | AddKnownTx(*peer, inv.hash); |
3966 | |
|
3967 | 0 | if (!m_chainman.IsInitialBlockDownload()) { |
3968 | 0 | const bool fAlreadyHave{m_txdownloadman.AddTxAnnouncement(pfrom.GetId(), gtxid, current_time)}; |
3969 | 0 | LogDebug(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3970 | 0 | } |
3971 | 0 | } else { |
3972 | 0 | LogDebug(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3973 | 0 | } |
3974 | 0 | } |
3975 | | |
3976 | 0 | if (best_block != nullptr) { |
3977 | | // If we haven't started initial headers-sync with this peer, then |
3978 | | // consider sending a getheaders now. On initial startup, there's a |
3979 | | // reliability vs bandwidth tradeoff, where we are only trying to do |
3980 | | // initial headers sync with one peer at a time, with a long |
3981 | | // timeout (at which point, if the sync hasn't completed, we will |
3982 | | // disconnect the peer and then choose another). In the meantime, |
3983 | | // as new blocks are found, we are willing to add one new peer per |
3984 | | // block to sync with as well, to sync quicker in the case where |
3985 | | // our initial peer is unresponsive (but less bandwidth than we'd |
3986 | | // use if we turned on sync with all peers). |
3987 | 0 | CNodeState& state{*Assert(State(pfrom.GetId()))}; Line | Count | Source | 106 | 0 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
3988 | 0 | if (state.fSyncStarted || (!peer->m_inv_triggered_getheaders_before_sync && *best_block != m_last_block_inv_triggering_headers_sync)) { |
3989 | 0 | if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer)) { |
3990 | 0 | LogDebug(BCLog::NET, "getheaders (%d) %s to peer=%d\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
3991 | 0 | m_chainman.m_best_header->nHeight, best_block->ToString(), |
3992 | 0 | pfrom.GetId()); |
3993 | 0 | } |
3994 | 0 | if (!state.fSyncStarted) { |
3995 | 0 | peer->m_inv_triggered_getheaders_before_sync = true; |
3996 | | // Update the last block hash that triggered a new headers |
3997 | | // sync, so that we don't turn on headers sync with more |
3998 | | // than 1 new peer every new block. |
3999 | 0 | m_last_block_inv_triggering_headers_sync = *best_block; |
4000 | 0 | } |
4001 | 0 | } |
4002 | 0 | } |
4003 | |
|
4004 | 0 | return; |
4005 | 0 | } |
4006 | | |
4007 | 5.68M | if (msg_type == NetMsgType::GETDATA) { |
4008 | 0 | std::vector<CInv> vInv; |
4009 | 0 | vRecv >> vInv; |
4010 | 0 | if (vInv.size() > MAX_INV_SZ) |
4011 | 0 | { |
4012 | 0 | Misbehaving(*peer, strprintf("getdata message size = %u", vInv.size())); Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
4013 | 0 | return; |
4014 | 0 | } |
4015 | | |
4016 | 0 | LogDebug(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4017 | |
|
4018 | 0 | if (vInv.size() > 0) { |
4019 | 0 | LogDebug(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4020 | 0 | } |
4021 | |
|
4022 | 0 | { |
4023 | 0 | LOCK(peer->m_getdata_requests_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4024 | 0 | peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end()); |
4025 | 0 | ProcessGetData(pfrom, *peer, interruptMsgProc); |
4026 | 0 | } |
4027 | |
|
4028 | 0 | return; |
4029 | 0 | } |
4030 | | |
4031 | 5.68M | if (msg_type == NetMsgType::GETBLOCKS) { |
4032 | 0 | CBlockLocator locator; |
4033 | 0 | uint256 hashStop; |
4034 | 0 | vRecv >> locator >> hashStop; |
4035 | |
|
4036 | 0 | if (locator.vHave.size() > MAX_LOCATOR_SZ) { |
4037 | 0 | LogDebug(BCLog::NET, "getblocks locator size %lld > %d, %s\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4038 | 0 | pfrom.fDisconnect = true; |
4039 | 0 | return; |
4040 | 0 | } |
4041 | | |
4042 | | // We might have announced the currently-being-connected tip using a |
4043 | | // compact block, which resulted in the peer sending a getblocks |
4044 | | // request, which we would otherwise respond to without the new block. |
4045 | | // To avoid this situation we simply verify that we are on our best |
4046 | | // known chain now. This is super overkill, but we handle it better |
4047 | | // for getheaders requests, and there are no known nodes which support |
4048 | | // compact blocks but still use getblocks to request blocks. |
4049 | 0 | { |
4050 | 0 | std::shared_ptr<const CBlock> a_recent_block; |
4051 | 0 | { |
4052 | 0 | LOCK(m_most_recent_block_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4053 | 0 | a_recent_block = m_most_recent_block; |
4054 | 0 | } |
4055 | 0 | BlockValidationState state; |
4056 | 0 | if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) { |
4057 | 0 | LogDebug(BCLog::NET, "failed to activate chain (%s)\n", state.ToString()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4058 | 0 | } |
4059 | 0 | } |
4060 | |
|
4061 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4062 | | |
4063 | | // Find the last block the caller has in the main chain |
4064 | 0 | const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator); |
4065 | | |
4066 | | // Send the rest of the chain |
4067 | 0 | if (pindex) |
4068 | 0 | pindex = m_chainman.ActiveChain().Next(pindex); |
4069 | 0 | int nLimit = 500; |
4070 | 0 | LogDebug(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4071 | 0 | for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) |
4072 | 0 | { |
4073 | 0 | if (pindex->GetBlockHash() == hashStop) |
4074 | 0 | { |
4075 | 0 | LogDebug(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4076 | 0 | break; |
4077 | 0 | } |
4078 | | // If pruning, don't inv blocks unless we have on disk and are likely to still have |
4079 | | // for some reasonable time window (1 hour) that block relay might require. |
4080 | 0 | const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing; |
4081 | 0 | if (m_chainman.m_blockman.IsPruneMode() && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave)) { |
4082 | 0 | LogDebug(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4083 | 0 | break; |
4084 | 0 | } |
4085 | 0 | WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash())); Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
4086 | 0 | if (--nLimit <= 0) { |
4087 | | // When this block is requested, we'll send an inv that'll |
4088 | | // trigger the peer to getblocks the next batch of inventory. |
4089 | 0 | LogDebug(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4090 | 0 | WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();}); Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
4091 | 0 | break; |
4092 | 0 | } |
4093 | 0 | } |
4094 | 0 | return; |
4095 | 0 | } |
4096 | | |
4097 | 5.68M | if (msg_type == NetMsgType::GETBLOCKTXN) { |
4098 | 0 | BlockTransactionsRequest req; |
4099 | 0 | vRecv >> req; |
4100 | |
|
4101 | 0 | std::shared_ptr<const CBlock> recent_block; |
4102 | 0 | { |
4103 | 0 | LOCK(m_most_recent_block_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4104 | 0 | if (m_most_recent_block_hash == req.blockhash) |
4105 | 0 | recent_block = m_most_recent_block; |
4106 | | // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion |
4107 | 0 | } |
4108 | 0 | if (recent_block) { |
4109 | 0 | SendBlockTransactions(pfrom, *peer, *recent_block, req); |
4110 | 0 | return; |
4111 | 0 | } |
4112 | | |
4113 | 0 | FlatFilePos block_pos{}; |
4114 | 0 | { |
4115 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4116 | |
|
4117 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash); |
4118 | 0 | if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) { |
4119 | 0 | LogDebug(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4120 | 0 | return; |
4121 | 0 | } |
4122 | | |
4123 | 0 | if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) { |
4124 | 0 | block_pos = pindex->GetBlockPos(); |
4125 | 0 | } |
4126 | 0 | } |
4127 | | |
4128 | 0 | if (!block_pos.IsNull()) { |
4129 | 0 | CBlock block; |
4130 | 0 | const bool ret{m_chainman.m_blockman.ReadBlock(block, block_pos, req.blockhash)}; |
4131 | | // If height is above MAX_BLOCKTXN_DEPTH then this block cannot get |
4132 | | // pruned after we release cs_main above, so this read should never fail. |
4133 | 0 | assert(ret); |
4134 | | |
4135 | 0 | SendBlockTransactions(pfrom, *peer, block, req); |
4136 | 0 | return; |
4137 | 0 | } |
4138 | | |
4139 | | // If an older block is requested (should never happen in practice, |
4140 | | // but can happen in tests) send a block response instead of a |
4141 | | // blocktxn response. Sending a full block response instead of a |
4142 | | // small blocktxn response is preferable in the case where a peer |
4143 | | // might maliciously send lots of getblocktxn requests to trigger |
4144 | | // expensive disk reads, because it will require the peer to |
4145 | | // actually receive all the data read from disk over the network. |
4146 | 0 | LogDebug(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4147 | 0 | CInv inv{MSG_WITNESS_BLOCK, req.blockhash}; |
4148 | 0 | WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv)); Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
4149 | | // The message processing loop will go around again (without pausing) and we'll respond then |
4150 | 0 | return; |
4151 | 0 | } |
4152 | | |
4153 | 5.68M | if (msg_type == NetMsgType::GETHEADERS) { |
4154 | 0 | CBlockLocator locator; |
4155 | 0 | uint256 hashStop; |
4156 | 0 | vRecv >> locator >> hashStop; |
4157 | |
|
4158 | 0 | if (locator.vHave.size() > MAX_LOCATOR_SZ) { |
4159 | 0 | LogDebug(BCLog::NET, "getheaders locator size %lld > %d, %s\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4160 | 0 | pfrom.fDisconnect = true; |
4161 | 0 | return; |
4162 | 0 | } |
4163 | | |
4164 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) { |
4165 | 0 | LogDebug(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4166 | 0 | return; |
4167 | 0 | } |
4168 | | |
4169 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4170 | | |
4171 | | // Don't serve headers from our active chain until our chainwork is at least |
4172 | | // the minimum chain work. This prevents us from starting a low-work headers |
4173 | | // sync that will inevitably be aborted by our peer. |
4174 | 0 | if (m_chainman.ActiveTip() == nullptr || |
4175 | 0 | (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && !pfrom.HasPermission(NetPermissionFlags::Download))) { |
4176 | 0 | LogDebug(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4177 | | // Just respond with an empty headers message, to tell the peer to |
4178 | | // go away but not treat us as unresponsive. |
4179 | 0 | MakeAndPushMessage(pfrom, NetMsgType::HEADERS, std::vector<CBlockHeader>()); |
4180 | 0 | return; |
4181 | 0 | } |
4182 | | |
4183 | 0 | CNodeState *nodestate = State(pfrom.GetId()); |
4184 | 0 | const CBlockIndex* pindex = nullptr; |
4185 | 0 | if (locator.IsNull()) |
4186 | 0 | { |
4187 | | // If locator is null, return the hashStop block |
4188 | 0 | pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop); |
4189 | 0 | if (!pindex) { |
4190 | 0 | return; |
4191 | 0 | } |
4192 | | |
4193 | 0 | if (!BlockRequestAllowed(pindex)) { |
4194 | 0 | LogDebug(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4195 | 0 | return; |
4196 | 0 | } |
4197 | 0 | } |
4198 | 0 | else |
4199 | 0 | { |
4200 | | // Find the last block the caller has in the main chain |
4201 | 0 | pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator); |
4202 | 0 | if (pindex) |
4203 | 0 | pindex = m_chainman.ActiveChain().Next(pindex); |
4204 | 0 | } |
4205 | | |
4206 | | // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end |
4207 | 0 | std::vector<CBlock> vHeaders; |
4208 | 0 | int nLimit = m_opts.max_headers_result; |
4209 | 0 | LogDebug(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4210 | 0 | for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) |
4211 | 0 | { |
4212 | 0 | vHeaders.emplace_back(pindex->GetBlockHeader()); |
4213 | 0 | if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) |
4214 | 0 | break; |
4215 | 0 | } |
4216 | | // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR |
4217 | | // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty |
4218 | | // headers message). In both cases it's safe to update |
4219 | | // pindexBestHeaderSent to be our tip. |
4220 | | // |
4221 | | // It is important that we simply reset the BestHeaderSent value here, |
4222 | | // and not max(BestHeaderSent, newHeaderSent). We might have announced |
4223 | | // the currently-being-connected tip using a compact block, which |
4224 | | // resulted in the peer sending a headers request, which we respond to |
4225 | | // without the new block. By resetting the BestHeaderSent, we ensure we |
4226 | | // will re-announce the new block via headers (or compact blocks again) |
4227 | | // in the SendMessages logic. |
4228 | 0 | nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip(); |
4229 | 0 | MakeAndPushMessage(pfrom, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders)); |
4230 | 0 | return; |
4231 | 0 | } |
4232 | | |
4233 | 5.68M | if (msg_type == NetMsgType::TX) { |
4234 | 1.21M | if (RejectIncomingTxs(pfrom)) { |
4235 | 28 | LogDebug(BCLog::NET, "transaction sent in violation of protocol, %s", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 28 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 28 | do { \ | 374 | 28 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 28 | } while (0) |
|
|
4236 | 28 | pfrom.fDisconnect = true; |
4237 | 28 | return; |
4238 | 28 | } |
4239 | | |
4240 | | // Stop processing the transaction early if we are still in IBD since we don't |
4241 | | // have enough information to validate it yet. Sending unsolicited transactions |
4242 | | // is not considered a protocol violation, so don't punish the peer. |
4243 | 1.21M | if (m_chainman.IsInitialBlockDownload()) return25.8k ; |
4244 | | |
4245 | 1.18M | CTransactionRef ptx; |
4246 | 1.18M | vRecv >> TX_WITH_WITNESS(ptx); |
4247 | | |
4248 | 1.18M | const Txid& txid = ptx->GetHash(); |
4249 | 1.18M | const Wtxid& wtxid = ptx->GetWitnessHash(); |
4250 | | |
4251 | 1.18M | const uint256& hash = peer->m_wtxid_relay ? wtxid.ToUint256()0 : txid.ToUint256(); |
4252 | 1.18M | AddKnownTx(*peer, hash); |
4253 | | |
4254 | 1.18M | LOCK2(cs_main, m_tx_download_mutex); Line | Count | Source | 261 | 1.18M | UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \ | 262 | 1.18M | UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__) |
|
4255 | | |
4256 | 1.18M | const auto& [should_validate, package_to_validate] = m_txdownloadman.ReceivedTx(pfrom.GetId(), ptx); |
4257 | 1.18M | if (!should_validate) { |
4258 | 734k | if (pfrom.HasPermission(NetPermissionFlags::ForceRelay)) { |
4259 | | // Always relay transactions received from peers with forcerelay |
4260 | | // permission, even if they were already in the mempool, allowing |
4261 | | // the node to function as a gateway for nodes hidden behind it. |
4262 | 640k | if (!m_mempool.exists(txid)) { |
4263 | 139k | LogPrintf("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n", Line | Count | Source | 361 | 139k | #define LogPrintf(...) LogInfo(__VA_ARGS__) Line | Count | Source | 356 | 139k | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 139k | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
|
4264 | 139k | txid.ToString(), wtxid.ToString(), pfrom.GetId()); |
4265 | 501k | } else { |
4266 | 501k | LogPrintf("Force relaying tx %s (wtxid=%s) from peer=%d\n", Line | Count | Source | 361 | 501k | #define LogPrintf(...) LogInfo(__VA_ARGS__) Line | Count | Source | 356 | 501k | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 501k | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
|
4267 | 501k | txid.ToString(), wtxid.ToString(), pfrom.GetId()); |
4268 | 501k | RelayTransaction(txid, wtxid); |
4269 | 501k | } |
4270 | 640k | } |
4271 | | |
4272 | 734k | if (package_to_validate) { |
4273 | 0 | const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)}; |
4274 | 0 | LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(), Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4275 | 0 | package_result.m_state.IsValid() ? "package accepted" : "package rejected"); |
4276 | 0 | ProcessPackageResult(package_to_validate.value(), package_result); |
4277 | 0 | } |
4278 | 734k | return; |
4279 | 734k | } |
4280 | | |
4281 | | // ReceivedTx should not be telling us to validate the tx and a package. |
4282 | 454k | Assume(!package_to_validate.has_value()); Line | Count | Source | 118 | 454k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
4283 | | |
4284 | 454k | const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx); |
4285 | 454k | const TxValidationState& state = result.m_state; |
4286 | | |
4287 | 454k | if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) { |
4288 | 258k | ProcessValidTx(pfrom.GetId(), ptx, result.m_replaced_transactions); |
4289 | 258k | pfrom.m_last_tx_time = GetTime<std::chrono::seconds>(); |
4290 | 258k | } |
4291 | 454k | if (state.IsInvalid()) { |
4292 | 195k | if (auto package_to_validate{ProcessInvalidTx(pfrom.GetId(), ptx, state, /*first_time_failure=*/true)}) { |
4293 | 0 | const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)}; |
4294 | 0 | LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(), Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4295 | 0 | package_result.m_state.IsValid() ? "package accepted" : "package rejected"); |
4296 | 0 | ProcessPackageResult(package_to_validate.value(), package_result); |
4297 | 0 | } |
4298 | 195k | } |
4299 | | |
4300 | 454k | return; |
4301 | 1.18M | } |
4302 | | |
4303 | 4.46M | if (msg_type == NetMsgType::CMPCTBLOCK) |
4304 | 2.47M | { |
4305 | | // Ignore cmpctblock received while importing |
4306 | 2.47M | if (m_chainman.m_blockman.LoadingBlocks()) { |
4307 | 0 | LogDebug(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4308 | 0 | return; |
4309 | 0 | } |
4310 | | |
4311 | 2.47M | CBlockHeaderAndShortTxIDs cmpctblock; |
4312 | 2.47M | vRecv >> cmpctblock; |
4313 | | |
4314 | 2.47M | bool received_new_header = false; |
4315 | 2.47M | const auto blockhash = cmpctblock.header.GetHash(); |
4316 | | |
4317 | 2.47M | { |
4318 | 2.47M | LOCK(cs_main); Line | Count | Source | 259 | 2.47M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 2.47M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 2.47M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 2.47M | #define PASTE(x, y) x ## y |
|
|
|
|
4319 | | |
4320 | 2.47M | const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock); |
4321 | 2.47M | if (!prev_block) { |
4322 | | // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers |
4323 | 14.1k | if (!m_chainman.IsInitialBlockDownload()) { |
4324 | 8.75k | MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer); |
4325 | 8.75k | } |
4326 | 14.1k | return; |
4327 | 2.45M | } else if (prev_block->nChainWork + CalculateClaimedHeadersWork({{cmpctblock.header}}) < GetAntiDoSWorkThreshold()) { |
4328 | | // If we get a low-work header in a compact block, we can ignore it. |
4329 | 0 | LogDebug(BCLog::NET, "Ignoring low-work compact block from peer %d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4330 | 0 | return; |
4331 | 0 | } |
4332 | | |
4333 | 2.45M | if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) { |
4334 | 968k | received_new_header = true; |
4335 | 968k | } |
4336 | 2.45M | } |
4337 | | |
4338 | 0 | const CBlockIndex *pindex = nullptr; |
4339 | 2.45M | BlockValidationState state; |
4340 | 2.45M | if (!m_chainman.ProcessNewBlockHeaders({{cmpctblock.header}}, /*min_pow_checked=*/true, state, &pindex)) { |
4341 | 1.18M | if (state.IsInvalid()) { |
4342 | 1.18M | MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block=*/true, "invalid header via cmpctblock"); |
4343 | 1.18M | return; |
4344 | 1.18M | } |
4345 | 1.18M | } |
4346 | | |
4347 | | // If AcceptBlockHeader returned true, it set pindex |
4348 | 1.27M | Assert(pindex); Line | Count | Source | 106 | 1.27M | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
4349 | 1.27M | if (received_new_header) { |
4350 | 286k | LogBlockHeader(*pindex, pfrom, /*via_compact_block=*/true); |
4351 | 286k | } |
4352 | | |
4353 | 1.27M | bool fProcessBLOCKTXN = false; |
4354 | | |
4355 | | // If we end up treating this as a plain headers message, call that as well |
4356 | | // without cs_main. |
4357 | 1.27M | bool fRevertToHeaderProcessing = false; |
4358 | | |
4359 | | // Keep a CBlock for "optimistic" compactblock reconstructions (see |
4360 | | // below) |
4361 | 1.27M | std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); |
4362 | 1.27M | bool fBlockReconstructed = false; |
4363 | | |
4364 | 1.27M | { |
4365 | 1.27M | LOCK(cs_main); Line | Count | Source | 259 | 1.27M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 1.27M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 1.27M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 1.27M | #define PASTE(x, y) x ## y |
|
|
|
|
4366 | 1.27M | UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash()); |
4367 | | |
4368 | 1.27M | CNodeState *nodestate = State(pfrom.GetId()); |
4369 | | |
4370 | | // If this was a new header with more work than our tip, update the |
4371 | | // peer's last block announcement time |
4372 | 1.27M | if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork286k ) { |
4373 | 273k | nodestate->m_last_block_announcement = GetTime(); |
4374 | 273k | } |
4375 | | |
4376 | 1.27M | if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here |
4377 | 69.2k | return; |
4378 | | |
4379 | 1.20M | auto range_flight = mapBlocksInFlight.equal_range(pindex->GetBlockHash()); |
4380 | 1.20M | size_t already_in_flight = std::distance(range_flight.first, range_flight.second); |
4381 | 1.20M | bool requested_block_from_this_peer{false}; |
4382 | | |
4383 | | // Multimap ensures ordering of outstanding requests. It's either empty or first in line. |
4384 | 1.20M | bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId())705k ; |
4385 | | |
4386 | 1.50M | while (range_flight.first != range_flight.second) { |
4387 | 723k | if (range_flight.first->second.first == pfrom.GetId()) { |
4388 | 423k | requested_block_from_this_peer = true; |
4389 | 423k | break; |
4390 | 423k | } |
4391 | 299k | range_flight.first++; |
4392 | 299k | } |
4393 | | |
4394 | 1.20M | if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better |
4395 | 1.20M | pindex->nTx != 0939k ) { // We had this block at some point, but pruned it |
4396 | 262k | if (requested_block_from_this_peer) { |
4397 | | // We requested this block for some reason, but our mempool will probably be useless |
4398 | | // so we just grab the block via normal getdata |
4399 | 160k | std::vector<CInv> vInv(1); |
4400 | 160k | vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); |
4401 | 160k | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); |
4402 | 160k | } |
4403 | 262k | return; |
4404 | 262k | } |
4405 | | |
4406 | | // If we're not close to tip yet, give up and let parallel block fetch work its magic |
4407 | 939k | if (!already_in_flight && !CanDirectFetch()448k ) { |
4408 | 137k | return; |
4409 | 137k | } |
4410 | | |
4411 | | // We want to be a bit conservative just to be extra careful about DoS |
4412 | | // possibilities in compact block processing... |
4413 | 802k | if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) { |
4414 | 789k | if ((already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK && nodestate->vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || |
4415 | 789k | requested_block_from_this_peer44.5k ) { |
4416 | 750k | std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr; |
4417 | 750k | if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) { |
4418 | 260k | if (!(*queuedBlockIt)->partialBlock) |
4419 | 3.86k | (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool)); |
4420 | 256k | else { |
4421 | | // The block was already in flight using compact blocks from the same peer |
4422 | 256k | LogDebug(BCLog::NET, "Peer sent us compact block we were already syncing!\n"); Line | Count | Source | 381 | 256k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 256k | do { \ | 374 | 256k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 256k | } while (0) |
|
|
4423 | 256k | return; |
4424 | 256k | } |
4425 | 260k | } |
4426 | | |
4427 | 493k | PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock; |
4428 | 493k | ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact); |
4429 | 493k | if (status == READ_STATUS_INVALID) { |
4430 | 0 | RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect |
4431 | 0 | Misbehaving(*peer, "invalid compact block"); |
4432 | 0 | return; |
4433 | 493k | } else if (status == READ_STATUS_FAILED) { |
4434 | 7.64k | if (first_in_flight) { |
4435 | | // Duplicate txindexes, the block is now in-flight, so just request it |
4436 | 1.95k | std::vector<CInv> vInv(1); |
4437 | 1.95k | vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); |
4438 | 1.95k | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); |
4439 | 5.68k | } else { |
4440 | | // Give up for this peer and wait for other peer(s) |
4441 | 5.68k | RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); |
4442 | 5.68k | } |
4443 | 7.64k | return; |
4444 | 7.64k | } |
4445 | | |
4446 | 486k | BlockTransactionsRequest req; |
4447 | 1.87M | for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++1.39M ) { |
4448 | 1.39M | if (!partialBlock.IsTxAvailable(i)) |
4449 | 298k | req.indexes.push_back(i); |
4450 | 1.39M | } |
4451 | 486k | if (req.indexes.empty()) { |
4452 | 192k | fProcessBLOCKTXN = true; |
4453 | 293k | } else if (first_in_flight) { |
4454 | | // We will try to round-trip any compact blocks we get on failure, |
4455 | | // as long as it's first... |
4456 | 102k | req.blockhash = pindex->GetBlockHash(); |
4457 | 102k | MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req); |
4458 | 191k | } else if (pfrom.m_bip152_highbandwidth_to && |
4459 | 191k | (1.40k !pfrom.IsInboundConn()1.40k || |
4460 | 1.40k | IsBlockRequestedFromOutbound(blockhash)1.28k || |
4461 | 1.40k | already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK - 1217 )) { |
4462 | | // ... or it's a hb relay peer and: |
4463 | | // - peer is outbound, or |
4464 | | // - we already have an outbound attempt in flight(so we'll take what we can get), or |
4465 | | // - it's not the final parallel download slot (which we may reserve for first outbound) |
4466 | 1.40k | req.blockhash = pindex->GetBlockHash(); |
4467 | 1.40k | MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req); |
4468 | 190k | } else { |
4469 | | // Give up for this peer and wait for other peer(s) |
4470 | 190k | RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); |
4471 | 190k | } |
4472 | 486k | } else { |
4473 | | // This block is either already in flight from a different |
4474 | | // peer, or this peer has too many blocks outstanding to |
4475 | | // download from. |
4476 | | // Optimistically try to reconstruct anyway since we might be |
4477 | | // able to without any round trips. |
4478 | 38.9k | PartiallyDownloadedBlock tempBlock(&m_mempool); |
4479 | 38.9k | ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact); |
4480 | 38.9k | if (status != READ_STATUS_OK) { |
4481 | | // TODO: don't ignore failures |
4482 | 2.40k | return; |
4483 | 2.40k | } |
4484 | 36.5k | std::vector<CTransactionRef> dummy; |
4485 | 36.5k | const CBlockIndex* prev_block{Assume(m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock))}; Line | Count | Source | 118 | 36.5k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
4486 | 36.5k | status = tempBlock.FillBlock(*pblock, dummy, |
4487 | 36.5k | /*segwit_active=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT)); |
4488 | 36.5k | if (status == READ_STATUS_OK) { |
4489 | 3.44k | fBlockReconstructed = true; |
4490 | 3.44k | } |
4491 | 36.5k | } |
4492 | 789k | } else { |
4493 | 13.1k | if (requested_block_from_this_peer) { |
4494 | | // We requested this block, but its far into the future, so our |
4495 | | // mempool will probably be useless - request the block normally |
4496 | 2.92k | std::vector<CInv> vInv(1); |
4497 | 2.92k | vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); |
4498 | 2.92k | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); |
4499 | 2.92k | return; |
4500 | 10.1k | } else { |
4501 | | // If this was an announce-cmpctblock, we want the same treatment as a header message |
4502 | 10.1k | fRevertToHeaderProcessing = true; |
4503 | 10.1k | } |
4504 | 13.1k | } |
4505 | 802k | } // cs_main |
4506 | | |
4507 | 532k | if (fProcessBLOCKTXN) { |
4508 | 192k | BlockTransactions txn; |
4509 | 192k | txn.blockhash = blockhash; |
4510 | 192k | return ProcessCompactBlockTxns(pfrom, *peer, txn); |
4511 | 192k | } |
4512 | | |
4513 | 340k | if (fRevertToHeaderProcessing) { |
4514 | | // Headers received from HB compact block peers are permitted to be |
4515 | | // relayed before full validation (see BIP 152), so we don't want to disconnect |
4516 | | // the peer if the header turns out to be for an invalid block. |
4517 | | // Note that if a peer tries to build on an invalid chain, that |
4518 | | // will be detected and the peer will be disconnected/discouraged. |
4519 | 10.1k | return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true); |
4520 | 10.1k | } |
4521 | | |
4522 | 330k | if (fBlockReconstructed) { |
4523 | | // If we got here, we were able to optimistically reconstruct a |
4524 | | // block that is in flight from some other peer. |
4525 | 3.44k | { |
4526 | 3.44k | LOCK(cs_main); Line | Count | Source | 259 | 3.44k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 3.44k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 3.44k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 3.44k | #define PASTE(x, y) x ## y |
|
|
|
|
4527 | 3.44k | mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false)); |
4528 | 3.44k | } |
4529 | | // Setting force_processing to true means that we bypass some of |
4530 | | // our anti-DoS protections in AcceptBlock, which filters |
4531 | | // unrequested blocks that might be trying to waste our resources |
4532 | | // (eg disk space). Because we only try to reconstruct blocks when |
4533 | | // we're close to caught up (via the CanDirectFetch() requirement |
4534 | | // above, combined with the behavior of not requesting blocks until |
4535 | | // we have a chain with at least the minimum chain work), and we ignore |
4536 | | // compact blocks with less work than our tip, it is safe to treat |
4537 | | // reconstructed compact blocks as having been requested. |
4538 | 3.44k | ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true); |
4539 | 3.44k | LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid() Line | Count | Source | 259 | 3.44k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 3.44k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 3.44k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 3.44k | #define PASTE(x, y) x ## y |
|
|
|
|
4540 | 3.44k | if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) { |
4541 | | // Clear download state for this block, which is in |
4542 | | // process from some other peer. We do this after calling |
4543 | | // ProcessNewBlock so that a malleated cmpctblock announcement |
4544 | | // can't be used to interfere with block relay. |
4545 | 991 | RemoveBlockRequest(pblock->GetHash(), std::nullopt); |
4546 | 991 | } |
4547 | 3.44k | } |
4548 | 330k | return; |
4549 | 340k | } |
4550 | | |
4551 | 1.99M | if (msg_type == NetMsgType::BLOCKTXN) |
4552 | 175k | { |
4553 | | // Ignore blocktxn received while importing |
4554 | 175k | if (m_chainman.m_blockman.LoadingBlocks()) { |
4555 | 0 | LogDebug(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4556 | 0 | return; |
4557 | 0 | } |
4558 | | |
4559 | 175k | BlockTransactions resp; |
4560 | 175k | vRecv >> resp; |
4561 | | |
4562 | 175k | return ProcessCompactBlockTxns(pfrom, *peer, resp); |
4563 | 175k | } |
4564 | | |
4565 | 1.82M | if (msg_type == NetMsgType::HEADERS) |
4566 | 1.82M | { |
4567 | | // Ignore headers received while importing |
4568 | 1.82M | if (m_chainman.m_blockman.LoadingBlocks()) { |
4569 | 0 | LogDebug(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4570 | 0 | return; |
4571 | 0 | } |
4572 | | |
4573 | 1.82M | std::vector<CBlockHeader> headers; |
4574 | | |
4575 | | // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. |
4576 | 1.82M | unsigned int nCount = ReadCompactSize(vRecv); |
4577 | 1.82M | if (nCount > m_opts.max_headers_result) { |
4578 | 0 | Misbehaving(*peer, strprintf("headers message size = %u", nCount)); Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
4579 | 0 | return; |
4580 | 0 | } |
4581 | 1.82M | headers.resize(nCount); |
4582 | 3.64M | for (unsigned int n = 0; n < nCount; n++1.82M ) { |
4583 | 1.82M | vRecv >> headers[n]; |
4584 | 1.82M | ReadCompactSize(vRecv); // ignore tx count; assume it is 0. |
4585 | 1.82M | } |
4586 | | |
4587 | 1.82M | ProcessHeadersMessage(pfrom, *peer, std::move(headers), /*via_compact_block=*/false); |
4588 | | |
4589 | | // Check if the headers presync progress needs to be reported to validation. |
4590 | | // This needs to be done without holding the m_headers_presync_mutex lock. |
4591 | 1.82M | if (m_headers_presync_should_signal.exchange(false)) { |
4592 | 0 | HeadersPresyncStats stats; |
4593 | 0 | { |
4594 | 0 | LOCK(m_headers_presync_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4595 | 0 | auto it = m_headers_presync_stats.find(m_headers_presync_bestpeer); |
4596 | 0 | if (it != m_headers_presync_stats.end()) stats = it->second; |
4597 | 0 | } |
4598 | 0 | if (stats.second) { |
4599 | 0 | m_chainman.ReportHeadersPresync(stats.first, stats.second->first, stats.second->second); |
4600 | 0 | } |
4601 | 0 | } |
4602 | | |
4603 | 1.82M | return; |
4604 | 1.82M | } |
4605 | | |
4606 | 0 | if (msg_type == NetMsgType::BLOCK) |
4607 | 0 | { |
4608 | | // Ignore block received while importing |
4609 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) { |
4610 | 0 | LogDebug(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4611 | 0 | return; |
4612 | 0 | } |
4613 | | |
4614 | 0 | std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); |
4615 | 0 | vRecv >> TX_WITH_WITNESS(*pblock); |
4616 | |
|
4617 | 0 | LogDebug(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4618 | |
|
4619 | 0 | const CBlockIndex* prev_block{WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock))}; Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
4620 | | |
4621 | | // Check for possible mutation if it connects to something we know so we can check for DEPLOYMENT_SEGWIT being active |
4622 | 0 | if (prev_block && IsBlockMutated(/*block=*/*pblock, |
4623 | 0 | /*check_witness_root=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT))) { |
4624 | 0 | LogDebug(BCLog::NET, "Received mutated block from peer=%d\n", peer->m_id); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4625 | 0 | Misbehaving(*peer, "mutated block"); |
4626 | 0 | WITH_LOCK(cs_main, RemoveBlockRequest(pblock->GetHash(), peer->m_id)); Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
4627 | 0 | return; |
4628 | 0 | } |
4629 | | |
4630 | 0 | bool forceProcessing = false; |
4631 | 0 | const uint256 hash(pblock->GetHash()); |
4632 | 0 | bool min_pow_checked = false; |
4633 | 0 | { |
4634 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4635 | | // Always process the block if we requested it, since we may |
4636 | | // need it even when it's not a candidate for a new best tip. |
4637 | 0 | forceProcessing = IsBlockRequested(hash); |
4638 | 0 | RemoveBlockRequest(hash, pfrom.GetId()); |
4639 | | // mapBlockSource is only used for punishing peers and setting |
4640 | | // which peers send us compact blocks, so the race between here and |
4641 | | // cs_main in ProcessNewBlock is fine. |
4642 | 0 | mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true)); |
4643 | | |
4644 | | // Check claimed work on this block against our anti-dos thresholds. |
4645 | 0 | if (prev_block && prev_block->nChainWork + CalculateClaimedHeadersWork({{pblock->GetBlockHeader()}}) >= GetAntiDoSWorkThreshold()) { |
4646 | 0 | min_pow_checked = true; |
4647 | 0 | } |
4648 | 0 | } |
4649 | 0 | ProcessBlock(pfrom, pblock, forceProcessing, min_pow_checked); |
4650 | 0 | return; |
4651 | 0 | } |
4652 | | |
4653 | 0 | if (msg_type == NetMsgType::GETADDR) { |
4654 | | // This asymmetric behavior for inbound and outbound connections was introduced |
4655 | | // to prevent a fingerprinting attack: an attacker can send specific fake addresses |
4656 | | // to users' AddrMan and later request them by sending getaddr messages. |
4657 | | // Making nodes which are behind NAT and can only make outgoing connections ignore |
4658 | | // the getaddr message mitigates the attack. |
4659 | 0 | if (!pfrom.IsInboundConn()) { |
4660 | 0 | LogDebug(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4661 | 0 | return; |
4662 | 0 | } |
4663 | | |
4664 | | // Since this must be an inbound connection, SetupAddressRelay will |
4665 | | // never fail. |
4666 | 0 | Assume(SetupAddressRelay(pfrom, *peer)); Line | Count | Source | 118 | 0 | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
4667 | | |
4668 | | // Only send one GetAddr response per connection to reduce resource waste |
4669 | | // and discourage addr stamping of INV announcements. |
4670 | 0 | if (peer->m_getaddr_recvd) { |
4671 | 0 | LogDebug(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4672 | 0 | return; |
4673 | 0 | } |
4674 | 0 | peer->m_getaddr_recvd = true; |
4675 | |
|
4676 | 0 | peer->m_addrs_to_send.clear(); |
4677 | 0 | std::vector<CAddress> vAddr; |
4678 | 0 | if (pfrom.HasPermission(NetPermissionFlags::Addr)) { |
4679 | 0 | vAddr = m_connman.GetAddressesUnsafe(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /*network=*/std::nullopt); |
4680 | 0 | } else { |
4681 | 0 | vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND); |
4682 | 0 | } |
4683 | 0 | for (const CAddress &addr : vAddr) { |
4684 | 0 | PushAddress(*peer, addr); |
4685 | 0 | } |
4686 | 0 | return; |
4687 | 0 | } |
4688 | | |
4689 | 0 | if (msg_type == NetMsgType::MEMPOOL) { |
4690 | | // Only process received mempool messages if we advertise NODE_BLOOM |
4691 | | // or if the peer has mempool permissions. |
4692 | 0 | if (!(peer->m_our_services & NODE_BLOOM) && !pfrom.HasPermission(NetPermissionFlags::Mempool)) |
4693 | 0 | { |
4694 | 0 | if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) |
4695 | 0 | { |
4696 | 0 | LogDebug(BCLog::NET, "mempool request with bloom filters disabled, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4697 | 0 | pfrom.fDisconnect = true; |
4698 | 0 | } |
4699 | 0 | return; |
4700 | 0 | } |
4701 | | |
4702 | 0 | if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool)) |
4703 | 0 | { |
4704 | 0 | if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) |
4705 | 0 | { |
4706 | 0 | LogDebug(BCLog::NET, "mempool request with bandwidth limit reached, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4707 | 0 | pfrom.fDisconnect = true; |
4708 | 0 | } |
4709 | 0 | return; |
4710 | 0 | } |
4711 | | |
4712 | 0 | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { |
4713 | 0 | LOCK(tx_relay->m_tx_inventory_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4714 | 0 | tx_relay->m_send_mempool = true; |
4715 | 0 | } |
4716 | 0 | return; |
4717 | 0 | } |
4718 | | |
4719 | 0 | if (msg_type == NetMsgType::PING) { |
4720 | 0 | if (pfrom.GetCommonVersion() > BIP0031_VERSION) { |
4721 | 0 | uint64_t nonce = 0; |
4722 | 0 | vRecv >> nonce; |
4723 | | // Echo the message back with the nonce. This allows for two useful features: |
4724 | | // |
4725 | | // 1) A remote node can quickly check if the connection is operational |
4726 | | // 2) Remote nodes can measure the latency of the network thread. If this node |
4727 | | // is overloaded it won't respond to pings quickly and the remote node can |
4728 | | // avoid sending us more work, like chain download requests. |
4729 | | // |
4730 | | // The nonce stops the remote getting confused between different pings: without |
4731 | | // it, if the remote node sends a ping once per second and this node takes 5 |
4732 | | // seconds to respond to each, the 5th ping the remote sends would appear to |
4733 | | // return very quickly. |
4734 | 0 | MakeAndPushMessage(pfrom, NetMsgType::PONG, nonce); |
4735 | 0 | } |
4736 | 0 | return; |
4737 | 0 | } |
4738 | | |
4739 | 0 | if (msg_type == NetMsgType::PONG) { |
4740 | 0 | const auto ping_end = time_received; |
4741 | 0 | uint64_t nonce = 0; |
4742 | 0 | size_t nAvail = vRecv.in_avail(); |
4743 | 0 | bool bPingFinished = false; |
4744 | 0 | std::string sProblem; |
4745 | |
|
4746 | 0 | if (nAvail >= sizeof(nonce)) { |
4747 | 0 | vRecv >> nonce; |
4748 | | |
4749 | | // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) |
4750 | 0 | if (peer->m_ping_nonce_sent != 0) { |
4751 | 0 | if (nonce == peer->m_ping_nonce_sent) { |
4752 | | // Matching pong received, this ping is no longer outstanding |
4753 | 0 | bPingFinished = true; |
4754 | 0 | const auto ping_time = ping_end - peer->m_ping_start.load(); |
4755 | 0 | if (ping_time.count() >= 0) { |
4756 | | // Let connman know about this successful ping-pong |
4757 | 0 | pfrom.PongReceived(ping_time); |
4758 | 0 | } else { |
4759 | | // This should never happen |
4760 | 0 | sProblem = "Timing mishap"; |
4761 | 0 | } |
4762 | 0 | } else { |
4763 | | // Nonce mismatches are normal when pings are overlapping |
4764 | 0 | sProblem = "Nonce mismatch"; |
4765 | 0 | if (nonce == 0) { |
4766 | | // This is most likely a bug in another implementation somewhere; cancel this ping |
4767 | 0 | bPingFinished = true; |
4768 | 0 | sProblem = "Nonce zero"; |
4769 | 0 | } |
4770 | 0 | } |
4771 | 0 | } else { |
4772 | 0 | sProblem = "Unsolicited pong without ping"; |
4773 | 0 | } |
4774 | 0 | } else { |
4775 | | // This is most likely a bug in another implementation somewhere; cancel this ping |
4776 | 0 | bPingFinished = true; |
4777 | 0 | sProblem = "Short payload"; |
4778 | 0 | } |
4779 | |
|
4780 | 0 | if (!(sProblem.empty())) { |
4781 | 0 | LogDebug(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4782 | 0 | pfrom.GetId(), |
4783 | 0 | sProblem, |
4784 | 0 | peer->m_ping_nonce_sent, |
4785 | 0 | nonce, |
4786 | 0 | nAvail); |
4787 | 0 | } |
4788 | 0 | if (bPingFinished) { |
4789 | 0 | peer->m_ping_nonce_sent = 0; |
4790 | 0 | } |
4791 | 0 | return; |
4792 | 0 | } |
4793 | | |
4794 | 0 | if (msg_type == NetMsgType::FILTERLOAD) { |
4795 | 0 | if (!(peer->m_our_services & NODE_BLOOM)) { |
4796 | 0 | LogDebug(BCLog::NET, "filterload received despite not offering bloom services, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4797 | 0 | pfrom.fDisconnect = true; |
4798 | 0 | return; |
4799 | 0 | } |
4800 | 0 | CBloomFilter filter; |
4801 | 0 | vRecv >> filter; |
4802 | |
|
4803 | 0 | if (!filter.IsWithinSizeConstraints()) |
4804 | 0 | { |
4805 | | // There is no excuse for sending a too-large filter |
4806 | 0 | Misbehaving(*peer, "too-large bloom filter"); |
4807 | 0 | } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { |
4808 | 0 | { |
4809 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4810 | 0 | tx_relay->m_bloom_filter.reset(new CBloomFilter(filter)); |
4811 | 0 | tx_relay->m_relay_txs = true; |
4812 | 0 | } |
4813 | 0 | pfrom.m_bloom_filter_loaded = true; |
4814 | 0 | pfrom.m_relays_txs = true; |
4815 | 0 | } |
4816 | 0 | return; |
4817 | 0 | } |
4818 | | |
4819 | 0 | if (msg_type == NetMsgType::FILTERADD) { |
4820 | 0 | if (!(peer->m_our_services & NODE_BLOOM)) { |
4821 | 0 | LogDebug(BCLog::NET, "filteradd received despite not offering bloom services, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4822 | 0 | pfrom.fDisconnect = true; |
4823 | 0 | return; |
4824 | 0 | } |
4825 | 0 | std::vector<unsigned char> vData; |
4826 | 0 | vRecv >> vData; |
4827 | | |
4828 | | // Nodes must NEVER send a data item > MAX_SCRIPT_ELEMENT_SIZE bytes (the max size for a script data object, |
4829 | | // and thus, the maximum size any matched object can have) in a filteradd message |
4830 | 0 | bool bad = false; |
4831 | 0 | if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) { |
4832 | 0 | bad = true; |
4833 | 0 | } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { |
4834 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4835 | 0 | if (tx_relay->m_bloom_filter) { |
4836 | 0 | tx_relay->m_bloom_filter->insert(vData); |
4837 | 0 | } else { |
4838 | 0 | bad = true; |
4839 | 0 | } |
4840 | 0 | } |
4841 | 0 | if (bad) { |
4842 | 0 | Misbehaving(*peer, "bad filteradd message"); |
4843 | 0 | } |
4844 | 0 | return; |
4845 | 0 | } |
4846 | | |
4847 | 0 | if (msg_type == NetMsgType::FILTERCLEAR) { |
4848 | 0 | if (!(peer->m_our_services & NODE_BLOOM)) { |
4849 | 0 | LogDebug(BCLog::NET, "filterclear received despite not offering bloom services, %s\n", pfrom.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4850 | 0 | pfrom.fDisconnect = true; |
4851 | 0 | return; |
4852 | 0 | } |
4853 | 0 | auto tx_relay = peer->GetTxRelay(); |
4854 | 0 | if (!tx_relay) return; |
4855 | | |
4856 | 0 | { |
4857 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4858 | 0 | tx_relay->m_bloom_filter = nullptr; |
4859 | 0 | tx_relay->m_relay_txs = true; |
4860 | 0 | } |
4861 | 0 | pfrom.m_bloom_filter_loaded = false; |
4862 | 0 | pfrom.m_relays_txs = true; |
4863 | 0 | return; |
4864 | 0 | } |
4865 | | |
4866 | 0 | if (msg_type == NetMsgType::FEEFILTER) { |
4867 | 0 | CAmount newFeeFilter = 0; |
4868 | 0 | vRecv >> newFeeFilter; |
4869 | 0 | if (MoneyRange(newFeeFilter)) { |
4870 | 0 | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { |
4871 | 0 | tx_relay->m_fee_filter_received = newFeeFilter; |
4872 | 0 | } |
4873 | 0 | LogDebug(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4874 | 0 | } |
4875 | 0 | return; |
4876 | 0 | } |
4877 | | |
4878 | 0 | if (msg_type == NetMsgType::GETCFILTERS) { |
4879 | 0 | ProcessGetCFilters(pfrom, *peer, vRecv); |
4880 | 0 | return; |
4881 | 0 | } |
4882 | | |
4883 | 0 | if (msg_type == NetMsgType::GETCFHEADERS) { |
4884 | 0 | ProcessGetCFHeaders(pfrom, *peer, vRecv); |
4885 | 0 | return; |
4886 | 0 | } |
4887 | | |
4888 | 0 | if (msg_type == NetMsgType::GETCFCHECKPT) { |
4889 | 0 | ProcessGetCFCheckPt(pfrom, *peer, vRecv); |
4890 | 0 | return; |
4891 | 0 | } |
4892 | | |
4893 | 0 | if (msg_type == NetMsgType::NOTFOUND) { |
4894 | 0 | std::vector<CInv> vInv; |
4895 | 0 | vRecv >> vInv; |
4896 | 0 | std::vector<GenTxid> tx_invs; |
4897 | 0 | if (vInv.size() <= node::MAX_PEER_TX_ANNOUNCEMENTS + MAX_BLOCKS_IN_TRANSIT_PER_PEER) { |
4898 | 0 | for (CInv &inv : vInv) { |
4899 | 0 | if (inv.IsGenTxMsg()) { |
4900 | 0 | tx_invs.emplace_back(ToGenTxid(inv)); |
4901 | 0 | } |
4902 | 0 | } |
4903 | 0 | } |
4904 | 0 | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
4905 | 0 | m_txdownloadman.ReceivedNotFound(pfrom.GetId(), tx_invs); |
4906 | 0 | return; |
4907 | 0 | } |
4908 | | |
4909 | | // Ignore unknown commands for extensibility |
4910 | 0 | LogDebug(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
4911 | 0 | return; |
4912 | 0 | } |
4913 | | |
4914 | | bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer) |
4915 | 6.59M | { |
4916 | 6.59M | { |
4917 | 6.59M | LOCK(peer.m_misbehavior_mutex); Line | Count | Source | 259 | 6.59M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 6.59M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 6.59M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 6.59M | #define PASTE(x, y) x ## y |
|
|
|
|
4918 | | |
4919 | | // There's nothing to do if the m_should_discourage flag isn't set |
4920 | 6.59M | if (!peer.m_should_discourage) return false5.07M ; |
4921 | | |
4922 | 1.52M | peer.m_should_discourage = false; |
4923 | 1.52M | } // peer.m_misbehavior_mutex |
4924 | | |
4925 | 1.52M | if (pnode.HasPermission(NetPermissionFlags::NoBan)) { |
4926 | | // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission |
4927 | 872k | LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id); Line | Count | Source | 361 | 872k | #define LogPrintf(...) LogInfo(__VA_ARGS__) Line | Count | Source | 356 | 872k | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 872k | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
|
4928 | 872k | return false; |
4929 | 872k | } |
4930 | | |
4931 | 650k | if (pnode.IsManualConn()) { |
4932 | | // We never disconnect or discourage manual peers for bad behavior |
4933 | 600k | LogPrintf("Warning: not punishing manually connected peer %d!\n", peer.m_id); Line | Count | Source | 361 | 600k | #define LogPrintf(...) LogInfo(__VA_ARGS__) Line | Count | Source | 356 | 600k | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 600k | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
|
4934 | 600k | return false; |
4935 | 600k | } |
4936 | | |
4937 | 50.1k | if (pnode.addr.IsLocal()) { |
4938 | | // We disconnect local peers for bad behavior but don't discourage (since that would discourage |
4939 | | // all peers on the same local address) |
4940 | 5.53k | LogDebug(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n", Line | Count | Source | 381 | 5.53k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 5.53k | do { \ | 374 | 5.53k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 5.53k | } while (0) |
|
|
4941 | 5.53k | pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id); |
4942 | 5.53k | pnode.fDisconnect = true; |
4943 | 5.53k | return true; |
4944 | 5.53k | } |
4945 | | |
4946 | | // Normal case: Disconnect the peer and discourage all nodes sharing the address |
4947 | 44.5k | LogDebug(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id); Line | Count | Source | 381 | 44.5k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 44.5k | do { \ | 374 | 44.5k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 44.5k | } while (0) |
|
|
4948 | 44.5k | if (m_banman) m_banman->Discourage(pnode.addr); |
4949 | 44.5k | m_connman.DisconnectNode(pnode.addr); |
4950 | 44.5k | return true; |
4951 | 50.1k | } |
4952 | | |
4953 | | bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc) |
4954 | 6.47M | { |
4955 | 6.47M | AssertLockNotHeld(m_tx_download_mutex); Line | Count | Source | 142 | 6.47M | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
4956 | 6.47M | AssertLockHeld(g_msgproc_mutex); Line | Count | Source | 137 | 6.47M | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
4957 | | |
4958 | 6.47M | PeerRef peer = GetPeerRef(pfrom->GetId()); |
4959 | 6.47M | if (peer == nullptr) return false0 ; |
4960 | | |
4961 | | // For outbound connections, ensure that the initial VERSION message |
4962 | | // has been sent first before processing any incoming messages |
4963 | 6.47M | if (!pfrom->IsInboundConn() && !peer->m_outbound_version_message_sent5.58M ) return false0 ; |
4964 | | |
4965 | 6.47M | { |
4966 | 6.47M | LOCK(peer->m_getdata_requests_mutex); Line | Count | Source | 259 | 6.47M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 6.47M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 6.47M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 6.47M | #define PASTE(x, y) x ## y |
|
|
|
|
4967 | 6.47M | if (!peer->m_getdata_requests.empty()) { |
4968 | 0 | ProcessGetData(*pfrom, *peer, interruptMsgProc); |
4969 | 0 | } |
4970 | 6.47M | } |
4971 | | |
4972 | 6.47M | const bool processed_orphan = ProcessOrphanTx(*peer); |
4973 | | |
4974 | 6.47M | if (pfrom->fDisconnect) |
4975 | 456k | return false; |
4976 | | |
4977 | 6.02M | if (processed_orphan) return true0 ; |
4978 | | |
4979 | | // this maintains the order of responses |
4980 | | // and prevents m_getdata_requests to grow unbounded |
4981 | 6.02M | { |
4982 | 6.02M | LOCK(peer->m_getdata_requests_mutex); Line | Count | Source | 259 | 6.02M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 6.02M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 6.02M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 6.02M | #define PASTE(x, y) x ## y |
|
|
|
|
4983 | 6.02M | if (!peer->m_getdata_requests.empty()) return true0 ; |
4984 | 6.02M | } |
4985 | | |
4986 | | // Don't bother if send buffer is too full to respond anyway |
4987 | 6.02M | if (pfrom->fPauseSend) return false0 ; |
4988 | | |
4989 | 6.02M | auto poll_result{pfrom->PollMessage()}; |
4990 | 6.02M | if (!poll_result) { |
4991 | | // No message to process |
4992 | 0 | return false; |
4993 | 0 | } |
4994 | | |
4995 | 6.02M | CNetMessage& msg{poll_result->first}; |
4996 | 6.02M | bool fMoreWork = poll_result->second; |
4997 | | |
4998 | 6.02M | TRACEPOINT(net, inbound_message, |
4999 | 6.02M | pfrom->GetId(), |
5000 | 6.02M | pfrom->m_addr_name.c_str(), |
5001 | 6.02M | pfrom->ConnectionTypeAsString().c_str(), |
5002 | 6.02M | msg.m_type.c_str(), |
5003 | 6.02M | msg.m_recv.size(), |
5004 | 6.02M | msg.m_recv.data() |
5005 | 6.02M | ); |
5006 | | |
5007 | 6.02M | if (m_opts.capture_messages) { |
5008 | 0 | CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true); |
5009 | 0 | } |
5010 | | |
5011 | 6.02M | try { |
5012 | 6.02M | ProcessMessage(*pfrom, msg.m_type, msg.m_recv, msg.m_time, interruptMsgProc); |
5013 | 6.02M | if (interruptMsgProc) return false0 ; |
5014 | 6.02M | { |
5015 | 6.02M | LOCK(peer->m_getdata_requests_mutex); Line | Count | Source | 259 | 6.02M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 6.02M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 6.02M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 6.02M | #define PASTE(x, y) x ## y |
|
|
|
|
5016 | 6.02M | if (!peer->m_getdata_requests.empty()) fMoreWork = true0 ; |
5017 | 6.02M | } |
5018 | | // Does this peer has an orphan ready to reconsider? |
5019 | | // (Note: we may have provided a parent for an orphan provided |
5020 | | // by another peer that was already processed; in that case, |
5021 | | // the extra work may not be noticed, possibly resulting in an |
5022 | | // unnecessary 100ms delay) |
5023 | 6.02M | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 6.02M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 6.02M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 6.02M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 6.02M | #define PASTE(x, y) x ## y |
|
|
|
|
5024 | 6.02M | if (m_txdownloadman.HaveMoreWork(peer->m_id)) fMoreWork = true0 ; |
5025 | 6.02M | } catch (const std::exception& e) { |
5026 | 0 | LogDebug(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size, e.what(), typeid(e).name()); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5027 | 0 | } catch (...) { |
5028 | 0 | LogDebug(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5029 | 0 | } |
5030 | | |
5031 | 6.02M | return fMoreWork; |
5032 | 6.02M | } |
5033 | | |
5034 | | void PeerManagerImpl::ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) |
5035 | 5.81M | { |
5036 | 5.81M | AssertLockHeld(cs_main); Line | Count | Source | 137 | 5.81M | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
5037 | | |
5038 | 5.81M | CNodeState &state = *State(pto.GetId()); |
5039 | | |
5040 | 5.81M | if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn()5.80M && state.fSyncStarted33.1k ) { |
5041 | | // This is an outbound peer subject to disconnection if they don't |
5042 | | // announce a block with as much work as the current tip within |
5043 | | // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if |
5044 | | // their chain has more work than ours, we should sync to it, |
5045 | | // unless it's invalid, in which case we should find that out and |
5046 | | // disconnect from them elsewhere). |
5047 | 23.5k | if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork15.3k ) { |
5048 | | // 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 |
5049 | 10.5k | if (state.m_chain_sync.m_timeout != 0s) { |
5050 | 425 | state.m_chain_sync.m_timeout = 0s; |
5051 | 425 | state.m_chain_sync.m_work_header = nullptr; |
5052 | 425 | state.m_chain_sync.m_sent_getheaders = false; |
5053 | 425 | } |
5054 | 13.0k | } else if (state.m_chain_sync.m_timeout == 0s || (11.1k state.m_chain_sync.m_work_header != nullptr11.1k && state.pindexBestKnownBlock != nullptr11.1k && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork4.68k )) { |
5055 | | // 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 |
5056 | | // AND |
5057 | | // we are noticing this for the first time (m_timeout is 0) |
5058 | | // OR we noticed this at some point within the last CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds and set a timeout |
5059 | | // 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). |
5060 | | // Either way, set a new timeout based on our current tip. |
5061 | 1.89k | state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT; |
5062 | 1.89k | state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip(); |
5063 | 1.89k | state.m_chain_sync.m_sent_getheaders = false; |
5064 | 11.1k | } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) { |
5065 | | // No evidence yet that our peer has synced to a chain with work equal to that |
5066 | | // of our tip, when we first detected it was behind. Send a single getheaders |
5067 | | // message to give the peer a chance to update us. |
5068 | 290 | if (state.m_chain_sync.m_sent_getheaders) { |
5069 | | // They've run out of time to catch up! |
5070 | 68 | LogInfo("Outbound peer has old chain, best known block = %s, %s\n", state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", pto.DisconnectMsg(fLogIPs)); Line | Count | Source | 356 | 68 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 136 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, 68 __VA_ARGS__) |
|
|
5071 | 68 | pto.fDisconnect = true; |
5072 | 222 | } else { |
5073 | 222 | assert(state.m_chain_sync.m_work_header); |
5074 | | // Here, we assume that the getheaders message goes out, |
5075 | | // because it'll either go out or be skipped because of a |
5076 | | // getheaders in-flight already, in which case the peer should |
5077 | | // still respond to us with a sufficiently high work chain tip. |
5078 | 222 | MaybeSendGetHeaders(pto, |
5079 | 222 | GetLocator(state.m_chain_sync.m_work_header->pprev), |
5080 | 222 | peer); |
5081 | 222 | LogDebug(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString()); Line | Count | Source | 381 | 222 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 222 | do { \ | 374 | 222 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 222 | } while (0) |
|
|
5082 | 222 | state.m_chain_sync.m_sent_getheaders = true; |
5083 | | // Bump the timeout to allow a response, which could clear the timeout |
5084 | | // (if the response shows the peer has synced), reset the timeout (if |
5085 | | // the peer syncs to the required work but not to our tip), or result |
5086 | | // in disconnect (if we advance to the timeout and pindexBestKnownBlock |
5087 | | // has not sufficiently progressed) |
5088 | 222 | state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME; |
5089 | 222 | } |
5090 | 290 | } |
5091 | 23.5k | } |
5092 | 5.81M | } |
5093 | | |
5094 | | void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) |
5095 | 0 | { |
5096 | | // If we have any extra block-relay-only peers, disconnect the youngest unless |
5097 | | // it's given us a block -- in which case, compare with the second-youngest, and |
5098 | | // out of those two, disconnect the peer who least recently gave us a block. |
5099 | | // The youngest block-relay-only peer would be the extra peer we connected |
5100 | | // to temporarily in order to sync our tip; see net.cpp. |
5101 | | // Note that we use higher nodeid as a measure for most recent connection. |
5102 | 0 | if (m_connman.GetExtraBlockRelayCount() > 0) { |
5103 | 0 | std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0}; |
5104 | |
|
5105 | 0 | m_connman.ForEachNode([&](CNode* pnode) { |
5106 | 0 | if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return; |
5107 | 0 | if (pnode->GetId() > youngest_peer.first) { |
5108 | 0 | next_youngest_peer = youngest_peer; |
5109 | 0 | youngest_peer.first = pnode->GetId(); |
5110 | 0 | youngest_peer.second = pnode->m_last_block_time; |
5111 | 0 | } |
5112 | 0 | }); |
5113 | 0 | NodeId to_disconnect = youngest_peer.first; |
5114 | 0 | if (youngest_peer.second > next_youngest_peer.second) { |
5115 | | // Our newest block-relay-only peer gave us a block more recently; |
5116 | | // disconnect our second youngest. |
5117 | 0 | to_disconnect = next_youngest_peer.first; |
5118 | 0 | } |
5119 | 0 | m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
5120 | 0 | AssertLockHeld(::cs_main); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
5121 | | // Make sure we're not getting a block right now, and that |
5122 | | // we've been connected long enough for this eviction to happen |
5123 | | // at all. |
5124 | | // Note that we only request blocks from a peer if we learn of a |
5125 | | // valid headers chain with at least as much work as our tip. |
5126 | 0 | CNodeState *node_state = State(pnode->GetId()); |
5127 | 0 | if (node_state == nullptr || |
5128 | 0 | (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->vBlocksInFlight.empty())) { |
5129 | 0 | pnode->fDisconnect = true; |
5130 | 0 | LogDebug(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5131 | 0 | pnode->GetId(), count_seconds(pnode->m_last_block_time)); |
5132 | 0 | return true; |
5133 | 0 | } else { |
5134 | 0 | LogDebug(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5135 | 0 | pnode->GetId(), count_seconds(pnode->m_connected), node_state->vBlocksInFlight.size()); |
5136 | 0 | } |
5137 | 0 | return false; |
5138 | 0 | }); |
5139 | 0 | } |
5140 | | |
5141 | | // Check whether we have too many outbound-full-relay peers |
5142 | 0 | if (m_connman.GetExtraFullOutboundCount() > 0) { |
5143 | | // If we have more outbound-full-relay peers than we target, disconnect one. |
5144 | | // Pick the outbound-full-relay peer that least recently announced |
5145 | | // us a new block, with ties broken by choosing the more recent |
5146 | | // connection (higher node id) |
5147 | | // Protect peers from eviction if we don't have another connection |
5148 | | // to their network, counting both outbound-full-relay and manual peers. |
5149 | 0 | NodeId worst_peer = -1; |
5150 | 0 | int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max(); |
5151 | |
|
5152 | 0 | m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_connman.GetNodesMutex()) { |
5153 | 0 | AssertLockHeld(::cs_main); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
5154 | | |
5155 | | // Only consider outbound-full-relay peers that are not already |
5156 | | // marked for disconnection |
5157 | 0 | if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return; |
5158 | 0 | CNodeState *state = State(pnode->GetId()); |
5159 | 0 | if (state == nullptr) return; // shouldn't be possible, but just in case |
5160 | | // Don't evict our protected peers |
5161 | 0 | if (state->m_chain_sync.m_protect) return; |
5162 | | // If this is the only connection on a particular network that is |
5163 | | // OUTBOUND_FULL_RELAY or MANUAL, protect it. |
5164 | 0 | if (!m_connman.MultipleManualOrFullOutboundConns(pnode->addr.GetNetwork())) return; |
5165 | 0 | if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) { |
5166 | 0 | worst_peer = pnode->GetId(); |
5167 | 0 | oldest_block_announcement = state->m_last_block_announcement; |
5168 | 0 | } |
5169 | 0 | }); |
5170 | 0 | if (worst_peer != -1) { |
5171 | 0 | bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
5172 | 0 | AssertLockHeld(::cs_main); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
5173 | | |
5174 | | // Only disconnect a peer that has been connected to us for |
5175 | | // some reasonable fraction of our check-frequency, to give |
5176 | | // it time for new information to have arrived. |
5177 | | // Also don't disconnect any peer we're trying to download a |
5178 | | // block from. |
5179 | 0 | CNodeState &state = *State(pnode->GetId()); |
5180 | 0 | if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.vBlocksInFlight.empty()) { |
5181 | 0 | LogDebug(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5182 | 0 | pnode->fDisconnect = true; |
5183 | 0 | return true; |
5184 | 0 | } else { |
5185 | 0 | LogDebug(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5186 | 0 | pnode->GetId(), count_seconds(pnode->m_connected), state.vBlocksInFlight.size()); |
5187 | 0 | return false; |
5188 | 0 | } |
5189 | 0 | }); |
5190 | 0 | if (disconnected) { |
5191 | | // If we disconnected an extra peer, that means we successfully |
5192 | | // connected to at least one peer after the last time we |
5193 | | // detected a stale tip. Don't try any more extra peers until |
5194 | | // we next detect a stale tip, to limit the load we put on the |
5195 | | // network from these extra connections. |
5196 | 0 | m_connman.SetTryNewOutboundPeer(false); |
5197 | 0 | } |
5198 | 0 | } |
5199 | 0 | } |
5200 | 0 | } |
5201 | | |
5202 | | void PeerManagerImpl::CheckForStaleTipAndEvictPeers() |
5203 | 0 | { |
5204 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
5205 | |
|
5206 | 0 | auto now{GetTime<std::chrono::seconds>()}; |
5207 | |
|
5208 | 0 | EvictExtraOutboundPeers(now); |
5209 | |
|
5210 | 0 | if (now > m_stale_tip_check_time) { |
5211 | | // Check whether our tip is stale, and if so, allow using an extra |
5212 | | // outbound peer |
5213 | 0 | if (!m_chainman.m_blockman.LoadingBlocks() && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) { |
5214 | 0 | LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", Line | Count | Source | 361 | 0 | #define LogPrintf(...) LogInfo(__VA_ARGS__) Line | Count | Source | 356 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
|
5215 | 0 | count_seconds(now - m_last_tip_update.load())); |
5216 | 0 | m_connman.SetTryNewOutboundPeer(true); |
5217 | 0 | } else if (m_connman.GetTryNewOutboundPeer()) { |
5218 | 0 | m_connman.SetTryNewOutboundPeer(false); |
5219 | 0 | } |
5220 | 0 | m_stale_tip_check_time = now + STALE_CHECK_INTERVAL; |
5221 | 0 | } |
5222 | |
|
5223 | 0 | if (!m_initial_sync_finished && CanDirectFetch()) { |
5224 | 0 | m_connman.StartExtraBlockRelayPeers(); |
5225 | 0 | m_initial_sync_finished = true; |
5226 | 0 | } |
5227 | 0 | } |
5228 | | |
5229 | | void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now) |
5230 | 5.82M | { |
5231 | 5.82M | if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) && |
5232 | 5.82M | peer.m_ping_nonce_sent22.2k && |
5233 | 5.82M | now > peer.m_ping_start.load() + TIMEOUT_INTERVAL5.74k ) |
5234 | 5.74k | { |
5235 | | // The ping timeout is using mocktime. To disable the check during |
5236 | | // testing, increase -peertimeout. |
5237 | 5.74k | LogDebug(BCLog::NET, "ping timeout: %fs, %s", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), node_to.DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 5.74k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 5.74k | do { \ | 374 | 5.74k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 5.74k | } while (0) |
|
|
5238 | 5.74k | node_to.fDisconnect = true; |
5239 | 5.74k | return; |
5240 | 5.74k | } |
5241 | | |
5242 | 5.82M | bool pingSend = false; |
5243 | | |
5244 | 5.82M | if (peer.m_ping_queued) { |
5245 | | // RPC ping request by user |
5246 | 0 | pingSend = true; |
5247 | 0 | } |
5248 | | |
5249 | 5.82M | if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL100k ) { |
5250 | | // Ping automatically sent as a latency probe & keepalive. |
5251 | 77.5k | pingSend = true; |
5252 | 77.5k | } |
5253 | | |
5254 | 5.82M | if (pingSend) { |
5255 | 77.5k | uint64_t nonce; |
5256 | 77.5k | do { |
5257 | 77.5k | nonce = FastRandomContext().rand64(); |
5258 | 77.5k | } while (nonce == 0); |
5259 | 77.5k | peer.m_ping_queued = false; |
5260 | 77.5k | peer.m_ping_start = now; |
5261 | 77.5k | if (node_to.GetCommonVersion() > BIP0031_VERSION) { |
5262 | 76.1k | peer.m_ping_nonce_sent = nonce; |
5263 | 76.1k | MakeAndPushMessage(node_to, NetMsgType::PING, nonce); |
5264 | 76.1k | } else { |
5265 | | // Peer is too old to support ping command with nonce, pong will never arrive. |
5266 | 1.40k | peer.m_ping_nonce_sent = 0; |
5267 | 1.40k | MakeAndPushMessage(node_to, NetMsgType::PING); |
5268 | 1.40k | } |
5269 | 77.5k | } |
5270 | 5.82M | } |
5271 | | |
5272 | | void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) |
5273 | 5.82M | { |
5274 | | // Nothing to do for non-address-relay peers |
5275 | 5.82M | if (!peer.m_addr_relay_enabled) return722k ; |
5276 | | |
5277 | 5.09M | LOCK(peer.m_addr_send_times_mutex); Line | Count | Source | 259 | 5.09M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 5.09M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 5.09M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 5.09M | #define PASTE(x, y) x ## y |
|
|
|
|
5278 | | // Periodically advertise our local address to the peer. |
5279 | 5.09M | if (fListen && !m_chainman.IsInitialBlockDownload() && |
5280 | 5.09M | peer.m_next_local_addr_send < current_time4.75M ) { |
5281 | | // If we've sent before, clear the bloom filter for the peer, so that our |
5282 | | // self-announcement will actually go out. |
5283 | | // This might be unnecessary if the bloom filter has already rolled |
5284 | | // over since our last self-announcement, but there is only a small |
5285 | | // bandwidth cost that we can incur by doing this (which happens |
5286 | | // once a day on average). |
5287 | 53.8k | if (peer.m_next_local_addr_send != 0us) { |
5288 | 18.1k | peer.m_addr_known->reset(); |
5289 | 18.1k | } |
5290 | 53.8k | if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) { |
5291 | 0 | CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()}; |
5292 | 0 | PushAddress(peer, local_addr); |
5293 | 0 | } |
5294 | 53.8k | peer.m_next_local_addr_send = current_time + m_rng.rand_exp_duration(AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL); |
5295 | 53.8k | } |
5296 | | |
5297 | | // We sent an `addr` message to this peer recently. Nothing more to do. |
5298 | 5.09M | if (current_time <= peer.m_next_addr_send) return5.05M ; |
5299 | | |
5300 | 47.1k | peer.m_next_addr_send = current_time + m_rng.rand_exp_duration(AVG_ADDRESS_BROADCAST_INTERVAL); |
5301 | | |
5302 | 47.1k | if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) { Line | Count | Source | 118 | 47.1k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) |
|
5303 | | // Should be impossible since we always check size before adding to |
5304 | | // m_addrs_to_send. Recover by trimming the vector. |
5305 | 0 | peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND); |
5306 | 0 | } |
5307 | | |
5308 | | // Remove addr records that the peer already knows about, and add new |
5309 | | // addrs to the m_addr_known filter on the same pass. |
5310 | 47.1k | auto addr_already_known = [&peer](const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) { |
5311 | 0 | bool ret = peer.m_addr_known->contains(addr.GetKey()); |
5312 | 0 | if (!ret) peer.m_addr_known->insert(addr.GetKey()); |
5313 | 0 | return ret; |
5314 | 0 | }; |
5315 | 47.1k | peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known), |
5316 | 47.1k | peer.m_addrs_to_send.end()); |
5317 | | |
5318 | | // No addr messages to send |
5319 | 47.1k | if (peer.m_addrs_to_send.empty()) return; |
5320 | | |
5321 | 0 | if (peer.m_wants_addrv2) { |
5322 | 0 | MakeAndPushMessage(node, NetMsgType::ADDRV2, CAddress::V2_NETWORK(peer.m_addrs_to_send)); |
5323 | 0 | } else { |
5324 | 0 | MakeAndPushMessage(node, NetMsgType::ADDR, CAddress::V1_NETWORK(peer.m_addrs_to_send)); |
5325 | 0 | } |
5326 | 0 | peer.m_addrs_to_send.clear(); |
5327 | | |
5328 | | // we only send the big addr message once |
5329 | 0 | if (peer.m_addrs_to_send.capacity() > 40) { |
5330 | 0 | peer.m_addrs_to_send.shrink_to_fit(); |
5331 | 0 | } |
5332 | 0 | } |
5333 | | |
5334 | | void PeerManagerImpl::MaybeSendSendHeaders(CNode& node, Peer& peer) |
5335 | 5.82M | { |
5336 | | // Delay sending SENDHEADERS (BIP 130) until we're done with an |
5337 | | // initial-headers-sync with this peer. Receiving headers announcements for |
5338 | | // new blocks while trying to sync their headers chain is problematic, |
5339 | | // because of the state tracking done. |
5340 | 5.82M | if (!peer.m_sent_sendheaders && node.GetCommonVersion() >= SENDHEADERS_VERSION902k ) { |
5341 | 871k | LOCK(cs_main); Line | Count | Source | 259 | 871k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 871k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 871k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 871k | #define PASTE(x, y) x ## y |
|
|
|
|
5342 | 871k | CNodeState &state = *State(node.GetId()); |
5343 | 871k | if (state.pindexBestKnownBlock != nullptr && |
5344 | 871k | state.pindexBestKnownBlock->nChainWork > m_chainman.MinimumChainWork()40.0k ) { |
5345 | | // Tell our peer we prefer to receive headers rather than inv's |
5346 | | // We send this to non-NODE NETWORK peers as well, because even |
5347 | | // non-NODE NETWORK peers can announce blocks (such as pruning |
5348 | | // nodes) |
5349 | 40.0k | MakeAndPushMessage(node, NetMsgType::SENDHEADERS); |
5350 | 40.0k | peer.m_sent_sendheaders = true; |
5351 | 40.0k | } |
5352 | 871k | } |
5353 | 5.82M | } |
5354 | | |
5355 | | void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time) |
5356 | 5.81M | { |
5357 | 5.81M | if (m_opts.ignore_incoming_txs) return0 ; |
5358 | 5.81M | if (pto.GetCommonVersion() < FEEFILTER_VERSION) return31.4k ; |
5359 | | // peers with the forcerelay permission should not filter txs to us |
5360 | 5.78M | if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return4.66M ; |
5361 | | // Don't send feefilter messages to outbound block-relay-only peers since they should never announce |
5362 | | // transactions to us, regardless of feefilter state. |
5363 | 1.11M | if (pto.IsBlockOnlyConn()) return13.2k ; |
5364 | | |
5365 | 1.10M | CAmount currentFilter = m_mempool.GetMinFee().GetFeePerK(); |
5366 | | |
5367 | 1.10M | if (m_chainman.IsInitialBlockDownload()) { |
5368 | | // Received tx-inv messages are discarded when the active |
5369 | | // chainstate is in IBD, so tell the peer to not send them. |
5370 | 469k | currentFilter = MAX_MONEY; |
5371 | 636k | } else { |
5372 | 636k | static const CAmount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)}; |
5373 | 636k | if (peer.m_fee_filter_sent == MAX_FILTER) { |
5374 | | // Send the current filter if we sent MAX_FILTER previously |
5375 | | // and made it out of IBD. |
5376 | 28.0k | peer.m_next_send_feefilter = 0us; |
5377 | 28.0k | } |
5378 | 636k | } |
5379 | 1.10M | if (current_time > peer.m_next_send_feefilter) { |
5380 | 103k | CAmount filterToSend = m_fee_filter_rounder.round(currentFilter); |
5381 | | // We always have a fee filter of at least the min relay fee |
5382 | 103k | filterToSend = std::max(filterToSend, m_mempool.m_opts.min_relay_feerate.GetFeePerK()); |
5383 | 103k | if (filterToSend != peer.m_fee_filter_sent) { |
5384 | 71.4k | MakeAndPushMessage(pto, NetMsgType::FEEFILTER, filterToSend); |
5385 | 71.4k | peer.m_fee_filter_sent = filterToSend; |
5386 | 71.4k | } |
5387 | 103k | peer.m_next_send_feefilter = current_time + m_rng.rand_exp_duration(AVG_FEEFILTER_BROADCAST_INTERVAL); |
5388 | 103k | } |
5389 | | // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY |
5390 | | // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY. |
5391 | 1.00M | else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter && |
5392 | 1.00M | (65.2k currentFilter < 3 * peer.m_fee_filter_sent / 465.2k || currentFilter > 4 * peer.m_fee_filter_sent / 36.17k )) { |
5393 | 65.2k | peer.m_next_send_feefilter = current_time + m_rng.randrange<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY); |
5394 | 65.2k | } |
5395 | 1.10M | } |
5396 | | |
5397 | | namespace { |
5398 | | class CompareInvMempoolOrder |
5399 | | { |
5400 | | const CTxMemPool* m_mempool; |
5401 | | public: |
5402 | 2.33M | explicit CompareInvMempoolOrder(CTxMemPool* mempool) : m_mempool{mempool} {} |
5403 | | |
5404 | | bool operator()(std::set<Wtxid>::iterator a, std::set<Wtxid>::iterator b) |
5405 | 682k | { |
5406 | | /* As std::make_heap produces a max-heap, we want the entries with the |
5407 | | * fewest ancestors/highest fee to sort later. */ |
5408 | 682k | return m_mempool->CompareDepthAndScore(*b, *a); |
5409 | 682k | } |
5410 | | }; |
5411 | | } // namespace |
5412 | | |
5413 | | bool PeerManagerImpl::RejectIncomingTxs(const CNode& peer) const |
5414 | 1.33M | { |
5415 | | // block-relay-only peers may never send txs to us |
5416 | 1.33M | if (peer.IsBlockOnlyConn()) return true2.65k ; |
5417 | 1.32M | if (peer.IsFeelerConn()) return true20.0k ; |
5418 | | // In -blocksonly mode, peers need the 'relay' permission to send txs to us |
5419 | 1.30M | if (m_opts.ignore_incoming_txs && !peer.HasPermission(NetPermissionFlags::Relay)0 ) return true0 ; |
5420 | 1.30M | return false; |
5421 | 1.30M | } |
5422 | | |
5423 | | bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer) |
5424 | 70.4k | { |
5425 | | // We don't participate in addr relay with outbound block-relay-only |
5426 | | // connections to prevent providing adversaries with the additional |
5427 | | // information of addr traffic to infer the link. |
5428 | 70.4k | if (node.IsBlockOnlyConn()) return false869 ; |
5429 | | |
5430 | 69.5k | if (!peer.m_addr_relay_enabled.exchange(true)) { |
5431 | | // During version message processing (non-block-relay-only outbound peers) |
5432 | | // or on first addr-related message we have received (inbound peers), initialize |
5433 | | // m_addr_known. |
5434 | 69.5k | peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001); |
5435 | 69.5k | } |
5436 | | |
5437 | 69.5k | return true; |
5438 | 70.4k | } |
5439 | | |
5440 | | bool PeerManagerImpl::SendMessages(CNode* pto) |
5441 | 6.59M | { |
5442 | 6.59M | AssertLockNotHeld(m_tx_download_mutex); Line | Count | Source | 142 | 6.59M | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
5443 | 6.59M | AssertLockHeld(g_msgproc_mutex); Line | Count | Source | 137 | 6.59M | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
5444 | | |
5445 | 6.59M | PeerRef peer = GetPeerRef(pto->GetId()); |
5446 | 6.59M | if (!peer) return false0 ; |
5447 | 6.59M | const Consensus::Params& consensusParams = m_chainparams.GetConsensus(); |
5448 | | |
5449 | | // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll |
5450 | | // disconnect misbehaving peers even before the version handshake is complete. |
5451 | 6.59M | if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true50.1k ; |
5452 | | |
5453 | | // Initiate version handshake for outbound connections |
5454 | 6.54M | if (!pto->IsInboundConn() && !peer->m_outbound_version_message_sent5.65M ) { |
5455 | 77.2k | PushNodeVersion(*pto, *peer); |
5456 | 77.2k | peer->m_outbound_version_message_sent = true; |
5457 | 77.2k | } |
5458 | | |
5459 | | // Don't send anything until the version handshake is complete |
5460 | 6.54M | if (!pto->fSuccessfullyConnected || pto->fDisconnect6.11M ) |
5461 | 716k | return true; |
5462 | | |
5463 | 5.82M | const auto current_time{GetTime<std::chrono::microseconds>()}; |
5464 | | |
5465 | 5.82M | if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL2.29k ) { |
5466 | 34 | LogDebug(BCLog::NET, "addrfetch connection timeout, %s\n", pto->DisconnectMsg(fLogIPs)); Line | Count | Source | 381 | 34 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 34 | do { \ | 374 | 34 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 34 | } while (0) |
|
|
5467 | 34 | pto->fDisconnect = true; |
5468 | 34 | return true; |
5469 | 34 | } |
5470 | | |
5471 | 5.82M | MaybeSendPing(*pto, *peer, current_time); |
5472 | | |
5473 | | // MaybeSendPing may have marked peer for disconnection |
5474 | 5.82M | if (pto->fDisconnect) return true5.78k ; |
5475 | | |
5476 | 5.82M | MaybeSendAddr(*pto, *peer, current_time); |
5477 | | |
5478 | 5.82M | MaybeSendSendHeaders(*pto, *peer); |
5479 | | |
5480 | 5.82M | { |
5481 | 5.82M | LOCK(cs_main); Line | Count | Source | 259 | 5.82M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 5.82M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 5.82M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 5.82M | #define PASTE(x, y) x ## y |
|
|
|
|
5482 | | |
5483 | 5.82M | CNodeState &state = *State(pto->GetId()); |
5484 | | |
5485 | | // Start block sync |
5486 | 5.82M | if (m_chainman.m_best_header == nullptr) { |
5487 | 0 | m_chainman.m_best_header = m_chainman.ActiveChain().Tip(); |
5488 | 0 | } |
5489 | | |
5490 | | // Determine whether we might try initial headers sync or parallel |
5491 | | // block download from this peer -- this mostly affects behavior while |
5492 | | // in IBD (once out of IBD, we sync from all peers). |
5493 | 5.82M | bool sync_blocks_and_headers_from_peer = false; |
5494 | 5.82M | if (state.fPreferredDownload) { |
5495 | 4.41M | sync_blocks_and_headers_from_peer = true; |
5496 | 4.41M | } else if (1.40M CanServeBlocks(*peer)1.40M && !pto->IsAddrFetchConn()9.09k ) { |
5497 | | // Typically this is an inbound peer. If we don't have any outbound |
5498 | | // peers, or if we aren't downloading any blocks from such peers, |
5499 | | // then allow block downloads from this peer, too. |
5500 | | // We prefer downloading blocks from outbound peers to avoid |
5501 | | // putting undue load on (say) some home user who is just making |
5502 | | // outbound connections to the network, but if our only source of |
5503 | | // the latest blocks is from an inbound peer, we have to be sure to |
5504 | | // eventually download it (and not just wait indefinitely for an |
5505 | | // outbound peer to have it). |
5506 | 6.83k | if (m_num_preferred_download_peers == 0 || mapBlocksInFlight.empty()5.18k ) { |
5507 | 6.66k | sync_blocks_and_headers_from_peer = true; |
5508 | 6.66k | } |
5509 | 6.83k | } |
5510 | | |
5511 | 5.82M | if (!state.fSyncStarted && CanServeBlocks(*peer)1.46M && !m_chainman.m_blockman.LoadingBlocks()75.2k ) { |
5512 | | // Only actively request headers from a single peer, unless we're close to today. |
5513 | 75.2k | if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer37.1k ) || m_chainman.m_best_header->Time() > NodeClock::now() - 24h40.2k ) { |
5514 | 50.4k | const CBlockIndex* pindexStart = m_chainman.m_best_header; |
5515 | | /* If possible, start at the block preceding the currently |
5516 | | best known header. This ensures that we always get a |
5517 | | non-empty list of headers back as long as the peer |
5518 | | is up-to-date. With a non-empty response, we can initialise |
5519 | | the peer's known best block. This wouldn't be possible |
5520 | | if we requested starting at m_chainman.m_best_header and |
5521 | | got back an empty response. */ |
5522 | 50.4k | if (pindexStart->pprev) |
5523 | 50.4k | pindexStart = pindexStart->pprev; |
5524 | 50.4k | if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) { |
5525 | 38.9k | LogDebug(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height); Line | Count | Source | 381 | 38.9k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 38.9k | do { \ | 374 | 38.9k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 38.9k | } while (0) |
|
|
5526 | | |
5527 | 38.9k | state.fSyncStarted = true; |
5528 | 38.9k | peer->m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE + |
5529 | 38.9k | ( |
5530 | | // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling |
5531 | | // to maintain precision |
5532 | 38.9k | std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} * |
5533 | 38.9k | Ticks<std::chrono::seconds>(NodeClock::now() - m_chainman.m_best_header->Time()) / consensusParams.nPowTargetSpacing |
5534 | 38.9k | ); |
5535 | 38.9k | nSyncStarted++; |
5536 | 38.9k | } |
5537 | 50.4k | } |
5538 | 75.2k | } |
5539 | | |
5540 | | // |
5541 | | // Try sending block announcements via headers |
5542 | | // |
5543 | 5.82M | { |
5544 | | // If we have no more than MAX_BLOCKS_TO_ANNOUNCE in our |
5545 | | // list of block hashes we're relaying, and our peer wants |
5546 | | // headers announcements, then find the first header |
5547 | | // not yet known to our peer but would connect, and send. |
5548 | | // If no header would connect, or if we have too many |
5549 | | // blocks, or if the peer doesn't want headers, just |
5550 | | // add all to the inv queue. |
5551 | 5.82M | LOCK(peer->m_block_inv_mutex); Line | Count | Source | 259 | 5.82M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 5.82M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 5.82M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 5.82M | #define PASTE(x, y) x ## y |
|
|
|
|
5552 | 5.82M | std::vector<CBlock> vHeaders; |
5553 | 5.82M | bool fRevertToInv = ((!peer->m_prefers_headers && |
5554 | 5.82M | (!state.m_requested_hb_cmpctblocks || peer->m_blocks_for_headers_relay.size() > 12.56M )) || |
5555 | 5.82M | peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE2.56M ); |
5556 | 5.82M | const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery |
5557 | 5.82M | ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date |
5558 | | |
5559 | 5.82M | if (!fRevertToInv) { |
5560 | 2.56M | bool fFoundStartingHeader = false; |
5561 | | // Try to find first header that our peer doesn't have, and |
5562 | | // then send all headers past that one. If we come across any |
5563 | | // headers that aren't on m_chainman.ActiveChain(), give up. |
5564 | 2.56M | for (const uint256& hash : peer->m_blocks_for_headers_relay) { |
5565 | 23.3k | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash); |
5566 | 23.3k | assert(pindex); |
5567 | 23.3k | if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) { |
5568 | | // Bail out if we reorged away from this block |
5569 | 0 | fRevertToInv = true; |
5570 | 0 | break; |
5571 | 0 | } |
5572 | 23.3k | if (pBestIndex != nullptr && pindex->pprev != pBestIndex0 ) { |
5573 | | // This means that the list of blocks to announce don't |
5574 | | // connect to each other. |
5575 | | // This shouldn't really be possible to hit during |
5576 | | // regular operation (because reorgs should take us to |
5577 | | // a chain that has some block not on the prior chain, |
5578 | | // which should be caught by the prior check), but one |
5579 | | // way this could happen is by using invalidateblock / |
5580 | | // reconsiderblock repeatedly on the tip, causing it to |
5581 | | // be added multiple times to m_blocks_for_headers_relay. |
5582 | | // Robustly deal with this rare situation by reverting |
5583 | | // to an inv. |
5584 | 0 | fRevertToInv = true; |
5585 | 0 | break; |
5586 | 0 | } |
5587 | 23.3k | pBestIndex = pindex; |
5588 | 23.3k | if (fFoundStartingHeader) { |
5589 | | // add this to the headers message |
5590 | 0 | vHeaders.emplace_back(pindex->GetBlockHeader()); |
5591 | 23.3k | } else if (PeerHasHeader(&state, pindex)) { |
5592 | 15.9k | continue; // keep looking for the first new block |
5593 | 15.9k | } else if (7.41k pindex->pprev == nullptr7.41k || PeerHasHeader(&state, pindex->pprev)7.41k ) { |
5594 | | // Peer doesn't have this header but they do have the prior one. |
5595 | | // Start sending headers. |
5596 | 4.29k | fFoundStartingHeader = true; |
5597 | 4.29k | vHeaders.emplace_back(pindex->GetBlockHeader()); |
5598 | 4.29k | } else { |
5599 | | // Peer doesn't have this header or the prior one -- nothing will |
5600 | | // connect, so bail out. |
5601 | 3.12k | fRevertToInv = true; |
5602 | 3.12k | break; |
5603 | 3.12k | } |
5604 | 23.3k | } |
5605 | 2.56M | } |
5606 | 5.82M | if (!fRevertToInv && !vHeaders.empty()2.56M ) { |
5607 | 4.29k | if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) { |
5608 | | // We only send up to 1 block as header-and-ids, as otherwise |
5609 | | // probably means we're doing an initial-ish-sync or they're slow |
5610 | 4.29k | LogDebug(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__, Line | Count | Source | 381 | 4.29k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 4.29k | do { \ | 374 | 4.29k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 4.29k | } while (0) |
|
|
5611 | 4.29k | vHeaders.front().GetHash().ToString(), pto->GetId()); |
5612 | | |
5613 | 4.29k | std::optional<CSerializedNetMsg> cached_cmpctblock_msg; |
5614 | 4.29k | { |
5615 | 4.29k | LOCK(m_most_recent_block_mutex); Line | Count | Source | 259 | 4.29k | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 4.29k | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 4.29k | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 4.29k | #define PASTE(x, y) x ## y |
|
|
|
|
5616 | 4.29k | if (m_most_recent_block_hash == pBestIndex->GetBlockHash()) { |
5617 | 254 | cached_cmpctblock_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, *m_most_recent_compact_block); |
5618 | 254 | } |
5619 | 4.29k | } |
5620 | 4.29k | if (cached_cmpctblock_msg.has_value()) { |
5621 | 254 | PushMessage(*pto, std::move(cached_cmpctblock_msg.value())); |
5622 | 4.04k | } else { |
5623 | 4.04k | CBlock block; |
5624 | 4.04k | const bool ret{m_chainman.m_blockman.ReadBlock(block, *pBestIndex)}; |
5625 | 4.04k | assert(ret); |
5626 | 4.04k | CBlockHeaderAndShortTxIDs cmpctblock{block, m_rng.rand64()}; |
5627 | 4.04k | MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK, cmpctblock); |
5628 | 4.04k | } |
5629 | 4.29k | state.pindexBestHeaderSent = pBestIndex; |
5630 | 4.29k | } else if (0 peer->m_prefers_headers0 ) { |
5631 | 0 | if (vHeaders.size() > 1) { |
5632 | 0 | LogDebug(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__, Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5633 | 0 | vHeaders.size(), |
5634 | 0 | vHeaders.front().GetHash().ToString(), |
5635 | 0 | vHeaders.back().GetHash().ToString(), pto->GetId()); |
5636 | 0 | } else { |
5637 | 0 | LogDebug(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__, Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5638 | 0 | vHeaders.front().GetHash().ToString(), pto->GetId()); |
5639 | 0 | } |
5640 | 0 | MakeAndPushMessage(*pto, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders)); |
5641 | 0 | state.pindexBestHeaderSent = pBestIndex; |
5642 | 0 | } else |
5643 | 0 | fRevertToInv = true; |
5644 | 4.29k | } |
5645 | 5.82M | if (fRevertToInv) { |
5646 | | // If falling back to using an inv, just try to inv the tip. |
5647 | | // The last entry in m_blocks_for_headers_relay was our tip at some point |
5648 | | // in the past. |
5649 | 3.25M | if (!peer->m_blocks_for_headers_relay.empty()) { |
5650 | 23.5k | const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back(); |
5651 | 23.5k | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce); |
5652 | 23.5k | assert(pindex); |
5653 | | |
5654 | | // Warn if we're announcing a block that is not on the main chain. |
5655 | | // This should be very rare and could be optimized out. |
5656 | | // Just log for now. |
5657 | 23.5k | if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) { |
5658 | 0 | LogDebug(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n", Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5659 | 0 | hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString()); |
5660 | 0 | } |
5661 | | |
5662 | | // If the peer's chain has this block, don't inv it back. |
5663 | 23.5k | if (!PeerHasHeader(&state, pindex)) { |
5664 | 13.4k | peer->m_blocks_for_inv_relay.push_back(hashToAnnounce); |
5665 | 13.4k | LogDebug(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__, Line | Count | Source | 381 | 13.4k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 13.4k | do { \ | 374 | 13.4k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 13.4k | } while (0) |
|
|
5666 | 13.4k | pto->GetId(), hashToAnnounce.ToString()); |
5667 | 13.4k | } |
5668 | 23.5k | } |
5669 | 3.25M | } |
5670 | 5.82M | peer->m_blocks_for_headers_relay.clear(); |
5671 | 5.82M | } |
5672 | | |
5673 | | // |
5674 | | // Message: inventory |
5675 | | // |
5676 | 0 | std::vector<CInv> vInv; |
5677 | 5.82M | { |
5678 | 5.82M | LOCK(peer->m_block_inv_mutex); Line | Count | Source | 259 | 5.82M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 5.82M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 5.82M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 5.82M | #define PASTE(x, y) x ## y |
|
|
|
|
5679 | 5.82M | vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_TARGET)); |
5680 | | |
5681 | | // Add blocks |
5682 | 5.82M | for (const uint256& hash : peer->m_blocks_for_inv_relay) { |
5683 | 13.4k | vInv.emplace_back(MSG_BLOCK, hash); |
5684 | 13.4k | if (vInv.size() == MAX_INV_SZ) { |
5685 | 0 | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
5686 | 0 | vInv.clear(); |
5687 | 0 | } |
5688 | 13.4k | } |
5689 | 5.82M | peer->m_blocks_for_inv_relay.clear(); |
5690 | 5.82M | } |
5691 | | |
5692 | 5.82M | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { |
5693 | 2.94M | LOCK(tx_relay->m_tx_inventory_mutex); Line | Count | Source | 259 | 2.94M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 2.94M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 2.94M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 2.94M | #define PASTE(x, y) x ## y |
|
|
|
|
5694 | | // Check whether periodic sends should happen |
5695 | 2.94M | bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan); |
5696 | 2.94M | if (tx_relay->m_next_inv_send_time < current_time) { |
5697 | 51.5k | fSendTrickle = true; |
5698 | 51.5k | if (pto->IsInboundConn()) { |
5699 | 28.4k | tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL); |
5700 | 28.4k | } else { |
5701 | 23.1k | tx_relay->m_next_inv_send_time = current_time + m_rng.rand_exp_duration(OUTBOUND_INVENTORY_BROADCAST_INTERVAL); |
5702 | 23.1k | } |
5703 | 51.5k | } |
5704 | | |
5705 | | // Time to send but the peer has requested we not relay transactions. |
5706 | 2.94M | if (fSendTrickle) { |
5707 | 2.33M | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 2.33M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 2.33M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 2.33M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 2.33M | #define PASTE(x, y) x ## y |
|
|
|
|
5708 | 2.33M | if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear()1.30M ; |
5709 | 2.33M | } |
5710 | | |
5711 | | // Respond to BIP35 mempool requests |
5712 | 2.94M | if (fSendTrickle && tx_relay->m_send_mempool2.33M ) { |
5713 | 0 | auto vtxinfo = m_mempool.infoAll(); |
5714 | 0 | tx_relay->m_send_mempool = false; |
5715 | 0 | const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()}; |
5716 | |
|
5717 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
5718 | |
|
5719 | 0 | for (const auto& txinfo : vtxinfo) { |
5720 | 0 | const Txid& txid{txinfo.tx->GetHash()}; |
5721 | 0 | const Wtxid& wtxid{txinfo.tx->GetWitnessHash()}; |
5722 | 0 | const auto inv = peer->m_wtxid_relay ? |
5723 | 0 | CInv{MSG_WTX, wtxid.ToUint256()} : |
5724 | 0 | CInv{MSG_TX, txid.ToUint256()}; |
5725 | 0 | tx_relay->m_tx_inventory_to_send.erase(wtxid); |
5726 | | |
5727 | | // Don't send transactions that peers will not put into their mempool |
5728 | 0 | if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) { |
5729 | 0 | continue; |
5730 | 0 | } |
5731 | 0 | if (tx_relay->m_bloom_filter) { |
5732 | 0 | if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue; |
5733 | 0 | } |
5734 | 0 | tx_relay->m_tx_inventory_known_filter.insert(inv.hash); |
5735 | 0 | vInv.push_back(inv); |
5736 | 0 | if (vInv.size() == MAX_INV_SZ) { |
5737 | 0 | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
5738 | 0 | vInv.clear(); |
5739 | 0 | } |
5740 | 0 | } |
5741 | 0 | } |
5742 | | |
5743 | | // Determine transactions to relay |
5744 | 2.94M | if (fSendTrickle) { |
5745 | | // Produce a vector with all candidates for sending |
5746 | 2.33M | std::vector<std::set<Wtxid>::iterator> vInvTx; |
5747 | 2.33M | vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size()); |
5748 | 2.52M | for (std::set<Wtxid>::iterator it = tx_relay->m_tx_inventory_to_send.begin(); it != tx_relay->m_tx_inventory_to_send.end(); it++186k ) { |
5749 | 186k | vInvTx.push_back(it); |
5750 | 186k | } |
5751 | 2.33M | const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()}; |
5752 | | // Topologically and fee-rate sort the inventory we send for privacy and priority reasons. |
5753 | | // A heap is used so that not all items need sorting if only a few are being sent. |
5754 | 2.33M | CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool); |
5755 | 2.33M | std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); |
5756 | | // No reason to drain out at many times the network's capacity, |
5757 | | // especially since we have many peers and some will draw much shorter delays. |
5758 | 2.33M | unsigned int nRelayedTransactions = 0; |
5759 | 2.33M | LOCK(tx_relay->m_bloom_filter_mutex); Line | Count | Source | 259 | 2.33M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 2.33M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 2.33M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 2.33M | #define PASTE(x, y) x ## y |
|
|
|
|
5760 | 2.33M | size_t broadcast_max{INVENTORY_BROADCAST_TARGET + (tx_relay->m_tx_inventory_to_send.size()/1000)*5}; |
5761 | 2.33M | broadcast_max = std::min<size_t>(INVENTORY_BROADCAST_MAX, broadcast_max); |
5762 | 2.52M | while (!vInvTx.empty() && nRelayedTransactions < broadcast_max186k ) { |
5763 | | // Fetch the top element from the heap |
5764 | 186k | std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); |
5765 | 186k | std::set<Wtxid>::iterator it = vInvTx.back(); |
5766 | 186k | vInvTx.pop_back(); |
5767 | 186k | auto wtxid = *it; |
5768 | | // Remove it from the to-be-sent set |
5769 | 186k | tx_relay->m_tx_inventory_to_send.erase(it); |
5770 | | // Not in the mempool anymore? don't bother sending it. |
5771 | 186k | auto txinfo = m_mempool.info(wtxid); |
5772 | 186k | if (!txinfo.tx) { |
5773 | 92.1k | continue; |
5774 | 92.1k | } |
5775 | | // `TxRelay::m_tx_inventory_known_filter` contains either txids or wtxids |
5776 | | // depending on whether our peer supports wtxid-relay. Therefore, first |
5777 | | // construct the inv and then use its hash for the filter check. |
5778 | 94.5k | const auto inv = peer->m_wtxid_relay ? |
5779 | 0 | CInv{MSG_WTX, wtxid.ToUint256()} : |
5780 | 94.5k | CInv{MSG_TX, txinfo.tx->GetHash().ToUint256()}; |
5781 | | // Check if not in the filter already |
5782 | 94.5k | if (tx_relay->m_tx_inventory_known_filter.contains(inv.hash)) { |
5783 | 2.69k | continue; |
5784 | 2.69k | } |
5785 | | // Peer told you to not send transactions at that feerate? Don't bother sending it. |
5786 | 91.8k | if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) { |
5787 | 0 | continue; |
5788 | 0 | } |
5789 | 91.8k | if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)0 ) continue0 ; |
5790 | | // Send |
5791 | 91.8k | vInv.push_back(inv); |
5792 | 91.8k | nRelayedTransactions++; |
5793 | 91.8k | if (vInv.size() == MAX_INV_SZ) { |
5794 | 0 | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
5795 | 0 | vInv.clear(); |
5796 | 0 | } |
5797 | 91.8k | tx_relay->m_tx_inventory_known_filter.insert(inv.hash); |
5798 | 91.8k | } |
5799 | | |
5800 | | // Ensure we'll respond to GETDATA requests for anything we've just announced |
5801 | 2.33M | LOCK(m_mempool.cs); Line | Count | Source | 259 | 2.33M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 2.33M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 2.33M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 2.33M | #define PASTE(x, y) x ## y |
|
|
|
|
5802 | 2.33M | tx_relay->m_last_inv_sequence = m_mempool.GetSequence(); |
5803 | 2.33M | } |
5804 | 2.94M | } |
5805 | 5.82M | if (!vInv.empty()) |
5806 | 44.2k | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
5807 | | |
5808 | | // Detect whether we're stalling |
5809 | 5.82M | auto stalling_timeout = m_block_stalling_timeout.load(); |
5810 | 5.82M | if (state.m_stalling_since.count() && state.m_stalling_since < current_time - stalling_timeout0 ) { |
5811 | | // Stalling only triggers when the block download window cannot move. During normal steady state, |
5812 | | // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection |
5813 | | // should only happen during initial block download. |
5814 | 0 | LogInfo("Peer is stalling block download, %s\n", pto->DisconnectMsg(fLogIPs)); Line | Count | Source | 356 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
5815 | 0 | pto->fDisconnect = true; |
5816 | | // Increase timeout for the next peer so that we don't disconnect multiple peers if our own |
5817 | | // bandwidth is insufficient. |
5818 | 0 | const auto new_timeout = std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX); |
5819 | 0 | if (stalling_timeout != new_timeout && m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { |
5820 | 0 | LogDebug(BCLog::NET, "Increased stalling timeout temporarily to %d seconds\n", count_seconds(new_timeout)); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5821 | 0 | } |
5822 | 0 | return true; |
5823 | 0 | } |
5824 | | // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N) |
5825 | | // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout. |
5826 | | // We compensate for other peers to prevent killing off peers due to our own downstream link |
5827 | | // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes |
5828 | | // to unreasonably increase our timeout. |
5829 | 5.82M | if (state.vBlocksInFlight.size() > 0) { |
5830 | 3.51M | QueuedBlock &queuedBlock = state.vBlocksInFlight.front(); |
5831 | 3.51M | int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1; |
5832 | 3.51M | if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { |
5833 | 3.10k | LogInfo("Timeout downloading block %s, %s\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->DisconnectMsg(fLogIPs)); Line | Count | Source | 356 | 3.10k | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 3.10k | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
5834 | 3.10k | pto->fDisconnect = true; |
5835 | 3.10k | return true; |
5836 | 3.10k | } |
5837 | 3.51M | } |
5838 | | // Check for headers sync timeouts |
5839 | 5.81M | if (state.fSyncStarted && peer->m_headers_sync_timeout < std::chrono::microseconds::max()4.38M ) { |
5840 | | // Detect whether this is a stalling initial-headers-sync peer |
5841 | 349k | if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) { |
5842 | 319k | if (current_time > peer->m_headers_sync_timeout && nSyncStarted == 14.95k && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)2.62k ) { |
5843 | | // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer, |
5844 | | // and we have others we could be using instead. |
5845 | | // Note: If all our peers are inbound, then we won't |
5846 | | // disconnect our sync peer for stalling; we have bigger |
5847 | | // problems if we can't get any outbound peers. |
5848 | 272 | if (!pto->HasPermission(NetPermissionFlags::NoBan)) { |
5849 | 10 | LogInfo("Timeout downloading headers, %s\n", pto->DisconnectMsg(fLogIPs)); Line | Count | Source | 356 | 10 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 10 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
5850 | 10 | pto->fDisconnect = true; |
5851 | 10 | return true; |
5852 | 262 | } else { |
5853 | 262 | LogInfo("Timeout downloading headers from noban peer, not %s\n", pto->DisconnectMsg(fLogIPs)); Line | Count | Source | 356 | 262 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 350 | 262 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
5854 | | // Reset the headers sync state so that we have a |
5855 | | // chance to try downloading from a different peer. |
5856 | | // Note: this will also result in at least one more |
5857 | | // getheaders message to be sent to |
5858 | | // this peer (eventually). |
5859 | 262 | state.fSyncStarted = false; |
5860 | 262 | nSyncStarted--; |
5861 | 262 | peer->m_headers_sync_timeout = 0us; |
5862 | 262 | } |
5863 | 272 | } |
5864 | 319k | } else { |
5865 | | // After we've caught up once, reset the timeout so we can't trigger |
5866 | | // disconnect later. |
5867 | 30.4k | peer->m_headers_sync_timeout = std::chrono::microseconds::max(); |
5868 | 30.4k | } |
5869 | 349k | } |
5870 | | |
5871 | | // Check that outbound peers have reasonable chains |
5872 | | // GetTime() is used by this anti-DoS logic so we can test this using mocktime |
5873 | 5.81M | ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>()); |
5874 | | |
5875 | | // |
5876 | | // Message: getdata (blocks) |
5877 | | // |
5878 | 5.81M | std::vector<CInv> vGetData; |
5879 | 5.81M | if (CanServeBlocks(*peer) && (4.42M (4.42M sync_blocks_and_headers_from_peer4.42M && !IsLimitedPeer(*peer)4.42M ) || !m_chainman.IsInitialBlockDownload()3.97M ) && state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER4.18M ) { |
5880 | 4.08M | std::vector<const CBlockIndex*> vToDownload; |
5881 | 4.08M | NodeId staller = -1; |
5882 | 4.08M | auto get_inflight_budget = [&state]() { |
5883 | 4.08M | return std::max(0, MAX_BLOCKS_IN_TRANSIT_PER_PEER - static_cast<int>(state.vBlocksInFlight.size())); |
5884 | 4.08M | }; |
5885 | | |
5886 | | // If a snapshot chainstate is in use, we want to find its next blocks |
5887 | | // before the background chainstate to prioritize getting to network tip. |
5888 | 4.08M | FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload, staller); |
5889 | 4.08M | if (m_chainman.BackgroundSyncInProgress() && !IsLimitedPeer(*peer)0 ) { |
5890 | | // If the background tip is not an ancestor of the snapshot block, |
5891 | | // we need to start requesting blocks from their last common ancestor. |
5892 | 0 | const CBlockIndex *from_tip = LastCommonAncestor(m_chainman.GetBackgroundSyncTip(), m_chainman.GetSnapshotBaseBlock()); |
5893 | 0 | TryDownloadingHistoricalBlocks( |
5894 | 0 | *peer, |
5895 | 0 | get_inflight_budget(), |
5896 | 0 | vToDownload, from_tip, |
5897 | 0 | Assert(m_chainman.GetSnapshotBaseBlock())); Line | Count | Source | 106 | 0 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) |
|
5898 | 0 | } |
5899 | 4.08M | for (const CBlockIndex *pindex : vToDownload) { |
5900 | 5.43k | uint32_t nFetchFlags = GetFetchFlags(*peer); |
5901 | 5.43k | vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()); |
5902 | 5.43k | BlockRequested(pto->GetId(), *pindex); |
5903 | 5.43k | LogDebug(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), Line | Count | Source | 381 | 5.43k | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 5.43k | do { \ | 374 | 5.43k | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 5.43k | } while (0) |
|
|
5904 | 5.43k | pindex->nHeight, pto->GetId()); |
5905 | 5.43k | } |
5906 | 4.08M | if (state.vBlocksInFlight.empty() && staller != -11.42M ) { |
5907 | 0 | if (State(staller)->m_stalling_since == 0us) { |
5908 | 0 | State(staller)->m_stalling_since = current_time; |
5909 | 0 | LogDebug(BCLog::NET, "Stall started peer=%d\n", staller); Line | Count | Source | 381 | 0 | #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 373 | 0 | do { \ | 374 | 0 | if (LogAcceptCategory((category), (level))) { \ | 375 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 376 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 350 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
| 377 | 0 | } \ | 378 | 0 | } while (0) |
|
|
5910 | 0 | } |
5911 | 0 | } |
5912 | 4.08M | } |
5913 | | |
5914 | | // |
5915 | | // Message: getdata (transactions) |
5916 | | // |
5917 | 5.81M | { |
5918 | 5.81M | LOCK(m_tx_download_mutex); Line | Count | Source | 259 | 5.81M | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 5.81M | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 5.81M | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 5.81M | #define PASTE(x, y) x ## y |
|
|
|
|
5919 | 5.81M | for (const GenTxid& gtxid : m_txdownloadman.GetRequestsToSend(pto->GetId(), current_time)) { |
5920 | 0 | vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*peer)), gtxid.ToUint256()); |
5921 | 0 | if (vGetData.size() >= MAX_GETDATA_SZ) { |
5922 | 0 | MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData); |
5923 | 0 | vGetData.clear(); |
5924 | 0 | } |
5925 | 0 | } |
5926 | 5.81M | } |
5927 | | |
5928 | 5.81M | if (!vGetData.empty()) |
5929 | 5.31k | MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData); |
5930 | 5.81M | } // release cs_main |
5931 | 0 | MaybeSendFeefilter(*pto, *peer, current_time); |
5932 | 5.81M | return true; |
5933 | 5.81M | } |