/workdir/bitcoin/src/net_processing.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright (c) 2009-2010 Satoshi Nakamoto |
2 | | // Copyright (c) 2009-2022 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 <banman.h> |
10 | | #include <blockencodings.h> |
11 | | #include <blockfilter.h> |
12 | | #include <chainparams.h> |
13 | | #include <consensus/amount.h> |
14 | | #include <consensus/validation.h> |
15 | | #include <deploymentstatus.h> |
16 | | #include <hash.h> |
17 | | #include <headerssync.h> |
18 | | #include <index/blockfilterindex.h> |
19 | | #include <kernel/chain.h> |
20 | | #include <kernel/mempool_entry.h> |
21 | | #include <logging.h> |
22 | | #include <merkleblock.h> |
23 | | #include <netbase.h> |
24 | | #include <netmessagemaker.h> |
25 | | #include <node/blockstorage.h> |
26 | | #include <node/timeoffsets.h> |
27 | | #include <node/txreconciliation.h> |
28 | | #include <node/warnings.h> |
29 | | #include <policy/fees.h> |
30 | | #include <policy/policy.h> |
31 | | #include <policy/settings.h> |
32 | | #include <primitives/block.h> |
33 | | #include <primitives/transaction.h> |
34 | | #include <random.h> |
35 | | #include <reverse_iterator.h> |
36 | | #include <scheduler.h> |
37 | | #include <streams.h> |
38 | | #include <sync.h> |
39 | | #include <tinyformat.h> |
40 | | #include <txmempool.h> |
41 | | #include <txorphanage.h> |
42 | | #include <txrequest.h> |
43 | | #include <util/check.h> |
44 | | #include <util/strencodings.h> |
45 | | #include <util/time.h> |
46 | | #include <util/trace.h> |
47 | | #include <validation.h> |
48 | | |
49 | | #include <algorithm> |
50 | | #include <atomic> |
51 | | #include <future> |
52 | | #include <memory> |
53 | | #include <optional> |
54 | | #include <typeinfo> |
55 | | #include <utility> |
56 | | |
57 | | /** Headers download timeout. |
58 | | * Timeout = base + per_header * (expected number of headers) */ |
59 | | static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min; |
60 | | static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms; |
61 | | /** How long to wait for a peer to respond to a getheaders request */ |
62 | | static constexpr auto HEADERS_RESPONSE_TIME{2min}; |
63 | | /** Protect at least this many outbound peers from disconnection due to slow/ |
64 | | * behind headers chain. |
65 | | */ |
66 | | static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4; |
67 | | /** Timeout for (unprotected) outbound peers to sync to our chainwork */ |
68 | | static constexpr auto CHAIN_SYNC_TIMEOUT{20min}; |
69 | | /** How frequently to check for stale tips */ |
70 | | static constexpr auto STALE_CHECK_INTERVAL{10min}; |
71 | | /** How frequently to check for extra outbound peers and disconnect */ |
72 | | static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s}; |
73 | | /** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */ |
74 | | static constexpr auto MINIMUM_CONNECT_TIME{30s}; |
75 | | /** SHA256("main address relay")[0:8] */ |
76 | | static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; |
77 | | /// Age after which a stale block will no longer be served if requested as |
78 | | /// protection against fingerprinting. Set to one month, denominated in seconds. |
79 | | static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60; |
80 | | /// Age after which a block is considered historical for purposes of rate |
81 | | /// limiting block relay. Set to one week, denominated in seconds. |
82 | | static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60; |
83 | | /** Time between pings automatically sent out for latency probing and keepalive */ |
84 | | static constexpr auto PING_INTERVAL{2min}; |
85 | | /** The maximum number of entries in a locator */ |
86 | | static const unsigned int MAX_LOCATOR_SZ = 101; |
87 | | /** The maximum number of entries in an 'inv' protocol message */ |
88 | | static const unsigned int MAX_INV_SZ = 50000; |
89 | | /** Maximum number of in-flight transaction requests from a peer. It is not a hard limit, but the threshold at which |
90 | | * point the OVERLOADED_PEER_TX_DELAY kicks in. */ |
91 | | static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT = 100; |
92 | | /** Maximum number of transactions to consider for requesting, per peer. It provides a reasonable DoS limit to |
93 | | * per-peer memory usage spent on announcements, while covering peers continuously sending INVs at the maximum |
94 | | * rate (by our own policy, see INVENTORY_BROADCAST_PER_SECOND) for several minutes, while not receiving |
95 | | * the actual transaction (from any peer) in response to requests for them. */ |
96 | | static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 5000; |
97 | | /** How long to delay requesting transactions via txids, if we have wtxid-relaying peers */ |
98 | | static constexpr auto TXID_RELAY_DELAY{2s}; |
99 | | /** How long to delay requesting transactions from non-preferred peers */ |
100 | | static constexpr auto NONPREF_PEER_TX_DELAY{2s}; |
101 | | /** How long to delay requesting transactions from overloaded peers (see MAX_PEER_TX_REQUEST_IN_FLIGHT). */ |
102 | | static constexpr auto OVERLOADED_PEER_TX_DELAY{2s}; |
103 | | /** How long to wait before downloading a transaction from an additional peer */ |
104 | | static constexpr auto GETDATA_TX_INTERVAL{60s}; |
105 | | /** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */ |
106 | | static const unsigned int MAX_GETDATA_SZ = 1000; |
107 | | /** Number of blocks that can be requested at any given time from a single peer. */ |
108 | | static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16; |
109 | | /** Default time during which a peer must stall block download progress before being disconnected. |
110 | | * the actual timeout is increased temporarily if peers are disconnected for hitting the timeout */ |
111 | | static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT{2s}; |
112 | | /** Maximum timeout for stalling block download. */ |
113 | | static constexpr auto BLOCK_STALLING_TIMEOUT_MAX{64s}; |
114 | | /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends |
115 | | * less than this number, we reached its tip. Changing this value is a protocol upgrade. */ |
116 | | static const unsigned int MAX_HEADERS_RESULTS = 2000; |
117 | | /** Maximum depth of blocks we're willing to serve as compact blocks to peers |
118 | | * when requested. For older blocks, a regular BLOCK response will be sent. */ |
119 | | static const int MAX_CMPCTBLOCK_DEPTH = 5; |
120 | | /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */ |
121 | | static const int MAX_BLOCKTXN_DEPTH = 10; |
122 | | static_assert(MAX_BLOCKTXN_DEPTH <= MIN_BLOCKS_TO_KEEP, "MAX_BLOCKTXN_DEPTH too high"); |
123 | | /** Size of the "block download window": how far ahead of our current height do we fetch? |
124 | | * Larger windows tolerate larger download speed differences between peer, but increase the potential |
125 | | * degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably |
126 | | * want to make this a per-peer adaptive value at some point. */ |
127 | | static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024; |
128 | | /** Block download timeout base, expressed in multiples of the block interval (i.e. 10 min) */ |
129 | | static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1; |
130 | | /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */ |
131 | | static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5; |
132 | | /** Maximum number of headers to announce when relaying blocks with headers message.*/ |
133 | | static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8; |
134 | | /** Minimum blocks required to signal NODE_NETWORK_LIMITED */ |
135 | | static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288; |
136 | | /** Window, in blocks, for connecting to NODE_NETWORK_LIMITED peers */ |
137 | | static const unsigned int NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS = 144; |
138 | | /** Average delay between local address broadcasts */ |
139 | | static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h}; |
140 | | /** Average delay between peer address broadcasts */ |
141 | | static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s}; |
142 | | /** Delay between rotating the peers we relay a particular address to */ |
143 | | static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h}; |
144 | | /** Average delay between trickled inventory transmissions for inbound peers. |
145 | | * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */ |
146 | | static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s}; |
147 | | /** Average delay between trickled inventory transmissions for outbound peers. |
148 | | * Use a smaller delay as there is less privacy concern for them. |
149 | | * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */ |
150 | | static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s}; |
151 | | /** Maximum rate of inventory items to send per second. |
152 | | * Limits the impact of low-fee transaction floods. */ |
153 | | static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7; |
154 | | /** Target number of tx inventory items to send per transmission. */ |
155 | | static constexpr unsigned int INVENTORY_BROADCAST_TARGET = INVENTORY_BROADCAST_PER_SECOND * count_seconds(INBOUND_INVENTORY_BROADCAST_INTERVAL); |
156 | | /** Maximum number of inventory items to send per transmission. */ |
157 | | static constexpr unsigned int INVENTORY_BROADCAST_MAX = 1000; |
158 | | static_assert(INVENTORY_BROADCAST_MAX >= INVENTORY_BROADCAST_TARGET, "INVENTORY_BROADCAST_MAX too low"); |
159 | | static_assert(INVENTORY_BROADCAST_MAX <= MAX_PEER_TX_ANNOUNCEMENTS, "INVENTORY_BROADCAST_MAX too high"); |
160 | | /** Average delay between feefilter broadcasts in seconds. */ |
161 | | static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min}; |
162 | | /** Maximum feefilter broadcast delay after significant change. */ |
163 | | static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min}; |
164 | | /** Maximum number of compact filters that may be requested with one getcfilters. See BIP 157. */ |
165 | | static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000; |
166 | | /** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */ |
167 | | static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000; |
168 | | /** the maximum percentage of addresses from our addrman to return in response to a getaddr message. */ |
169 | | static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23; |
170 | | /** The maximum number of address records permitted in an ADDR message. */ |
171 | | static constexpr size_t MAX_ADDR_TO_SEND{1000}; |
172 | | /** The maximum rate of address records we're willing to process on average. Can be bypassed using |
173 | | * the NetPermissionFlags::Addr permission. */ |
174 | | static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1}; |
175 | | /** The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND |
176 | | * based increments won't go above this, but the MAX_ADDR_TO_SEND increment following GETADDR |
177 | | * is exempt from this limit). */ |
178 | | static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND}; |
179 | | /** The compactblocks version we support. See BIP 152. */ |
180 | | static constexpr uint64_t CMPCTBLOCKS_VERSION{2}; |
181 | | |
182 | | // Internal stuff |
183 | | namespace { |
184 | | /** Blocks that are in flight, and that are in the queue to be downloaded. */ |
185 | | struct QueuedBlock { |
186 | | /** BlockIndex. We must have this since we only request blocks when we've already validated the header. */ |
187 | | const CBlockIndex* pindex; |
188 | | /** Optional, used for CMPCTBLOCK downloads */ |
189 | | std::unique_ptr<PartiallyDownloadedBlock> partialBlock; |
190 | | }; |
191 | | |
192 | | /** |
193 | | * Data structure for an individual peer. This struct is not protected by |
194 | | * cs_main since it does not contain validation-critical data. |
195 | | * |
196 | | * Memory is owned by shared pointers and this object is destructed when |
197 | | * the refcount drops to zero. |
198 | | * |
199 | | * Mutexes inside this struct must not be held when locking m_peer_mutex. |
200 | | * |
201 | | * TODO: move most members from CNodeState to this structure. |
202 | | * TODO: move remaining application-layer data members from CNode to this structure. |
203 | | */ |
204 | | struct Peer { |
205 | | /** Same id as the CNode object for this peer */ |
206 | | const NodeId m_id{0}; |
207 | | |
208 | | /** Services we offered to this peer. |
209 | | * |
210 | | * This is supplied by CConnman during peer initialization. It's const |
211 | | * because there is no protocol defined for renegotiating services |
212 | | * initially offered to a peer. The set of local services we offer should |
213 | | * not change after initialization. |
214 | | * |
215 | | * An interesting example of this is NODE_NETWORK and initial block |
216 | | * download: a node which starts up from scratch doesn't have any blocks |
217 | | * to serve, but still advertises NODE_NETWORK because it will eventually |
218 | | * fulfill this role after IBD completes. P2P code is written in such a |
219 | | * way that it can gracefully handle peers who don't make good on their |
220 | | * service advertisements. */ |
221 | | const ServiceFlags m_our_services; |
222 | | /** Services this peer offered to us. */ |
223 | | std::atomic<ServiceFlags> m_their_services{NODE_NONE}; |
224 | | |
225 | | /** Protects misbehavior data members */ |
226 | | Mutex m_misbehavior_mutex; |
227 | | /** Whether this peer should be disconnected and marked as discouraged (unless it has NetPermissionFlags::NoBan permission). */ |
228 | | bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false}; |
229 | | |
230 | | /** Protects block inventory data members */ |
231 | | Mutex m_block_inv_mutex; |
232 | | /** List of blocks that we'll announce via an `inv` message. |
233 | | * There is no final sorting before sending, as they are always sent |
234 | | * immediately and in the order requested. */ |
235 | | std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex); |
236 | | /** Unfiltered list of blocks that we'd like to announce via a `headers` |
237 | | * message. If we can't announce via a `headers` message, we'll fall back to |
238 | | * announcing via `inv`. */ |
239 | | std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex); |
240 | | /** The final block hash that we sent in an `inv` message to this peer. |
241 | | * When the peer requests this block, we send an `inv` message to trigger |
242 | | * the peer to request the next sequence of block hashes. |
243 | | * Most peers use headers-first syncing, which doesn't use this mechanism */ |
244 | | uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {}; |
245 | | |
246 | | /** This peer's reported block height when we connected */ |
247 | | std::atomic<int> m_starting_height{-1}; |
248 | | |
249 | | /** The pong reply we're expecting, or 0 if no pong expected. */ |
250 | | std::atomic<uint64_t> m_ping_nonce_sent{0}; |
251 | | /** When the last ping was sent, or 0 if no ping was ever sent */ |
252 | | std::atomic<std::chrono::microseconds> m_ping_start{0us}; |
253 | | /** Whether a ping has been requested by the user */ |
254 | | std::atomic<bool> m_ping_queued{false}; |
255 | | |
256 | | /** Whether this peer relays txs via wtxid */ |
257 | | std::atomic<bool> m_wtxid_relay{false}; |
258 | | /** The feerate in the most recent BIP133 `feefilter` message sent to the peer. |
259 | | * It is *not* a p2p protocol violation for the peer to send us |
260 | | * transactions with a lower fee rate than this. See BIP133. */ |
261 | | CAmount m_fee_filter_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0}; |
262 | | /** Timestamp after which we will send the next BIP133 `feefilter` message |
263 | | * to the peer. */ |
264 | | std::chrono::microseconds m_next_send_feefilter GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0}; |
265 | | |
266 | | struct TxRelay { |
267 | | mutable RecursiveMutex m_bloom_filter_mutex; |
268 | | /** Whether we relay transactions to this peer. */ |
269 | | bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false}; |
270 | | /** A bloom filter for which transactions to announce to the peer. See BIP37. */ |
271 | | std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr}; |
272 | | |
273 | | mutable RecursiveMutex m_tx_inventory_mutex; |
274 | | /** A filter of all the (w)txids that the peer has announced to |
275 | | * us or we have announced to the peer. We use this to avoid announcing |
276 | | * the same (w)txid to a peer that already has the transaction. */ |
277 | | CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001}; |
278 | | /** Set of transaction ids we still have to announce (txid for |
279 | | * non-wtxid-relay peers, wtxid for wtxid-relay peers). We use the |
280 | | * mempool to sort transactions in dependency order before relay, so |
281 | | * this does not have to be sorted. */ |
282 | | std::set<uint256> m_tx_inventory_to_send GUARDED_BY(m_tx_inventory_mutex); |
283 | | /** Whether the peer has requested us to send our complete mempool. Only |
284 | | * permitted if the peer has NetPermissionFlags::Mempool or we advertise |
285 | | * NODE_BLOOM. See BIP35. */ |
286 | | bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false}; |
287 | | /** The next time after which we will send an `inv` message containing |
288 | | * transaction announcements to this peer. */ |
289 | | std::chrono::microseconds m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){0}; |
290 | | /** The mempool sequence num at which we sent the last `inv` message to this peer. |
291 | | * Can relay txs with lower sequence numbers than this (see CTxMempool::info_for_relay). */ |
292 | | uint64_t m_last_inv_sequence GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1}; |
293 | | |
294 | | /** Minimum fee rate with which to filter transaction announcements to this node. See BIP133. */ |
295 | | std::atomic<CAmount> m_fee_filter_received{0}; |
296 | | }; |
297 | | |
298 | | /* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */ |
299 | | TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) |
300 | 331 | { |
301 | 331 | LOCK(m_tx_relay_mutex); |
302 | 331 | Assume(!m_tx_relay); |
303 | 331 | m_tx_relay = std::make_unique<Peer::TxRelay>(); |
304 | 331 | return m_tx_relay.get(); |
305 | 331 | }; |
306 | | |
307 | | TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) |
308 | 982 | { |
309 | 982 | return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get()); |
310 | 982 | }; |
311 | | |
312 | | /** A vector of addresses to send to the peer, limited to MAX_ADDR_TO_SEND. */ |
313 | | std::vector<CAddress> m_addrs_to_send GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
314 | | /** Probabilistic filter to track recent addr messages relayed with this |
315 | | * peer. Used to avoid relaying redundant addresses to this peer. |
316 | | * |
317 | | * We initialize this filter for outbound peers (other than |
318 | | * block-relay-only connections) or when an inbound peer sends us an |
319 | | * address related message (ADDR, ADDRV2, GETADDR). |
320 | | * |
321 | | * Presence of this filter must correlate with m_addr_relay_enabled. |
322 | | **/ |
323 | | std::unique_ptr<CRollingBloomFilter> m_addr_known GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
324 | | /** Whether we are participating in address relay with this connection. |
325 | | * |
326 | | * We set this bool to true for outbound peers (other than |
327 | | * block-relay-only connections), or when an inbound peer sends us an |
328 | | * address related message (ADDR, ADDRV2, GETADDR). |
329 | | * |
330 | | * We use this bool to decide whether a peer is eligible for gossiping |
331 | | * addr messages. This avoids relaying to peers that are unlikely to |
332 | | * forward them, effectively blackholing self announcements. Reasons |
333 | | * peers might support addr relay on the link include that they connected |
334 | | * to us as a block-relay-only peer or they are a light client. |
335 | | * |
336 | | * This field must correlate with whether m_addr_known has been |
337 | | * initialized.*/ |
338 | | std::atomic_bool m_addr_relay_enabled{false}; |
339 | | /** Whether a getaddr request to this peer is outstanding. */ |
340 | | bool m_getaddr_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
341 | | /** Guards address sending timers. */ |
342 | | mutable Mutex m_addr_send_times_mutex; |
343 | | /** Time point to send the next ADDR message to this peer. */ |
344 | | std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0}; |
345 | | /** Time point to possibly re-announce our local address to this peer. */ |
346 | | std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0}; |
347 | | /** Whether the peer has signaled support for receiving ADDRv2 (BIP155) |
348 | | * messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */ |
349 | | std::atomic_bool m_wants_addrv2{false}; |
350 | | /** Whether this peer has already sent us a getaddr message. */ |
351 | | bool m_getaddr_recvd GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
352 | | /** Number of addresses that can be processed from this peer. Start at 1 to |
353 | | * permit self-announcement. */ |
354 | | double m_addr_token_bucket GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1.0}; |
355 | | /** When m_addr_token_bucket was last updated */ |
356 | | std::chrono::microseconds m_addr_token_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){GetTime<std::chrono::microseconds>()}; |
357 | | /** Total number of addresses that were dropped due to rate limiting. */ |
358 | | std::atomic<uint64_t> m_addr_rate_limited{0}; |
359 | | /** Total number of addresses that were processed (excludes rate-limited ones). */ |
360 | | std::atomic<uint64_t> m_addr_processed{0}; |
361 | | |
362 | | /** Whether we've sent this peer a getheaders in response to an inv prior to initial-headers-sync completing */ |
363 | | bool m_inv_triggered_getheaders_before_sync GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
364 | | |
365 | | /** Protects m_getdata_requests **/ |
366 | | Mutex m_getdata_requests_mutex; |
367 | | /** Work queue of items requested by this peer **/ |
368 | | std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex); |
369 | | |
370 | | /** Time of the last getheaders message to this peer */ |
371 | | NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){}; |
372 | | |
373 | | /** Protects m_headers_sync **/ |
374 | | Mutex m_headers_sync_mutex; |
375 | | /** Headers-sync state for this peer (eg for initial sync, or syncing large |
376 | | * reorgs) **/ |
377 | | std::unique_ptr<HeadersSyncState> m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex) GUARDED_BY(m_headers_sync_mutex) {}; |
378 | | |
379 | | /** Whether we've sent our peer a sendheaders message. **/ |
380 | | std::atomic<bool> m_sent_sendheaders{false}; |
381 | | |
382 | | /** When to potentially disconnect peer for stalling headers download */ |
383 | | std::chrono::microseconds m_headers_sync_timeout GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0us}; |
384 | | |
385 | | /** Whether this peer wants invs or headers (when possible) for block announcements */ |
386 | | bool m_prefers_headers GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; |
387 | | |
388 | | /** Time offset computed during the version handshake based on the |
389 | | * timestamp the peer sent in the version message. */ |
390 | | std::atomic<std::chrono::seconds> m_time_offset{0s}; |
391 | | |
392 | | explicit Peer(NodeId id, ServiceFlags our_services) |
393 | 1.01k | : m_id{id} |
394 | 1.01k | , m_our_services{our_services} |
395 | 1.01k | {} |
396 | | |
397 | | private: |
398 | | mutable Mutex m_tx_relay_mutex; |
399 | | |
400 | | /** Transaction relay data. May be a nullptr. */ |
401 | | std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex); |
402 | | }; |
403 | | |
404 | | using PeerRef = std::shared_ptr<Peer>; |
405 | | |
406 | | /** |
407 | | * Maintain validation-specific state about nodes, protected by cs_main, instead |
408 | | * by CNode's own locks. This simplifies asynchronous operation, where |
409 | | * processing of incoming data is done after the ProcessMessage call returns, |
410 | | * and we're no longer holding the node's locks. |
411 | | */ |
412 | | struct CNodeState { |
413 | | //! The best known block we know this peer has announced. |
414 | | const CBlockIndex* pindexBestKnownBlock{nullptr}; |
415 | | //! The hash of the last unknown block this peer has announced. |
416 | | uint256 hashLastUnknownBlock{}; |
417 | | //! The last full block we both have. |
418 | | const CBlockIndex* pindexLastCommonBlock{nullptr}; |
419 | | //! The best header we have sent our peer. |
420 | | const CBlockIndex* pindexBestHeaderSent{nullptr}; |
421 | | //! Whether we've started headers synchronization with this peer. |
422 | | bool fSyncStarted{false}; |
423 | | //! Since when we're stalling block download progress (in microseconds), or 0. |
424 | | std::chrono::microseconds m_stalling_since{0us}; |
425 | | std::list<QueuedBlock> vBlocksInFlight; |
426 | | //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty. |
427 | | std::chrono::microseconds m_downloading_since{0us}; |
428 | | //! Whether we consider this a preferred download peer. |
429 | | bool fPreferredDownload{false}; |
430 | | /** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */ |
431 | | bool m_requested_hb_cmpctblocks{false}; |
432 | | /** Whether this peer will send us cmpctblocks if we request them. */ |
433 | | bool m_provides_cmpctblocks{false}; |
434 | | |
435 | | /** State used to enforce CHAIN_SYNC_TIMEOUT and EXTRA_PEER_CHECK_INTERVAL logic. |
436 | | * |
437 | | * Both are only in effect for outbound, non-manual, non-protected connections. |
438 | | * Any peer protected (m_protect = true) is not chosen for eviction. A peer is |
439 | | * marked as protected if all of these are true: |
440 | | * - its connection type is IsBlockOnlyConn() == false |
441 | | * - it gave us a valid connecting header |
442 | | * - we haven't reached MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT yet |
443 | | * - its chain tip has at least as much work as ours |
444 | | * |
445 | | * CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip, |
446 | | * set a timeout CHAIN_SYNC_TIMEOUT in the future: |
447 | | * - If at timeout their best known block now has more work than our tip |
448 | | * when the timeout was set, then either reset the timeout or clear it |
449 | | * (after comparing against our current tip's work) |
450 | | * - If at timeout their best known block still has less work than our |
451 | | * tip did when the timeout was set, then send a getheaders message, |
452 | | * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future. |
453 | | * If their best known block is still behind when that new timeout is |
454 | | * reached, disconnect. |
455 | | * |
456 | | * EXTRA_PEER_CHECK_INTERVAL: after each interval, if we have too many outbound peers, |
457 | | * drop the outbound one that least recently announced us a new block. |
458 | | */ |
459 | | struct ChainSyncTimeoutState { |
460 | | //! A timeout used for checking whether our peer has sufficiently synced |
461 | | std::chrono::seconds m_timeout{0s}; |
462 | | //! A header with the work we require on our peer's chain |
463 | | const CBlockIndex* m_work_header{nullptr}; |
464 | | //! After timeout is reached, set to true after sending getheaders |
465 | | bool m_sent_getheaders{false}; |
466 | | //! Whether this peer is protected from disconnection due to a bad/slow chain |
467 | | bool m_protect{false}; |
468 | | }; |
469 | | |
470 | | ChainSyncTimeoutState m_chain_sync; |
471 | | |
472 | | //! Time of last new block announcement |
473 | | int64_t m_last_block_announcement{0}; |
474 | | |
475 | | //! Whether this peer is an inbound connection |
476 | | const bool m_is_inbound; |
477 | | |
478 | 1.01k | CNodeState(bool is_inbound) : m_is_inbound(is_inbound) {} |
479 | | }; |
480 | | |
481 | | class PeerManagerImpl final : public PeerManager |
482 | | { |
483 | | public: |
484 | | PeerManagerImpl(CConnman& connman, AddrMan& addrman, |
485 | | BanMan* banman, ChainstateManager& chainman, |
486 | | CTxMemPool& pool, node::Warnings& warnings, Options opts); |
487 | | |
488 | | /** Overridden from CValidationInterface. */ |
489 | | void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override |
490 | | EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex); |
491 | | void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override |
492 | | EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex); |
493 | | void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override |
494 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
495 | | void BlockChecked(const CBlock& block, const BlockValidationState& state) override |
496 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
497 | | void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override |
498 | | EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex); |
499 | | |
500 | | /** Implement NetEventsInterface */ |
501 | | void InitializeNode(CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
502 | | void FinalizeNode(const CNode& node) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex); |
503 | | bool HasAllDesirableServiceFlags(ServiceFlags services) const override; |
504 | | bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override |
505 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
506 | | bool SendMessages(CNode* pto) override |
507 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, g_msgproc_mutex); |
508 | | |
509 | | /** Implement PeerManager */ |
510 | | void StartScheduledTasks(CScheduler& scheduler) override; |
511 | | void CheckForStaleTipAndEvictPeers() override; |
512 | | std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) override |
513 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
514 | | bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
515 | | PeerManagerInfo GetInfo() const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
516 | | void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
517 | | void RelayTransaction(const uint256& txid, const uint256& wtxid) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
518 | | void SetBestBlock(int height, std::chrono::seconds time) override |
519 | 0 | { |
520 | 0 | m_best_height = height; |
521 | 0 | m_best_block_time = time; |
522 | 0 | }; |
523 | 0 | void UnitTestMisbehaving(NodeId peer_id) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), ""); }; |
524 | | void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, |
525 | | const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override |
526 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
527 | | void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override; |
528 | | ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const override; |
529 | | |
530 | | private: |
531 | | /** Consider evicting an outbound peer based on the amount of time they've been behind our tip */ |
532 | | void ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_msgproc_mutex); |
533 | | |
534 | | /** If we have extra outbound peers, try to disconnect the one with the oldest block announcement */ |
535 | | void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
536 | | |
537 | | /** Retrieve unbroadcast transactions from the mempool and reattempt sending to peers */ |
538 | | void ReattemptInitialBroadcast(CScheduler& scheduler) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
539 | | |
540 | | /** Get a shared pointer to the Peer object. |
541 | | * May return an empty shared_ptr if the Peer object can't be found. */ |
542 | | PeerRef GetPeerRef(NodeId id) const EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
543 | | |
544 | | /** Get a shared pointer to the Peer object and remove it from m_peer_map. |
545 | | * May return an empty shared_ptr if the Peer object can't be found. */ |
546 | | PeerRef RemovePeer(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
547 | | |
548 | | /** Mark a peer as misbehaving, which will cause it to be disconnected and its |
549 | | * address discouraged. */ |
550 | | void Misbehaving(Peer& peer, const std::string& message); |
551 | | |
552 | | /** |
553 | | * Potentially mark a node discouraged based on the contents of a BlockValidationState object |
554 | | * |
555 | | * @param[in] via_compact_block this bool is passed in because net_processing should |
556 | | * punish peers differently depending on whether the data was provided in a compact |
557 | | * block message or not. If the compact block had a valid header, but contained invalid |
558 | | * txs, the peer should not be punished. See BIP 152. |
559 | | */ |
560 | | void MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state, |
561 | | bool via_compact_block, const std::string& message = "") |
562 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
563 | | |
564 | | /** |
565 | | * Potentially disconnect and discourage a node based on the contents of a TxValidationState object |
566 | | */ |
567 | | void MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state) |
568 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); |
569 | | |
570 | | /** Maybe disconnect a peer and discourage future connections from its address. |
571 | | * |
572 | | * @param[in] pnode The node to check. |
573 | | * @param[in] peer The peer object to check. |
574 | | * @return True if the peer was marked for disconnection in this function |
575 | | */ |
576 | | bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer); |
577 | | |
578 | | /** Handle a transaction whose result was not MempoolAcceptResult::ResultType::VALID. |
579 | | * @param[in] maybe_add_extra_compact_tx Whether this tx should be added to vExtraTxnForCompact. |
580 | | * Set to false if the tx has already been rejected before, |
581 | | * e.g. is an orphan, to avoid adding duplicate entries. |
582 | | * Updates m_txrequest, m_recent_rejects, m_recent_rejects_reconsiderable, m_orphanage, and vExtraTxnForCompact. */ |
583 | | void ProcessInvalidTx(NodeId nodeid, const CTransactionRef& tx, const TxValidationState& result, |
584 | | bool maybe_add_extra_compact_tx) |
585 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main); |
586 | | |
587 | | /** Handle a transaction whose result was MempoolAcceptResult::ResultType::VALID. |
588 | | * Updates m_txrequest, m_orphanage, and vExtraTxnForCompact. Also queues the tx for relay. */ |
589 | | void ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions) |
590 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main); |
591 | | |
592 | | struct PackageToValidate { |
593 | | const Package m_txns; |
594 | | const std::vector<NodeId> m_senders; |
595 | | /** Construct a 1-parent-1-child package. */ |
596 | | explicit PackageToValidate(const CTransactionRef& parent, |
597 | | const CTransactionRef& child, |
598 | | NodeId parent_sender, |
599 | | NodeId child_sender) : |
600 | 0 | m_txns{parent, child}, |
601 | 0 | m_senders {parent_sender, child_sender} |
602 | 0 | {} |
603 | | |
604 | 0 | std::string ToString() const { |
605 | 0 | Assume(m_txns.size() == 2); |
606 | 0 | return strprintf("parent %s (wtxid=%s, sender=%d) + child %s (wtxid=%s, sender=%d)", |
607 | 0 | m_txns.front()->GetHash().ToString(), |
608 | 0 | m_txns.front()->GetWitnessHash().ToString(), |
609 | 0 | m_senders.front(), |
610 | 0 | m_txns.back()->GetHash().ToString(), |
611 | 0 | m_txns.back()->GetWitnessHash().ToString(), |
612 | 0 | m_senders.back()); |
613 | 0 | } |
614 | | }; |
615 | | |
616 | | /** Handle the results of package validation: calls ProcessValidTx and ProcessInvalidTx for |
617 | | * individual transactions, and caches rejection for the package as a group. |
618 | | */ |
619 | | void ProcessPackageResult(const PackageToValidate& package_to_validate, const PackageMempoolAcceptResult& package_result) |
620 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main); |
621 | | |
622 | | /** Look for a child of this transaction in the orphanage to form a 1-parent-1-child package, |
623 | | * skipping any combinations that have already been tried. Return the resulting package along with |
624 | | * the senders of its respective transactions, or std::nullopt if no package is found. */ |
625 | | std::optional<PackageToValidate> Find1P1CPackage(const CTransactionRef& ptx, NodeId nodeid) |
626 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main); |
627 | | |
628 | | /** |
629 | | * Reconsider orphan transactions after a parent has been accepted to the mempool. |
630 | | * |
631 | | * @peer[in] peer The peer whose orphan transactions we will reconsider. Generally only |
632 | | * one orphan will be reconsidered on each call of this function. If an |
633 | | * accepted orphan has orphaned children, those will need to be |
634 | | * reconsidered, creating more work, possibly for other peers. |
635 | | * @return True if meaningful work was done (an orphan was accepted/rejected). |
636 | | * If no meaningful work was done, then the work set for this peer |
637 | | * will be empty. |
638 | | */ |
639 | | bool ProcessOrphanTx(Peer& peer) |
640 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex); |
641 | | |
642 | | /** Process a single headers message from a peer. |
643 | | * |
644 | | * @param[in] pfrom CNode of the peer |
645 | | * @param[in] peer The peer sending us the headers |
646 | | * @param[in] headers The headers received. Note that this may be modified within ProcessHeadersMessage. |
647 | | * @param[in] via_compact_block Whether this header came in via compact block handling. |
648 | | */ |
649 | | void ProcessHeadersMessage(CNode& pfrom, Peer& peer, |
650 | | std::vector<CBlockHeader>&& headers, |
651 | | bool via_compact_block) |
652 | | EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
653 | | /** Various helpers for headers processing, invoked by ProcessHeadersMessage() */ |
654 | | /** Return true if headers are continuous and have valid proof-of-work (DoS points assigned on failure) */ |
655 | | bool CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer); |
656 | | /** Calculate an anti-DoS work threshold for headers chains */ |
657 | | arith_uint256 GetAntiDoSWorkThreshold(); |
658 | | /** Deal with state tracking and headers sync for peers that send |
659 | | * non-connecting headers (this can happen due to BIP 130 headers |
660 | | * announcements for blocks interacting with the 2hr (MAX_FUTURE_BLOCK_TIME) rule). */ |
661 | | void HandleUnconnectingHeaders(CNode& pfrom, Peer& peer, const std::vector<CBlockHeader>& headers) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
662 | | /** Return true if the headers connect to each other, false otherwise */ |
663 | | bool CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const; |
664 | | /** Try to continue a low-work headers sync that has already begun. |
665 | | * Assumes the caller has already verified the headers connect, and has |
666 | | * checked that each header satisfies the proof-of-work target included in |
667 | | * the header. |
668 | | * @param[in] peer The peer we're syncing with. |
669 | | * @param[in] pfrom CNode of the peer |
670 | | * @param[in,out] headers The headers to be processed. |
671 | | * @return True if the passed in headers were successfully processed |
672 | | * as the continuation of a low-work headers sync in progress; |
673 | | * false otherwise. |
674 | | * If false, the passed in headers will be returned back to |
675 | | * the caller. |
676 | | * If true, the returned headers may be empty, indicating |
677 | | * there is no more work for the caller to do; or the headers |
678 | | * may be populated with entries that have passed anti-DoS |
679 | | * checks (and therefore may be validated for block index |
680 | | * acceptance by the caller). |
681 | | */ |
682 | | bool IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, |
683 | | std::vector<CBlockHeader>& headers) |
684 | | EXCLUSIVE_LOCKS_REQUIRED(peer.m_headers_sync_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
685 | | /** Check work on a headers chain to be processed, and if insufficient, |
686 | | * initiate our anti-DoS headers sync mechanism. |
687 | | * |
688 | | * @param[in] peer The peer whose headers we're processing. |
689 | | * @param[in] pfrom CNode of the peer |
690 | | * @param[in] chain_start_header Where these headers connect in our index. |
691 | | * @param[in,out] headers The headers to be processed. |
692 | | * |
693 | | * @return True if chain was low work (headers will be empty after |
694 | | * calling); false otherwise. |
695 | | */ |
696 | | bool TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, |
697 | | const CBlockIndex* chain_start_header, |
698 | | std::vector<CBlockHeader>& headers) |
699 | | EXCLUSIVE_LOCKS_REQUIRED(!peer.m_headers_sync_mutex, !m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex); |
700 | | |
701 | | /** Return true if the given header is an ancestor of |
702 | | * m_chainman.m_best_header or our current tip */ |
703 | | bool IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
704 | | |
705 | | /** Request further headers from this peer with a given locator. |
706 | | * We don't issue a getheaders message if we have a recent one outstanding. |
707 | | * This returns true if a getheaders is actually sent, and false otherwise. |
708 | | */ |
709 | | bool MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
710 | | /** Potentially fetch blocks from this peer upon receipt of a new headers tip */ |
711 | | void HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header); |
712 | | /** Update peer state based on received headers message */ |
713 | | void UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers) |
714 | | EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
715 | | |
716 | | void SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req); |
717 | | |
718 | | /** Register with TxRequestTracker that an INV has been received from a |
719 | | * peer. The announcement parameters are decided in PeerManager and then |
720 | | * passed to TxRequestTracker. */ |
721 | | void AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time) |
722 | | EXCLUSIVE_LOCKS_REQUIRED(::cs_main); |
723 | | |
724 | | /** Send a message to a peer */ |
725 | 0 | void PushMessage(CNode& node, CSerializedNetMsg&& msg) const { m_connman.PushMessage(&node, std::move(msg)); } |
726 | | template <typename... Args> |
727 | | void MakeAndPushMessage(CNode& node, std::string msg_type, Args&&... args) const |
728 | 3.02k | { |
729 | 3.02k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); |
730 | 3.02k | } net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<bool, unsigned long const&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool&&, unsigned long const&) const Line | Count | Source | 728 | 157 | { | 729 | 157 | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 157 | } |
Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<std::vector<CInv, std::allocator<CInv> >&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<CInv, std::allocator<CInv> >&) const net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<int const&, unsigned long&, long const&, unsigned long&, ParamsWrapper<CNetAddr::SerParams, CService>, unsigned long&, ParamsWrapper<CNetAddr::SerParams, CService>, unsigned long&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int const&, bool const&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int const&, unsigned long&, long const&, unsigned long&, ParamsWrapper<CNetAddr::SerParams, CService>&&, unsigned long&, ParamsWrapper<CNetAddr::SerParams, CService>&&, unsigned long&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int const&, bool const&) const Line | Count | Source | 728 | 781 | { | 729 | 781 | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 781 | } |
net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) const Line | Count | Source | 728 | 1.46k | { | 729 | 1.46k | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 1.46k | } |
net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<unsigned int const&, unsigned long const&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, unsigned int const&, unsigned long const&) const Line | Count | Source | 728 | 264 | { | 729 | 264 | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 264 | } |
net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<Span<unsigned char const> >(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Span<unsigned char const>&&) const Line | Count | Source | 728 | 35 | { | 729 | 35 | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 35 | } |
net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<CBlockLocator const&, uint256>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, CBlockLocator const&, uint256&&) const Line | Count | Source | 728 | 85 | { | 729 | 85 | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 85 | } |
Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<ParamsWrapper<TransactionSerParams, CTransaction const> >(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, ParamsWrapper<TransactionSerParams, CTransaction const>&&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<Span<unsigned char> >(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Span<unsigned char>&&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<ParamsWrapper<TransactionSerParams, CBlock const> >(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, ParamsWrapper<TransactionSerParams, CBlock const>&&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<CMerkleBlock&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, CMerkleBlock&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<CBlockHeaderAndShortTxIDs const&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, CBlockHeaderAndShortTxIDs const&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<CBlockHeaderAndShortTxIDs&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, CBlockHeaderAndShortTxIDs&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<BlockTransactions&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, BlockTransactions&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<std::vector<CBlockHeader, std::allocator<CBlockHeader> > >(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<CBlockHeader, std::allocator<CBlockHeader> >&&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<ParamsWrapper<TransactionSerParams, std::vector<CBlock, std::allocator<CBlock> > > >(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, ParamsWrapper<TransactionSerParams, std::vector<CBlock, std::allocator<CBlock> > >&&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<BlockTransactionsRequest&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, BlockTransactionsRequest&) const net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<unsigned long&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, unsigned long&) const Line | Count | Source | 728 | 139 | { | 729 | 139 | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 139 | } |
Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<BlockFilter const&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, BlockFilter const&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<unsigned char&, uint256, uint256&, std::vector<uint256, std::allocator<uint256> >&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, unsigned char&, uint256&&, uint256&, std::vector<uint256, std::allocator<uint256> >&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<unsigned char&, uint256, std::vector<uint256, std::allocator<uint256> >&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, unsigned char&, uint256&&, std::vector<uint256, std::allocator<uint256> >&) const Unexecuted instantiation: net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<ParamsWrapper<CAddress::SerParams, std::vector<CAddress, std::allocator<CAddress> > > >(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, ParamsWrapper<CAddress::SerParams, std::vector<CAddress, std::allocator<CAddress> > >&&) const net_processing.cpp:void (anonymous namespace)::PeerManagerImpl::MakeAndPushMessage<long&>(CNode&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, long&) const Line | Count | Source | 728 | 108 | { | 729 | 108 | m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); | 730 | 108 | } |
|
731 | | |
732 | | /** Send a version message to a peer */ |
733 | | void PushNodeVersion(CNode& pnode, const Peer& peer); |
734 | | |
735 | | /** Send a ping message every PING_INTERVAL or if requested via RPC. May |
736 | | * mark the peer to be disconnected if a ping has timed out. |
737 | | * We use mockable time for ping timeouts, so setmocktime may cause pings |
738 | | * to time out. */ |
739 | | void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now); |
740 | | |
741 | | /** Send `addr` messages on a regular schedule. */ |
742 | | void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
743 | | |
744 | | /** Send a single `sendheaders` message, after we have completed headers sync with a peer. */ |
745 | | void MaybeSendSendHeaders(CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
746 | | |
747 | | /** Relay (gossip) an address to a few randomly chosen nodes. |
748 | | * |
749 | | * @param[in] originator The id of the peer that sent us the address. We don't want to relay it back. |
750 | | * @param[in] addr Address to relay. |
751 | | * @param[in] fReachable Whether the address' network is reachable. We relay unreachable |
752 | | * addresses less. |
753 | | */ |
754 | | void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex); |
755 | | |
756 | | /** Send `feefilter` message. */ |
757 | | void MaybeSendFeefilter(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
758 | | |
759 | | FastRandomContext m_rng GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
760 | | |
761 | | FeeFilterRounder m_fee_filter_rounder GUARDED_BY(NetEventsInterface::g_msgproc_mutex); |
762 | | |
763 | | const CChainParams& m_chainparams; |
764 | | CConnman& m_connman; |
765 | | AddrMan& m_addrman; |
766 | | /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */ |
767 | | BanMan* const m_banman; |
768 | | ChainstateManager& m_chainman; |
769 | | CTxMemPool& m_mempool; |
770 | | TxRequestTracker m_txrequest GUARDED_BY(::cs_main); |
771 | | std::unique_ptr<TxReconciliationTracker> m_txreconciliation; |
772 | | |
773 | | /** The height of the best chain */ |
774 | | std::atomic<int> m_best_height{-1}; |
775 | | /** The time of the best chain tip block */ |
776 | | std::atomic<std::chrono::seconds> m_best_block_time{0s}; |
777 | | |
778 | | /** Next time to check for stale tip */ |
779 | | std::chrono::seconds m_stale_tip_check_time GUARDED_BY(cs_main){0s}; |
780 | | |
781 | | node::Warnings& m_warnings; |
782 | | TimeOffsets m_outbound_time_offsets{m_warnings}; |
783 | | |
784 | | const Options m_opts; |
785 | | |
786 | | bool RejectIncomingTxs(const CNode& peer) const; |
787 | | |
788 | | /** Whether we've completed initial sync yet, for determining when to turn |
789 | | * on extra block-relay-only peers. */ |
790 | | bool m_initial_sync_finished GUARDED_BY(cs_main){false}; |
791 | | |
792 | | /** Protects m_peer_map. This mutex must not be locked while holding a lock |
793 | | * on any of the mutexes inside a Peer object. */ |
794 | | mutable Mutex m_peer_mutex; |
795 | | /** |
796 | | * Map of all Peer objects, keyed by peer id. This map is protected |
797 | | * by the m_peer_mutex. Once a shared pointer reference is |
798 | | * taken, the lock may be released. Individual fields are protected by |
799 | | * their own locks. |
800 | | */ |
801 | | std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex); |
802 | | |
803 | | /** Map maintaining per-node state. */ |
804 | | std::map<NodeId, CNodeState> m_node_states GUARDED_BY(cs_main); |
805 | | |
806 | | /** Get a pointer to a const CNodeState, used when not mutating the CNodeState object. */ |
807 | | const CNodeState* State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
808 | | /** Get a pointer to a mutable CNodeState. */ |
809 | | CNodeState* State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
810 | | |
811 | | uint32_t GetFetchFlags(const Peer& peer) const; |
812 | | |
813 | | std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us}; |
814 | | |
815 | | /** Number of nodes with fSyncStarted. */ |
816 | | int nSyncStarted GUARDED_BY(cs_main) = 0; |
817 | | |
818 | | /** Hash of the last block we received via INV */ |
819 | | uint256 m_last_block_inv_triggering_headers_sync GUARDED_BY(g_msgproc_mutex){}; |
820 | | |
821 | | /** |
822 | | * Sources of received blocks, saved to be able punish them when processing |
823 | | * happens afterwards. |
824 | | * Set mapBlockSource[hash].second to false if the node should not be |
825 | | * punished if the block is invalid. |
826 | | */ |
827 | | std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main); |
828 | | |
829 | | /** Number of peers with wtxid relay. */ |
830 | | std::atomic<int> m_wtxid_relay_peers{0}; |
831 | | |
832 | | /** Number of outbound peers with m_chain_sync.m_protect. */ |
833 | | int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0; |
834 | | |
835 | | /** Number of preferable block download peers. */ |
836 | | int m_num_preferred_download_peers GUARDED_BY(cs_main){0}; |
837 | | |
838 | | /** Stalling timeout for blocks in IBD */ |
839 | | std::atomic<std::chrono::seconds> m_block_stalling_timeout{BLOCK_STALLING_TIMEOUT_DEFAULT}; |
840 | | |
841 | | /** Check whether we already have this gtxid in: |
842 | | * - mempool |
843 | | * - orphanage |
844 | | * - m_recent_rejects |
845 | | * - m_recent_rejects_reconsiderable (if include_reconsiderable = true) |
846 | | * - m_recent_confirmed_transactions |
847 | | * Also responsible for resetting m_recent_rejects and m_recent_rejects_reconsiderable if the |
848 | | * chain tip has changed. |
849 | | * */ |
850 | | bool AlreadyHaveTx(const GenTxid& gtxid, bool include_reconsiderable) |
851 | | EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_recent_confirmed_transactions_mutex); |
852 | | |
853 | | /** |
854 | | * Filter for transactions that were recently rejected by the mempool. |
855 | | * These are not rerequested until the chain tip changes, at which point |
856 | | * the entire filter is reset. |
857 | | * |
858 | | * Without this filter we'd be re-requesting txs from each of our peers, |
859 | | * increasing bandwidth consumption considerably. For instance, with 100 |
860 | | * peers, half of which relay a tx we don't accept, that might be a 50x |
861 | | * bandwidth increase. A flooding attacker attempting to roll-over the |
862 | | * filter using minimum-sized, 60byte, transactions might manage to send |
863 | | * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a |
864 | | * two minute window to send invs to us. |
865 | | * |
866 | | * Decreasing the false positive rate is fairly cheap, so we pick one in a |
867 | | * million to make it highly unlikely for users to have issues with this |
868 | | * filter. |
869 | | * |
870 | | * We typically only add wtxids to this filter. For non-segwit |
871 | | * transactions, the txid == wtxid, so this only prevents us from |
872 | | * re-downloading non-segwit transactions when communicating with |
873 | | * non-wtxidrelay peers -- which is important for avoiding malleation |
874 | | * attacks that could otherwise interfere with transaction relay from |
875 | | * non-wtxidrelay peers. For communicating with wtxidrelay peers, having |
876 | | * the reject filter store wtxids is exactly what we want to avoid |
877 | | * redownload of a rejected transaction. |
878 | | * |
879 | | * In cases where we can tell that a segwit transaction will fail |
880 | | * validation no matter the witness, we may add the txid of such |
881 | | * transaction to the filter as well. This can be helpful when |
882 | | * communicating with txid-relay peers or if we were to otherwise fetch a |
883 | | * transaction via txid (eg in our orphan handling). |
884 | | * |
885 | | * Memory used: 1.3 MB |
886 | | */ |
887 | | std::unique_ptr<CRollingBloomFilter> m_recent_rejects GUARDED_BY(::cs_main){nullptr}; |
888 | | /** Block hash of chain tip the last time we reset m_recent_rejects and |
889 | | * RecentRejectsReconsiderableFilter(). */ |
890 | | uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main); |
891 | | |
892 | | CRollingBloomFilter& RecentRejectsFilter() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) |
893 | 0 | { |
894 | 0 | AssertLockHeld(::cs_main); |
895 | |
|
896 | 0 | if (!m_recent_rejects) { Branch (896:13): [True: 0, False: 0]
|
897 | 0 | m_recent_rejects = std::make_unique<CRollingBloomFilter>(120'000, 0.000'001); |
898 | 0 | } |
899 | |
|
900 | 0 | return *m_recent_rejects; |
901 | 0 | } |
902 | | |
903 | | /** |
904 | | * Filter for: |
905 | | * (1) wtxids of transactions that were recently rejected by the mempool but are |
906 | | * eligible for reconsideration if submitted with other transactions. |
907 | | * (2) packages (see GetPackageHash) we have already rejected before and should not retry. |
908 | | * |
909 | | * Similar to m_recent_rejects, this filter is used to save bandwidth when e.g. all of our peers |
910 | | * have larger mempools and thus lower minimum feerates than us. |
911 | | * |
912 | | * When a transaction's error is TxValidationResult::TX_RECONSIDERABLE (in a package or by |
913 | | * itself), add its wtxid to this filter. When a package fails for any reason, add the combined |
914 | | * hash to this filter. |
915 | | * |
916 | | * Upon receiving an announcement for a transaction, if it exists in this filter, do not |
917 | | * download the txdata. When considering packages, if it exists in this filter, drop it. |
918 | | * |
919 | | * Reset this filter when the chain tip changes. |
920 | | * |
921 | | * Parameters are picked to be the same as m_recent_rejects, with the same rationale. |
922 | | */ |
923 | | std::unique_ptr<CRollingBloomFilter> m_recent_rejects_reconsiderable GUARDED_BY(::cs_main){nullptr}; |
924 | | |
925 | | CRollingBloomFilter& RecentRejectsReconsiderableFilter() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) |
926 | 0 | { |
927 | 0 | AssertLockHeld(::cs_main); |
928 | |
|
929 | 0 | if (!m_recent_rejects_reconsiderable) { Branch (929:13): [True: 0, False: 0]
|
930 | 0 | m_recent_rejects_reconsiderable = std::make_unique<CRollingBloomFilter>(120'000, 0.000'001); |
931 | 0 | } |
932 | |
|
933 | 0 | return *m_recent_rejects_reconsiderable; |
934 | 0 | } |
935 | | |
936 | | /* |
937 | | * Filter for transactions that have been recently confirmed. |
938 | | * We use this to avoid requesting transactions that have already been |
939 | | * confirnmed. |
940 | | * |
941 | | * Blocks don't typically have more than 4000 transactions, so this should |
942 | | * be at least six blocks (~1 hr) worth of transactions that we can store, |
943 | | * inserting both a txid and wtxid for every observed transaction. |
944 | | * If the number of transactions appearing in a block goes up, or if we are |
945 | | * seeing getdata requests more than an hour after initial announcement, we |
946 | | * can increase this number. |
947 | | * The false positive rate of 1/1M should come out to less than 1 |
948 | | * transaction per day that would be inadvertently ignored (which is the |
949 | | * same probability that we have in the reject filter). |
950 | | */ |
951 | | Mutex m_recent_confirmed_transactions_mutex; |
952 | | std::unique_ptr<CRollingBloomFilter> m_recent_confirmed_transactions GUARDED_BY(m_recent_confirmed_transactions_mutex){nullptr}; |
953 | | |
954 | | CRollingBloomFilter& RecentConfirmedTransactionsFilter() EXCLUSIVE_LOCKS_REQUIRED(m_recent_confirmed_transactions_mutex) |
955 | 0 | { |
956 | 0 | AssertLockHeld(m_recent_confirmed_transactions_mutex); |
957 | |
|
958 | 0 | if (!m_recent_confirmed_transactions) { Branch (958:13): [True: 0, False: 0]
|
959 | 0 | m_recent_confirmed_transactions = std::make_unique<CRollingBloomFilter>(48'000, 0.000'001); |
960 | 0 | } |
961 | |
|
962 | 0 | return *m_recent_confirmed_transactions; |
963 | 0 | } |
964 | | |
965 | | /** |
966 | | * For sending `inv`s to inbound peers, we use a single (exponentially |
967 | | * distributed) timer for all peers. If we used a separate timer for each |
968 | | * peer, a spy node could make multiple inbound connections to us to |
969 | | * accurately determine when we received the transaction (and potentially |
970 | | * determine the transaction's origin). */ |
971 | | std::chrono::microseconds NextInvToInbounds(std::chrono::microseconds now, |
972 | | std::chrono::seconds average_interval) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
973 | | |
974 | | |
975 | | // All of the following cache a recent block, and are protected by m_most_recent_block_mutex |
976 | | Mutex m_most_recent_block_mutex; |
977 | | std::shared_ptr<const CBlock> m_most_recent_block GUARDED_BY(m_most_recent_block_mutex); |
978 | | std::shared_ptr<const CBlockHeaderAndShortTxIDs> m_most_recent_compact_block GUARDED_BY(m_most_recent_block_mutex); |
979 | | uint256 m_most_recent_block_hash GUARDED_BY(m_most_recent_block_mutex); |
980 | | std::unique_ptr<const std::map<uint256, CTransactionRef>> m_most_recent_block_txs GUARDED_BY(m_most_recent_block_mutex); |
981 | | |
982 | | // Data about the low-work headers synchronization, aggregated from all peers' HeadersSyncStates. |
983 | | /** Mutex guarding the other m_headers_presync_* variables. */ |
984 | | Mutex m_headers_presync_mutex; |
985 | | /** A type to represent statistics about a peer's low-work headers sync. |
986 | | * |
987 | | * - The first field is the total verified amount of work in that synchronization. |
988 | | * - The second is: |
989 | | * - nullopt: the sync is in REDOWNLOAD phase (phase 2). |
990 | | * - {height, timestamp}: the sync has the specified tip height and block timestamp (phase 1). |
991 | | */ |
992 | | using HeadersPresyncStats = std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>; |
993 | | /** Statistics for all peers in low-work headers sync. */ |
994 | | std::map<NodeId, HeadersPresyncStats> m_headers_presync_stats GUARDED_BY(m_headers_presync_mutex) {}; |
995 | | /** The peer with the most-work entry in m_headers_presync_stats. */ |
996 | | NodeId m_headers_presync_bestpeer GUARDED_BY(m_headers_presync_mutex) {-1}; |
997 | | /** The m_headers_presync_stats improved, and needs signalling. */ |
998 | | std::atomic_bool m_headers_presync_should_signal{false}; |
999 | | |
1000 | | /** Height of the highest block announced using BIP 152 high-bandwidth mode. */ |
1001 | | int m_highest_fast_announce GUARDED_BY(::cs_main){0}; |
1002 | | |
1003 | | /** Have we requested this block from a peer */ |
1004 | | bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1005 | | |
1006 | | /** Have we requested this block from an outbound peer */ |
1007 | | bool IsBlockRequestedFromOutbound(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1008 | | |
1009 | | /** Remove this block from our tracked requested blocks. Called if: |
1010 | | * - the block has been received from a peer |
1011 | | * - the request for the block has timed out |
1012 | | * If "from_peer" is specified, then only remove the block if it is in |
1013 | | * flight from that peer (to avoid one peer's network traffic from |
1014 | | * affecting another's state). |
1015 | | */ |
1016 | | void RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1017 | | |
1018 | | /* Mark a block as in flight |
1019 | | * Returns false, still setting pit, if the block was already in flight from the same peer |
1020 | | * pit will only be valid as long as the same cs_main lock is being held |
1021 | | */ |
1022 | | bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1023 | | |
1024 | | bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1025 | | |
1026 | | /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has |
1027 | | * at most count entries. |
1028 | | */ |
1029 | | void FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1030 | | |
1031 | | /** Request blocks for the background chainstate, if one is in use. */ |
1032 | | 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); |
1033 | | |
1034 | | /** |
1035 | | * \brief Find next blocks to download from a peer after a starting block. |
1036 | | * |
1037 | | * \param vBlocks Vector of blocks to download which will be appended to. |
1038 | | * \param peer Peer which blocks will be downloaded from. |
1039 | | * \param state Pointer to the state of the peer. |
1040 | | * \param pindexWalk Pointer to the starting block to add to vBlocks. |
1041 | | * \param count Maximum number of blocks to allow in vBlocks. No more |
1042 | | * blocks will be added if it reaches this size. |
1043 | | * \param nWindowEnd Maximum height of blocks to allow in vBlocks. No |
1044 | | * blocks will be added above this height. |
1045 | | * \param activeChain Optional pointer to a chain to compare against. If |
1046 | | * provided, any next blocks which are already contained |
1047 | | * in this chain will not be appended to vBlocks, but |
1048 | | * instead will be used to update the |
1049 | | * state->pindexLastCommonBlock pointer. |
1050 | | * \param nodeStaller Optional pointer to a NodeId variable that will receive |
1051 | | * the ID of another peer that might be causing this peer |
1052 | | * to stall. This is set to the ID of the peer which |
1053 | | * first requested the first in-flight block in the |
1054 | | * download window. It is only set if vBlocks is empty at |
1055 | | * the end of this function call and if increasing |
1056 | | * nWindowEnd by 1 would cause it to be non-empty (which |
1057 | | * indicates the download might be stalled because every |
1058 | | * block in the window is in flight and no other peer is |
1059 | | * trying to download the next block). |
1060 | | */ |
1061 | | 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); |
1062 | | |
1063 | | /* Multimap used to preserve insertion order */ |
1064 | | typedef std::multimap<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator>> BlockDownloadMap; |
1065 | | BlockDownloadMap mapBlocksInFlight GUARDED_BY(cs_main); |
1066 | | |
1067 | | /** When our tip was last updated. */ |
1068 | | std::atomic<std::chrono::seconds> m_last_tip_update{0s}; |
1069 | | |
1070 | | /** Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). */ |
1071 | | CTransactionRef FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid) |
1072 | | EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, NetEventsInterface::g_msgproc_mutex); |
1073 | | |
1074 | | void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) |
1075 | | EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex, NetEventsInterface::g_msgproc_mutex) |
1076 | | LOCKS_EXCLUDED(::cs_main); |
1077 | | |
1078 | | /** Process a new block. Perform any post-processing housekeeping */ |
1079 | | void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked); |
1080 | | |
1081 | | /** Process compact block txns */ |
1082 | | void ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions) |
1083 | | EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex, !m_most_recent_block_mutex); |
1084 | | |
1085 | | /** |
1086 | | * When a peer sends us a valid block, instruct it to announce blocks to us |
1087 | | * using CMPCTBLOCK if possible by adding its nodeid to the end of |
1088 | | * lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by |
1089 | | * removing the first element if necessary. |
1090 | | */ |
1091 | | void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1092 | | |
1093 | | /** Stack of nodes which we have set to announce using compact blocks */ |
1094 | | std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main); |
1095 | | |
1096 | | /** Number of peers from which we're downloading blocks. */ |
1097 | | int m_peers_downloading_from GUARDED_BY(cs_main) = 0; |
1098 | | |
1099 | | /** Storage for orphan information */ |
1100 | | TxOrphanage m_orphanage; |
1101 | | |
1102 | | void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
1103 | | |
1104 | | /** Orphan/conflicted/etc transactions that are kept for compact block reconstruction. |
1105 | | * The last -blockreconstructionextratxn/DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN of |
1106 | | * these are kept in a ring buffer */ |
1107 | | std::vector<CTransactionRef> vExtraTxnForCompact GUARDED_BY(g_msgproc_mutex); |
1108 | | /** Offset into vExtraTxnForCompact to insert the next tx */ |
1109 | | size_t vExtraTxnForCompactIt GUARDED_BY(g_msgproc_mutex) = 0; |
1110 | | |
1111 | | /** Check whether the last unknown block a peer advertised is not yet known. */ |
1112 | | void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1113 | | /** Update tracking information about which blocks a peer is assumed to have. */ |
1114 | | void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1115 | | bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1116 | | |
1117 | | /** |
1118 | | * Estimates the distance, in blocks, between the best-known block and the network chain tip. |
1119 | | * Utilizes the best-block time and the chainparams blocks spacing to approximate it. |
1120 | | */ |
1121 | | int64_t ApproximateBestBlockDepth() const; |
1122 | | |
1123 | | /** |
1124 | | * To prevent fingerprinting attacks, only send blocks/headers outside of |
1125 | | * the active chain if they are no more than a month older (both in time, |
1126 | | * and in best equivalent proof of work) than the best header chain we know |
1127 | | * about and we fully-validated them at some point. |
1128 | | */ |
1129 | | bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1130 | | bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); |
1131 | | void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv) |
1132 | | EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex); |
1133 | | |
1134 | | /** |
1135 | | * Validation logic for compact filters request handling. |
1136 | | * |
1137 | | * May disconnect from the peer in the case of a bad request. |
1138 | | * |
1139 | | * @param[in] node The node that we received the request from |
1140 | | * @param[in] peer The peer that we received the request from |
1141 | | * @param[in] filter_type The filter type the request is for. Must be basic filters. |
1142 | | * @param[in] start_height The start height for the request |
1143 | | * @param[in] stop_hash The stop_hash for the request |
1144 | | * @param[in] max_height_diff The maximum number of items permitted to request, as specified in BIP 157 |
1145 | | * @param[out] stop_index The CBlockIndex for the stop_hash block, if the request can be serviced. |
1146 | | * @param[out] filter_index The filter index, if the request can be serviced. |
1147 | | * @return True if the request can be serviced. |
1148 | | */ |
1149 | | bool PrepareBlockFilterRequest(CNode& node, Peer& peer, |
1150 | | BlockFilterType filter_type, uint32_t start_height, |
1151 | | const uint256& stop_hash, uint32_t max_height_diff, |
1152 | | const CBlockIndex*& stop_index, |
1153 | | BlockFilterIndex*& filter_index); |
1154 | | |
1155 | | /** |
1156 | | * Handle a cfilters request. |
1157 | | * |
1158 | | * May disconnect from the peer in the case of a bad request. |
1159 | | * |
1160 | | * @param[in] node The node that we received the request from |
1161 | | * @param[in] peer The peer that we received the request from |
1162 | | * @param[in] vRecv The raw message received |
1163 | | */ |
1164 | | void ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv); |
1165 | | |
1166 | | /** |
1167 | | * Handle a cfheaders request. |
1168 | | * |
1169 | | * May disconnect from the peer in the case of a bad request. |
1170 | | * |
1171 | | * @param[in] node The node that we received the request from |
1172 | | * @param[in] peer The peer that we received the request from |
1173 | | * @param[in] vRecv The raw message received |
1174 | | */ |
1175 | | void ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv); |
1176 | | |
1177 | | /** |
1178 | | * Handle a getcfcheckpt request. |
1179 | | * |
1180 | | * May disconnect from the peer in the case of a bad request. |
1181 | | * |
1182 | | * @param[in] node The node that we received the request from |
1183 | | * @param[in] peer The peer that we received the request from |
1184 | | * @param[in] vRecv The raw message received |
1185 | | */ |
1186 | | void ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv); |
1187 | | |
1188 | | /** Checks if address relay is permitted with peer. If needed, initializes |
1189 | | * the m_addr_known bloom filter and sets m_addr_relay_enabled to true. |
1190 | | * |
1191 | | * @return True if address relay is enabled with peer |
1192 | | * False if address relay is disallowed |
1193 | | */ |
1194 | | bool SetupAddressRelay(const CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
1195 | | |
1196 | | void AddAddressKnown(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
1197 | | void PushAddress(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); |
1198 | | }; |
1199 | | |
1200 | | const CNodeState* PeerManagerImpl::State(NodeId pnode) const |
1201 | 2.27k | { |
1202 | 2.27k | std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode); |
1203 | 2.27k | if (it == m_node_states.end()) Branch (1203:9): [True: 0, False: 2.27k]
|
1204 | 0 | return nullptr; |
1205 | 2.27k | return &it->second; |
1206 | 2.27k | } |
1207 | | |
1208 | | CNodeState* PeerManagerImpl::State(NodeId pnode) |
1209 | 2.27k | { |
1210 | 2.27k | return const_cast<CNodeState*>(std::as_const(*this).State(pnode)); |
1211 | 2.27k | } |
1212 | | |
1213 | | /** |
1214 | | * Whether the peer supports the address. For example, a peer that does not |
1215 | | * implement BIP155 cannot receive Tor v3 addresses because it requires |
1216 | | * ADDRv2 (BIP155) encoding. |
1217 | | */ |
1218 | | static bool IsAddrCompatible(const Peer& peer, const CAddress& addr) |
1219 | 0 | { |
1220 | 0 | return peer.m_wants_addrv2 || addr.IsAddrV1Compatible(); Branch (1220:12): [True: 0, False: 0]
Branch (1220:35): [True: 0, False: 0]
|
1221 | 0 | } |
1222 | | |
1223 | | void PeerManagerImpl::AddAddressKnown(Peer& peer, const CAddress& addr) |
1224 | 0 | { |
1225 | 0 | assert(peer.m_addr_known); |
1226 | 0 | peer.m_addr_known->insert(addr.GetKey()); |
1227 | 0 | } |
1228 | | |
1229 | | void PeerManagerImpl::PushAddress(Peer& peer, const CAddress& addr) |
1230 | 0 | { |
1231 | | // Known checking here is only to save space from duplicates. |
1232 | | // Before sending, we'll filter it again for known addresses that were |
1233 | | // added after addresses were pushed. |
1234 | 0 | assert(peer.m_addr_known); |
1235 | 0 | if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) { Branch (1235:9): [True: 0, False: 0]
Branch (1235:9): [True: 0, False: 0]
Branch (1235:27): [True: 0, False: 0]
Branch (1235:74): [True: 0, False: 0]
|
1236 | 0 | if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) { Branch (1236:13): [True: 0, False: 0]
|
1237 | 0 | peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] = addr; |
1238 | 0 | } else { |
1239 | 0 | peer.m_addrs_to_send.push_back(addr); |
1240 | 0 | } |
1241 | 0 | } |
1242 | 0 | } |
1243 | | |
1244 | | static void AddKnownTx(Peer& peer, const uint256& hash) |
1245 | 0 | { |
1246 | 0 | auto tx_relay = peer.GetTxRelay(); |
1247 | 0 | if (!tx_relay) return; Branch (1247:9): [True: 0, False: 0]
|
1248 | | |
1249 | 0 | LOCK(tx_relay->m_tx_inventory_mutex); |
1250 | 0 | tx_relay->m_tx_inventory_known_filter.insert(hash); |
1251 | 0 | } |
1252 | | |
1253 | | /** Whether this peer can serve us blocks. */ |
1254 | | static bool CanServeBlocks(const Peer& peer) |
1255 | 600 | { |
1256 | 600 | return peer.m_their_services & (NODE_NETWORK|NODE_NETWORK_LIMITED); |
1257 | 600 | } |
1258 | | |
1259 | | /** Whether this peer can only serve limited recent blocks (e.g. because |
1260 | | * it prunes old blocks) */ |
1261 | | static bool IsLimitedPeer(const Peer& peer) |
1262 | 125 | { |
1263 | 125 | return (!(peer.m_their_services & NODE_NETWORK) && Branch (1263:13): [True: 19, False: 106]
|
1264 | 125 | (peer.m_their_services & NODE_NETWORK_LIMITED)); Branch (1264:14): [True: 19, False: 0]
|
1265 | 125 | } |
1266 | | |
1267 | | /** Whether this peer can serve us witness data */ |
1268 | | static bool CanServeWitnesses(const Peer& peer) |
1269 | 0 | { |
1270 | 0 | return peer.m_their_services & NODE_WITNESS; |
1271 | 0 | } |
1272 | | |
1273 | | std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now, |
1274 | | std::chrono::seconds average_interval) |
1275 | 29 | { |
1276 | 29 | if (m_next_inv_to_inbounds.load() < now) { Branch (1276:9): [True: 26, False: 3]
|
1277 | | // If this function were called from multiple threads simultaneously |
1278 | | // it would possible that both update the next send variable, and return a different result to their caller. |
1279 | | // This is not possible in practice as only the net processing thread invokes this function. |
1280 | 26 | m_next_inv_to_inbounds = now + m_rng.rand_exp_duration(average_interval); |
1281 | 26 | } |
1282 | 29 | return m_next_inv_to_inbounds; |
1283 | 29 | } |
1284 | | |
1285 | | bool PeerManagerImpl::IsBlockRequested(const uint256& hash) |
1286 | 0 | { |
1287 | 0 | return mapBlocksInFlight.count(hash); |
1288 | 0 | } |
1289 | | |
1290 | | bool PeerManagerImpl::IsBlockRequestedFromOutbound(const uint256& hash) |
1291 | 0 | { |
1292 | 0 | for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) { Branch (1292:60): [True: 0, False: 0]
|
1293 | 0 | auto [nodeid, block_it] = range.first->second; |
1294 | 0 | CNodeState& nodestate = *Assert(State(nodeid)); |
1295 | 0 | if (!nodestate.m_is_inbound) return true; Branch (1295:13): [True: 0, False: 0]
|
1296 | 0 | } |
1297 | | |
1298 | 0 | return false; |
1299 | 0 | } |
1300 | | |
1301 | | void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) |
1302 | 0 | { |
1303 | 0 | auto range = mapBlocksInFlight.equal_range(hash); |
1304 | 0 | if (range.first == range.second) { Branch (1304:9): [True: 0, False: 0]
|
1305 | | // Block was not requested from any peer |
1306 | 0 | return; |
1307 | 0 | } |
1308 | | |
1309 | | // We should not have requested too many of this block |
1310 | 0 | Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK); |
1311 | |
|
1312 | 0 | while (range.first != range.second) { Branch (1312:12): [True: 0, False: 0]
|
1313 | 0 | auto [node_id, list_it] = range.first->second; |
1314 | |
|
1315 | 0 | if (from_peer && *from_peer != node_id) { Branch (1315:13): [True: 0, False: 0]
Branch (1315:26): [True: 0, False: 0]
|
1316 | 0 | range.first++; |
1317 | 0 | continue; |
1318 | 0 | } |
1319 | | |
1320 | 0 | CNodeState& state = *Assert(State(node_id)); |
1321 | |
|
1322 | 0 | if (state.vBlocksInFlight.begin() == list_it) { Branch (1322:13): [True: 0, False: 0]
|
1323 | | // First block on the queue was received, update the start download time for the next one |
1324 | 0 | state.m_downloading_since = std::max(state.m_downloading_since, GetTime<std::chrono::microseconds>()); |
1325 | 0 | } |
1326 | 0 | state.vBlocksInFlight.erase(list_it); |
1327 | |
|
1328 | 0 | if (state.vBlocksInFlight.empty()) { Branch (1328:13): [True: 0, False: 0]
|
1329 | | // Last validated block on the queue for this peer was received. |
1330 | 0 | m_peers_downloading_from--; |
1331 | 0 | } |
1332 | 0 | state.m_stalling_since = 0us; |
1333 | |
|
1334 | 0 | range.first = mapBlocksInFlight.erase(range.first); |
1335 | 0 | } |
1336 | 0 | } |
1337 | | |
1338 | | bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit) |
1339 | 0 | { |
1340 | 0 | const uint256& hash{block.GetBlockHash()}; |
1341 | |
|
1342 | 0 | CNodeState *state = State(nodeid); |
1343 | 0 | assert(state != nullptr); |
1344 | | |
1345 | 0 | Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK); |
1346 | | |
1347 | | // Short-circuit most stuff in case it is from the same node |
1348 | 0 | for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) { Branch (1348:60): [True: 0, False: 0]
|
1349 | 0 | if (range.first->second.first == nodeid) { Branch (1349:13): [True: 0, False: 0]
|
1350 | 0 | if (pit) { Branch (1350:17): [True: 0, False: 0]
|
1351 | 0 | *pit = &range.first->second.second; |
1352 | 0 | } |
1353 | 0 | return false; |
1354 | 0 | } |
1355 | 0 | } |
1356 | | |
1357 | | // Make sure it's not being fetched already from same peer. |
1358 | 0 | RemoveBlockRequest(hash, nodeid); |
1359 | |
|
1360 | 0 | std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), |
1361 | 0 | {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool) : nullptr)}); Branch (1361:64): [True: 0, False: 0]
|
1362 | 0 | if (state->vBlocksInFlight.size() == 1) { Branch (1362:9): [True: 0, False: 0]
|
1363 | | // We're starting a block download (batch) from this peer. |
1364 | 0 | state->m_downloading_since = GetTime<std::chrono::microseconds>(); |
1365 | 0 | m_peers_downloading_from++; |
1366 | 0 | } |
1367 | 0 | auto itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))); |
1368 | 0 | if (pit) { Branch (1368:9): [True: 0, False: 0]
|
1369 | 0 | *pit = &itInFlight->second.second; |
1370 | 0 | } |
1371 | 0 | return true; |
1372 | 0 | } |
1373 | | |
1374 | | void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) |
1375 | 0 | { |
1376 | 0 | AssertLockHeld(cs_main); |
1377 | | |
1378 | | // When in -blocksonly mode, never request high-bandwidth mode from peers. Our |
1379 | | // mempool will not contain the transactions necessary to reconstruct the |
1380 | | // compact block. |
1381 | 0 | if (m_opts.ignore_incoming_txs) return; Branch (1381:9): [True: 0, False: 0]
|
1382 | | |
1383 | 0 | CNodeState* nodestate = State(nodeid); |
1384 | 0 | if (!nodestate || !nodestate->m_provides_cmpctblocks) { Branch (1384:9): [True: 0, False: 0]
Branch (1384:23): [True: 0, False: 0]
|
1385 | | // Don't request compact blocks if the peer has not signalled support |
1386 | 0 | return; |
1387 | 0 | } |
1388 | | |
1389 | 0 | int num_outbound_hb_peers = 0; |
1390 | 0 | for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) { Branch (1390:81): [True: 0, False: 0]
|
1391 | 0 | if (*it == nodeid) { Branch (1391:13): [True: 0, False: 0]
|
1392 | 0 | lNodesAnnouncingHeaderAndIDs.erase(it); |
1393 | 0 | lNodesAnnouncingHeaderAndIDs.push_back(nodeid); |
1394 | 0 | return; |
1395 | 0 | } |
1396 | 0 | CNodeState *state = State(*it); |
1397 | 0 | if (state != nullptr && !state->m_is_inbound) ++num_outbound_hb_peers; Branch (1397:13): [True: 0, False: 0]
Branch (1397:33): [True: 0, False: 0]
|
1398 | 0 | } |
1399 | 0 | if (nodestate->m_is_inbound) { Branch (1399:9): [True: 0, False: 0]
|
1400 | | // If we're adding an inbound HB peer, make sure we're not removing |
1401 | | // our last outbound HB peer in the process. |
1402 | 0 | if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 1) { Branch (1402:13): [True: 0, False: 0]
Branch (1402:57): [True: 0, False: 0]
|
1403 | 0 | CNodeState *remove_node = State(lNodesAnnouncingHeaderAndIDs.front()); |
1404 | 0 | if (remove_node != nullptr && !remove_node->m_is_inbound) { Branch (1404:17): [True: 0, False: 0]
Branch (1404:43): [True: 0, False: 0]
|
1405 | | // Put the HB outbound peer in the second slot, so that it |
1406 | | // doesn't get removed. |
1407 | 0 | std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin())); |
1408 | 0 | } |
1409 | 0 | } |
1410 | 0 | } |
1411 | 0 | m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
1412 | 0 | AssertLockHeld(::cs_main); |
1413 | 0 | if (lNodesAnnouncingHeaderAndIDs.size() >= 3) { Branch (1413:13): [True: 0, False: 0]
|
1414 | | // As per BIP152, we only get 3 of our peers to announce |
1415 | | // blocks using compact encodings. |
1416 | 0 | m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this](CNode* pnodeStop){ |
1417 | 0 | MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION); |
1418 | | // save BIP152 bandwidth state: we select peer to be low-bandwidth |
1419 | 0 | pnodeStop->m_bip152_highbandwidth_to = false; |
1420 | 0 | return true; |
1421 | 0 | }); |
1422 | 0 | lNodesAnnouncingHeaderAndIDs.pop_front(); |
1423 | 0 | } |
1424 | 0 | MakeAndPushMessage(*pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/true, /*version=*/CMPCTBLOCKS_VERSION); |
1425 | | // save BIP152 bandwidth state: we select peer to be high-bandwidth |
1426 | 0 | pfrom->m_bip152_highbandwidth_to = true; |
1427 | 0 | lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId()); |
1428 | 0 | return true; |
1429 | 0 | }); |
1430 | 0 | } |
1431 | | |
1432 | | bool PeerManagerImpl::TipMayBeStale() |
1433 | 0 | { |
1434 | 0 | AssertLockHeld(cs_main); |
1435 | 0 | const Consensus::Params& consensusParams = m_chainparams.GetConsensus(); |
1436 | 0 | if (m_last_tip_update.load() == 0s) { Branch (1436:9): [True: 0, False: 0]
|
1437 | 0 | m_last_tip_update = GetTime<std::chrono::seconds>(); |
1438 | 0 | } |
1439 | 0 | return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty(); Branch (1439:12): [True: 0, False: 0]
Branch (1439:136): [True: 0, False: 0]
|
1440 | 0 | } |
1441 | | |
1442 | | int64_t PeerManagerImpl::ApproximateBestBlockDepth() const |
1443 | 346 | { |
1444 | 346 | return (GetTime<std::chrono::seconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing; |
1445 | 346 | } |
1446 | | |
1447 | | bool PeerManagerImpl::CanDirectFetch() |
1448 | 0 | { |
1449 | 0 | return m_chainman.ActiveChain().Tip()->Time() > NodeClock::now() - m_chainparams.GetConsensus().PowTargetSpacing() * 20; |
1450 | 0 | } |
1451 | | |
1452 | | static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main) |
1453 | 0 | { |
1454 | 0 | if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) Branch (1454:9): [True: 0, False: 0]
Branch (1454:40): [True: 0, False: 0]
|
1455 | 0 | return true; |
1456 | 0 | if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) Branch (1456:9): [True: 0, False: 0]
Branch (1456:40): [True: 0, False: 0]
|
1457 | 0 | return true; |
1458 | 0 | return false; |
1459 | 0 | } |
1460 | | |
1461 | 247 | void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) { |
1462 | 247 | CNodeState *state = State(nodeid); |
1463 | 247 | assert(state != nullptr); |
1464 | | |
1465 | 247 | if (!state->hashLastUnknownBlock.IsNull()) { Branch (1465:9): [True: 0, False: 247]
|
1466 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock); |
1467 | 0 | if (pindex && pindex->nChainWork > 0) { Branch (1467:13): [True: 0, False: 0]
Branch (1467:13): [True: 0, False: 0]
Branch (1467:23): [True: 0, False: 0]
|
1468 | 0 | if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) { Branch (1468:17): [True: 0, False: 0]
Branch (1468:59): [True: 0, False: 0]
|
1469 | 0 | state->pindexBestKnownBlock = pindex; |
1470 | 0 | } |
1471 | 0 | state->hashLastUnknownBlock.SetNull(); |
1472 | 0 | } |
1473 | 0 | } |
1474 | 247 | } |
1475 | | |
1476 | 0 | void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { |
1477 | 0 | CNodeState *state = State(nodeid); |
1478 | 0 | assert(state != nullptr); |
1479 | | |
1480 | 0 | ProcessBlockAvailability(nodeid); |
1481 | |
|
1482 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash); |
1483 | 0 | if (pindex && pindex->nChainWork > 0) { Branch (1483:9): [True: 0, False: 0]
Branch (1483:9): [True: 0, False: 0]
Branch (1483:19): [True: 0, False: 0]
|
1484 | | // An actually better block was announced. |
1485 | 0 | if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) { Branch (1485:13): [True: 0, False: 0]
Branch (1485:55): [True: 0, False: 0]
|
1486 | 0 | state->pindexBestKnownBlock = pindex; |
1487 | 0 | } |
1488 | 0 | } else { |
1489 | | // An unknown block was announced; just assume that the latest one is the best one. |
1490 | 0 | state->hashLastUnknownBlock = hash; |
1491 | 0 | } |
1492 | 0 | } |
1493 | | |
1494 | | // Logic for calculating which blocks to download from a given peer, given our current tip. |
1495 | | void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) |
1496 | 106 | { |
1497 | 106 | if (count == 0) Branch (1497:9): [True: 0, False: 106]
|
1498 | 0 | return; |
1499 | | |
1500 | 106 | vBlocks.reserve(vBlocks.size() + count); |
1501 | 106 | CNodeState *state = State(peer.m_id); |
1502 | 106 | assert(state != nullptr); |
1503 | | |
1504 | | // Make sure pindexBestKnownBlock is up to date, we'll need it. |
1505 | 106 | ProcessBlockAvailability(peer.m_id); |
1506 | | |
1507 | 106 | if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) { Branch (1507:9): [True: 106, False: 0]
Branch (1507:51): [True: 0, False: 0]
Branch (1507:139): [True: 0, False: 0]
|
1508 | | // This peer has nothing interesting. |
1509 | 106 | return; |
1510 | 106 | } |
1511 | | |
1512 | 0 | if (state->pindexLastCommonBlock == nullptr) { Branch (1512:9): [True: 0, False: 0]
|
1513 | | // Bootstrap quickly by guessing a parent of our best tip is the forking point. |
1514 | | // Guessing wrong in either direction is not a problem. |
1515 | 0 | state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())]; |
1516 | 0 | } |
1517 | | |
1518 | | // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor |
1519 | | // of its current tip anymore. Go back enough to fix that. |
1520 | 0 | state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); |
1521 | 0 | if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) Branch (1521:9): [True: 0, False: 0]
|
1522 | 0 | return; |
1523 | | |
1524 | 0 | const CBlockIndex *pindexWalk = state->pindexLastCommonBlock; |
1525 | | // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last |
1526 | | // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to |
1527 | | // download that next block if the window were 1 larger. |
1528 | 0 | int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; |
1529 | |
|
1530 | 0 | FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller); |
1531 | 0 | } |
1532 | | |
1533 | | void PeerManagerImpl::TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex *from_tip, const CBlockIndex* target_block) |
1534 | 0 | { |
1535 | 0 | Assert(from_tip); |
1536 | 0 | Assert(target_block); |
1537 | |
|
1538 | 0 | if (vBlocks.size() >= count) { Branch (1538:9): [True: 0, False: 0]
|
1539 | 0 | return; |
1540 | 0 | } |
1541 | | |
1542 | 0 | vBlocks.reserve(count); |
1543 | 0 | CNodeState *state = Assert(State(peer.m_id)); |
1544 | |
|
1545 | 0 | if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->GetAncestor(target_block->nHeight) != target_block) { Branch (1545:9): [True: 0, False: 0]
Branch (1545:51): [True: 0, False: 0]
|
1546 | | // This peer can't provide us the complete series of blocks leading up to the |
1547 | | // assumeutxo snapshot base. |
1548 | | // |
1549 | | // Presumably this peer's chain has less work than our ActiveChain()'s tip, or else we |
1550 | | // will eventually crash when we try to reorg to it. Let other logic |
1551 | | // deal with whether we disconnect this peer. |
1552 | | // |
1553 | | // TODO at some point in the future, we might choose to request what blocks |
1554 | | // this peer does have from the historical chain, despite it not having a |
1555 | | // complete history beneath the snapshot base. |
1556 | 0 | return; |
1557 | 0 | } |
1558 | | |
1559 | 0 | FindNextBlocks(vBlocks, peer, state, from_tip, count, std::min<int>(from_tip->nHeight + BLOCK_DOWNLOAD_WINDOW, target_block->nHeight)); |
1560 | 0 | } |
1561 | | |
1562 | | 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) |
1563 | 0 | { |
1564 | 0 | std::vector<const CBlockIndex*> vToFetch; |
1565 | 0 | int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); |
1566 | 0 | bool is_limited_peer = IsLimitedPeer(peer); |
1567 | 0 | NodeId waitingfor = -1; |
1568 | 0 | while (pindexWalk->nHeight < nMaxHeight) { Branch (1568:12): [True: 0, False: 0]
|
1569 | | // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards |
1570 | | // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive |
1571 | | // as iterating over ~100 CBlockIndex* entries anyway. |
1572 | 0 | int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128)); |
1573 | 0 | vToFetch.resize(nToFetch); |
1574 | 0 | pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); |
1575 | 0 | vToFetch[nToFetch - 1] = pindexWalk; |
1576 | 0 | for (unsigned int i = nToFetch - 1; i > 0; i--) { Branch (1576:45): [True: 0, False: 0]
|
1577 | 0 | vToFetch[i - 1] = vToFetch[i]->pprev; |
1578 | 0 | } |
1579 | | |
1580 | | // Iterate over those blocks in vToFetch (in forward direction), adding the ones that |
1581 | | // are not yet downloaded and not in flight to vBlocks. In the meantime, update |
1582 | | // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's |
1583 | | // already part of our chain (and therefore don't need it even if pruned). |
1584 | 0 | for (const CBlockIndex* pindex : vToFetch) { Branch (1584:40): [True: 0, False: 0]
|
1585 | 0 | if (!pindex->IsValid(BLOCK_VALID_TREE)) { Branch (1585:17): [True: 0, False: 0]
|
1586 | | // We consider the chain that this peer is on invalid. |
1587 | 0 | return; |
1588 | 0 | } |
1589 | | |
1590 | 0 | if (!CanServeWitnesses(peer) && DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) { Branch (1590:17): [True: 0, False: 0]
Branch (1590:45): [True: 0, False: 0]
|
1591 | | // We wouldn't download this block or its descendants from this peer. |
1592 | 0 | return; |
1593 | 0 | } |
1594 | | |
1595 | 0 | if (pindex->nStatus & BLOCK_HAVE_DATA || (activeChain && activeChain->Contains(pindex))) { Branch (1595:17): [True: 0, False: 0]
Branch (1595:55): [True: 0, False: 0]
Branch (1595:70): [True: 0, False: 0]
|
1596 | 0 | if (activeChain && pindex->HaveNumChainTxs()) { Branch (1596:21): [True: 0, False: 0]
Branch (1596:36): [True: 0, False: 0]
|
1597 | 0 | state->pindexLastCommonBlock = pindex; |
1598 | 0 | } |
1599 | 0 | continue; |
1600 | 0 | } |
1601 | | |
1602 | | // Is block in-flight? |
1603 | 0 | if (IsBlockRequested(pindex->GetBlockHash())) { Branch (1603:17): [True: 0, False: 0]
|
1604 | 0 | if (waitingfor == -1) { Branch (1604:21): [True: 0, False: 0]
|
1605 | | // This is the first already-in-flight block. |
1606 | 0 | waitingfor = mapBlocksInFlight.lower_bound(pindex->GetBlockHash())->second.first; |
1607 | 0 | } |
1608 | 0 | continue; |
1609 | 0 | } |
1610 | | |
1611 | | // The block is not already downloaded, and not yet in flight. |
1612 | 0 | if (pindex->nHeight > nWindowEnd) { Branch (1612:17): [True: 0, False: 0]
|
1613 | | // We reached the end of the window. |
1614 | 0 | if (vBlocks.size() == 0 && waitingfor != peer.m_id) { Branch (1614:21): [True: 0, False: 0]
Branch (1614:44): [True: 0, False: 0]
|
1615 | | // We aren't able to fetch anything, but we would be if the download window was one larger. |
1616 | 0 | if (nodeStaller) *nodeStaller = waitingfor; Branch (1616:25): [True: 0, False: 0]
|
1617 | 0 | } |
1618 | 0 | return; |
1619 | 0 | } |
1620 | | |
1621 | | // Don't request blocks that go further than what limited peers can provide |
1622 | 0 | if (is_limited_peer && (state->pindexBestKnownBlock->nHeight - pindex->nHeight >= static_cast<int>(NODE_NETWORK_LIMITED_MIN_BLOCKS) - 2 /* two blocks buffer for possible races */)) { Branch (1622:17): [True: 0, False: 0]
Branch (1622:36): [True: 0, False: 0]
|
1623 | 0 | continue; |
1624 | 0 | } |
1625 | | |
1626 | 0 | vBlocks.push_back(pindex); |
1627 | 0 | if (vBlocks.size() == count) { Branch (1627:17): [True: 0, False: 0]
|
1628 | 0 | return; |
1629 | 0 | } |
1630 | 0 | } |
1631 | 0 | } |
1632 | 0 | } |
1633 | | |
1634 | | } // namespace |
1635 | | |
1636 | | void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer) |
1637 | 781 | { |
1638 | 781 | uint64_t my_services{peer.m_our_services}; |
1639 | 781 | const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())}; |
1640 | 781 | uint64_t nonce = pnode.GetLocalNonce(); |
1641 | 781 | const int nNodeStartingHeight{m_best_height}; |
1642 | 781 | NodeId nodeid = pnode.GetId(); |
1643 | 781 | CAddress addr = pnode.addr; |
1644 | | |
1645 | 781 | CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService(); Branch (1645:25): [True: 583, False: 198]
Branch (1645:46): [True: 583, False: 0]
Branch (1645:64): [True: 455, False: 128]
|
1646 | 781 | uint64_t your_services{addr.nServices}; |
1647 | | |
1648 | 781 | const bool tx_relay{!RejectIncomingTxs(pnode)}; |
1649 | 781 | MakeAndPushMessage(pnode, NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime, |
1650 | 781 | your_services, CNetAddr::V1(addr_you), // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime) |
1651 | 781 | my_services, CNetAddr::V1(CService{}), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime) |
1652 | 781 | nonce, strSubVersion, nNodeStartingHeight, tx_relay); |
1653 | | |
1654 | 781 | if (fLogIPs) { Branch (1654:9): [True: 0, False: 781]
|
1655 | 0 | LogPrint(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); |
1656 | 781 | } else { |
1657 | 781 | LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid); |
1658 | 781 | } |
1659 | 781 | } |
1660 | | |
1661 | | void PeerManagerImpl::AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time) |
1662 | 0 | { |
1663 | 0 | AssertLockHeld(::cs_main); // For m_txrequest |
1664 | 0 | NodeId nodeid = node.GetId(); |
1665 | 0 | if (!node.HasPermission(NetPermissionFlags::Relay) && m_txrequest.Count(nodeid) >= MAX_PEER_TX_ANNOUNCEMENTS) { Branch (1665:9): [True: 0, False: 0]
Branch (1665:59): [True: 0, False: 0]
|
1666 | | // Too many queued announcements from this peer |
1667 | 0 | return; |
1668 | 0 | } |
1669 | 0 | const CNodeState* state = State(nodeid); |
1670 | | |
1671 | | // Decide the TxRequestTracker parameters for this announcement: |
1672 | | // - "preferred": if fPreferredDownload is set (= outbound, or NetPermissionFlags::NoBan permission) |
1673 | | // - "reqtime": current time plus delays for: |
1674 | | // - NONPREF_PEER_TX_DELAY for announcements from non-preferred connections |
1675 | | // - TXID_RELAY_DELAY for txid announcements while wtxid peers are available |
1676 | | // - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least |
1677 | | // MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay). |
1678 | 0 | auto delay{0us}; |
1679 | 0 | const bool preferred = state->fPreferredDownload; |
1680 | 0 | if (!preferred) delay += NONPREF_PEER_TX_DELAY; Branch (1680:9): [True: 0, False: 0]
|
1681 | 0 | if (!gtxid.IsWtxid() && m_wtxid_relay_peers > 0) delay += TXID_RELAY_DELAY; Branch (1681:9): [True: 0, False: 0]
Branch (1681:29): [True: 0, False: 0]
|
1682 | 0 | const bool overloaded = !node.HasPermission(NetPermissionFlags::Relay) && Branch (1682:29): [True: 0, False: 0]
|
1683 | 0 | m_txrequest.CountInFlight(nodeid) >= MAX_PEER_TX_REQUEST_IN_FLIGHT; Branch (1683:9): [True: 0, False: 0]
|
1684 | 0 | if (overloaded) delay += OVERLOADED_PEER_TX_DELAY; Branch (1684:9): [True: 0, False: 0]
|
1685 | 0 | m_txrequest.ReceivedInv(nodeid, gtxid, preferred, current_time + delay); |
1686 | 0 | } |
1687 | | |
1688 | | void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) |
1689 | 0 | { |
1690 | 0 | LOCK(cs_main); |
1691 | 0 | CNodeState *state = State(node); |
1692 | 0 | if (state) state->m_last_block_announcement = time_in_seconds; Branch (1692:9): [True: 0, False: 0]
|
1693 | 0 | } |
1694 | | |
1695 | | void PeerManagerImpl::InitializeNode(CNode& node, ServiceFlags our_services) |
1696 | 1.01k | { |
1697 | 1.01k | NodeId nodeid = node.GetId(); |
1698 | 1.01k | { |
1699 | 1.01k | LOCK(cs_main); |
1700 | 1.01k | m_node_states.emplace_hint(m_node_states.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(node.IsInboundConn())); |
1701 | 1.01k | assert(m_txrequest.Count(nodeid) == 0); |
1702 | 1.01k | } |
1703 | | |
1704 | 1.01k | if (NetPermissions::HasFlag(node.m_permission_flags, NetPermissionFlags::BloomFilter)) { Branch (1704:9): [True: 172, False: 842]
|
1705 | 172 | our_services = static_cast<ServiceFlags>(our_services | NODE_BLOOM); |
1706 | 172 | } |
1707 | | |
1708 | 1.01k | PeerRef peer = std::make_shared<Peer>(nodeid, our_services); |
1709 | 1.01k | { |
1710 | 1.01k | LOCK(m_peer_mutex); |
1711 | 1.01k | m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer); |
1712 | 1.01k | } |
1713 | 1.01k | if (!node.IsInboundConn()) { Branch (1713:9): [True: 647, False: 367]
|
1714 | 647 | PushNodeVersion(node, *peer); |
1715 | 647 | } |
1716 | 1.01k | } |
1717 | | |
1718 | | void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler) |
1719 | 0 | { |
1720 | 0 | std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs(); |
1721 | |
|
1722 | 0 | for (const auto& txid : unbroadcast_txids) { Branch (1722:27): [True: 0, False: 0]
|
1723 | 0 | CTransactionRef tx = m_mempool.get(txid); |
1724 | |
|
1725 | 0 | if (tx != nullptr) { Branch (1725:13): [True: 0, False: 0]
|
1726 | 0 | RelayTransaction(txid, tx->GetWitnessHash()); |
1727 | 0 | } else { |
1728 | 0 | m_mempool.RemoveUnbroadcastTx(txid, true); |
1729 | 0 | } |
1730 | 0 | } |
1731 | | |
1732 | | // Schedule next run for 10-15 minutes in the future. |
1733 | | // We add randomness on every cycle to avoid the possibility of P2P fingerprinting. |
1734 | 0 | const auto delta = 10min + FastRandomContext().randrange<std::chrono::milliseconds>(5min); |
1735 | 0 | scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta); |
1736 | 0 | } |
1737 | | |
1738 | | void PeerManagerImpl::FinalizeNode(const CNode& node) |
1739 | 1.01k | { |
1740 | 1.01k | NodeId nodeid = node.GetId(); |
1741 | 1.01k | { |
1742 | 1.01k | LOCK(cs_main); |
1743 | 1.01k | { |
1744 | | // We remove the PeerRef from g_peer_map here, but we don't always |
1745 | | // destruct the Peer. Sometimes another thread is still holding a |
1746 | | // PeerRef, so the refcount is >= 1. Be careful not to do any |
1747 | | // processing here that assumes Peer won't be changed before it's |
1748 | | // destructed. |
1749 | 1.01k | PeerRef peer = RemovePeer(nodeid); |
1750 | 1.01k | assert(peer != nullptr); |
1751 | 1.01k | m_wtxid_relay_peers -= peer->m_wtxid_relay; |
1752 | 1.01k | assert(m_wtxid_relay_peers >= 0); |
1753 | 1.01k | } |
1754 | 1.01k | CNodeState *state = State(nodeid); |
1755 | 1.01k | assert(state != nullptr); |
1756 | | |
1757 | 1.01k | if (state->fSyncStarted) Branch (1757:9): [True: 85, False: 929]
|
1758 | 85 | nSyncStarted--; |
1759 | | |
1760 | 1.01k | for (const QueuedBlock& entry : state->vBlocksInFlight) { Branch (1760:35): [True: 0, False: 1.01k]
|
1761 | 0 | auto range = mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash()); |
1762 | 0 | while (range.first != range.second) { Branch (1762:16): [True: 0, False: 0]
|
1763 | 0 | auto [node_id, list_it] = range.first->second; |
1764 | 0 | if (node_id != nodeid) { Branch (1764:17): [True: 0, False: 0]
|
1765 | 0 | range.first++; |
1766 | 0 | } else { |
1767 | 0 | range.first = mapBlocksInFlight.erase(range.first); |
1768 | 0 | } |
1769 | 0 | } |
1770 | 0 | } |
1771 | 1.01k | m_orphanage.EraseForPeer(nodeid); |
1772 | 1.01k | m_txrequest.DisconnectedPeer(nodeid); |
1773 | 1.01k | if (m_txreconciliation) m_txreconciliation->ForgetPeer(nodeid); Branch (1773:9): [True: 1.01k, False: 0]
|
1774 | 1.01k | m_num_preferred_download_peers -= state->fPreferredDownload; |
1775 | 1.01k | m_peers_downloading_from -= (!state->vBlocksInFlight.empty()); |
1776 | 1.01k | assert(m_peers_downloading_from >= 0); |
1777 | 1.01k | m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect; |
1778 | 1.01k | assert(m_outbound_peers_with_protect_from_disconnect >= 0); |
1779 | | |
1780 | 1.01k | m_node_states.erase(nodeid); |
1781 | | |
1782 | 1.01k | if (m_node_states.empty()) { Branch (1782:9): [True: 575, False: 439]
|
1783 | | // Do a consistency check after the last peer is removed. |
1784 | 575 | assert(mapBlocksInFlight.empty()); |
1785 | 575 | assert(m_num_preferred_download_peers == 0); |
1786 | 575 | assert(m_peers_downloading_from == 0); |
1787 | 575 | assert(m_outbound_peers_with_protect_from_disconnect == 0); |
1788 | 575 | assert(m_wtxid_relay_peers == 0); |
1789 | 575 | assert(m_txrequest.Size() == 0); |
1790 | 575 | assert(m_orphanage.Size() == 0); |
1791 | 575 | } |
1792 | 1.01k | } // cs_main |
1793 | 1.01k | if (node.fSuccessfullyConnected && Branch (1793:9): [True: 163, False: 851]
|
1794 | 1.01k | !node.IsBlockOnlyConn() && !node.IsInboundConn()) { Branch (1794:9): [True: 147, False: 16]
Branch (1794:36): [True: 111, False: 36]
|
1795 | | // Only change visible addrman state for full outbound peers. We don't |
1796 | | // call Connected() for feeler connections since they don't have |
1797 | | // fSuccessfullyConnected set. |
1798 | 111 | m_addrman.Connected(node.addr); |
1799 | 111 | } |
1800 | 1.01k | { |
1801 | 1.01k | LOCK(m_headers_presync_mutex); |
1802 | 1.01k | m_headers_presync_stats.erase(nodeid); |
1803 | 1.01k | } |
1804 | 1.01k | LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid); |
1805 | 1.01k | } |
1806 | | |
1807 | | bool PeerManagerImpl::HasAllDesirableServiceFlags(ServiceFlags services) const |
1808 | 803 | { |
1809 | | // Shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services) |
1810 | 803 | return !(GetDesirableServiceFlags(services) & (~services)); |
1811 | 803 | } |
1812 | | |
1813 | | ServiceFlags PeerManagerImpl::GetDesirableServiceFlags(ServiceFlags services) const |
1814 | 803 | { |
1815 | 803 | if (services & NODE_NETWORK_LIMITED) { Branch (1815:9): [True: 346, False: 457]
|
1816 | | // Limited peers are desirable when we are close to the tip. |
1817 | 346 | if (ApproximateBestBlockDepth() < NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS) { Branch (1817:13): [True: 0, False: 346]
|
1818 | 0 | return ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS); |
1819 | 0 | } |
1820 | 346 | } |
1821 | 803 | return ServiceFlags(NODE_NETWORK | NODE_WITNESS); |
1822 | 803 | } |
1823 | | |
1824 | | PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const |
1825 | 16.9k | { |
1826 | 16.9k | LOCK(m_peer_mutex); |
1827 | 16.9k | auto it = m_peer_map.find(id); |
1828 | 16.9k | return it != m_peer_map.end() ? it->second : nullptr; Branch (1828:12): [True: 16.9k, False: 0]
|
1829 | 16.9k | } |
1830 | | |
1831 | | PeerRef PeerManagerImpl::RemovePeer(NodeId id) |
1832 | 1.01k | { |
1833 | 1.01k | PeerRef ret; |
1834 | 1.01k | LOCK(m_peer_mutex); |
1835 | 1.01k | auto it = m_peer_map.find(id); |
1836 | 1.01k | if (it != m_peer_map.end()) { Branch (1836:9): [True: 1.01k, False: 0]
|
1837 | 1.01k | ret = std::move(it->second); |
1838 | 1.01k | m_peer_map.erase(it); |
1839 | 1.01k | } |
1840 | 1.01k | return ret; |
1841 | 1.01k | } |
1842 | | |
1843 | | bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const |
1844 | 0 | { |
1845 | 0 | { |
1846 | 0 | LOCK(cs_main); |
1847 | 0 | const CNodeState* state = State(nodeid); |
1848 | 0 | if (state == nullptr) Branch (1848:13): [True: 0, False: 0]
|
1849 | 0 | return false; |
1850 | 0 | stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; Branch (1850:29): [True: 0, False: 0]
|
1851 | 0 | stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1; Branch (1851:31): [True: 0, False: 0]
|
1852 | 0 | for (const QueuedBlock& queue : state->vBlocksInFlight) { Branch (1852:39): [True: 0, False: 0]
|
1853 | 0 | if (queue.pindex) Branch (1853:17): [True: 0, False: 0]
|
1854 | 0 | stats.vHeightInFlight.push_back(queue.pindex->nHeight); |
1855 | 0 | } |
1856 | 0 | } |
1857 | | |
1858 | 0 | PeerRef peer = GetPeerRef(nodeid); |
1859 | 0 | if (peer == nullptr) return false; Branch (1859:9): [True: 0, False: 0]
|
1860 | 0 | stats.their_services = peer->m_their_services; |
1861 | 0 | stats.m_starting_height = peer->m_starting_height; |
1862 | | // It is common for nodes with good ping times to suddenly become lagged, |
1863 | | // due to a new block arriving or other large transfer. |
1864 | | // Merely reporting pingtime might fool the caller into thinking the node was still responsive, |
1865 | | // since pingtime does not update until the ping is complete, which might take a while. |
1866 | | // So, if a ping is taking an unusually long time in flight, |
1867 | | // the caller can immediately detect that this is happening. |
1868 | 0 | auto ping_wait{0us}; |
1869 | 0 | if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) { Branch (1869:9): [True: 0, False: 0]
Branch (1869:9): [True: 0, False: 0]
Branch (1869:43): [True: 0, False: 0]
|
1870 | 0 | ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load(); |
1871 | 0 | } |
1872 | |
|
1873 | 0 | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { Branch (1873:45): [True: 0, False: 0]
|
1874 | 0 | stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs); |
1875 | 0 | stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load(); |
1876 | 0 | } else { |
1877 | 0 | stats.m_relay_txs = false; |
1878 | 0 | stats.m_fee_filter_received = 0; |
1879 | 0 | } |
1880 | |
|
1881 | 0 | stats.m_ping_wait = ping_wait; |
1882 | 0 | stats.m_addr_processed = peer->m_addr_processed.load(); |
1883 | 0 | stats.m_addr_rate_limited = peer->m_addr_rate_limited.load(); |
1884 | 0 | stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load(); |
1885 | 0 | { |
1886 | 0 | LOCK(peer->m_headers_sync_mutex); |
1887 | 0 | if (peer->m_headers_sync) { Branch (1887:13): [True: 0, False: 0]
|
1888 | 0 | stats.presync_height = peer->m_headers_sync->GetPresyncHeight(); |
1889 | 0 | } |
1890 | 0 | } |
1891 | 0 | stats.time_offset = peer->m_time_offset; |
1892 | |
|
1893 | 0 | return true; |
1894 | 0 | } |
1895 | | |
1896 | | PeerManagerInfo PeerManagerImpl::GetInfo() const |
1897 | 0 | { |
1898 | 0 | return PeerManagerInfo{ |
1899 | 0 | .median_outbound_time_offset = m_outbound_time_offsets.Median(), |
1900 | 0 | .ignores_incoming_txs = m_opts.ignore_incoming_txs, |
1901 | 0 | }; |
1902 | 0 | } |
1903 | | |
1904 | | void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx) |
1905 | 0 | { |
1906 | 0 | if (m_opts.max_extra_txs <= 0) Branch (1906:9): [True: 0, False: 0]
|
1907 | 0 | return; |
1908 | 0 | if (!vExtraTxnForCompact.size()) Branch (1908:9): [True: 0, False: 0]
|
1909 | 0 | vExtraTxnForCompact.resize(m_opts.max_extra_txs); |
1910 | 0 | vExtraTxnForCompact[vExtraTxnForCompactIt] = tx; |
1911 | 0 | vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs; |
1912 | 0 | } |
1913 | | |
1914 | | void PeerManagerImpl::Misbehaving(Peer& peer, const std::string& message) |
1915 | 0 | { |
1916 | 0 | LOCK(peer.m_misbehavior_mutex); |
1917 | |
|
1918 | 0 | const std::string message_prefixed = message.empty() ? "" : (": " + message); Branch (1918:42): [True: 0, False: 0]
|
1919 | 0 | peer.m_should_discourage = true; |
1920 | 0 | LogPrint(BCLog::NET, "Misbehaving: peer=%d%s\n", peer.m_id, message_prefixed); |
1921 | 0 | } |
1922 | | |
1923 | | void PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state, |
1924 | | bool via_compact_block, const std::string& message) |
1925 | 0 | { |
1926 | 0 | PeerRef peer{GetPeerRef(nodeid)}; |
1927 | 0 | switch (state.GetResult()) { Branch (1927:13): [True: 0, False: 0]
|
1928 | 0 | case BlockValidationResult::BLOCK_RESULT_UNSET: Branch (1928:5): [True: 0, False: 0]
|
1929 | 0 | break; |
1930 | 0 | case BlockValidationResult::BLOCK_HEADER_LOW_WORK: Branch (1930:5): [True: 0, False: 0]
|
1931 | | // We didn't try to process the block because the header chain may have |
1932 | | // too little work. |
1933 | 0 | break; |
1934 | | // The node is providing invalid data: |
1935 | 0 | case BlockValidationResult::BLOCK_CONSENSUS: Branch (1935:5): [True: 0, False: 0]
|
1936 | 0 | case BlockValidationResult::BLOCK_MUTATED: Branch (1936:5): [True: 0, False: 0]
|
1937 | 0 | if (!via_compact_block) { Branch (1937:13): [True: 0, False: 0]
|
1938 | 0 | if (peer) Misbehaving(*peer, message); Branch (1938:17): [True: 0, False: 0]
|
1939 | 0 | return; |
1940 | 0 | } |
1941 | 0 | break; |
1942 | 0 | case BlockValidationResult::BLOCK_CACHED_INVALID: Branch (1942:5): [True: 0, False: 0]
|
1943 | 0 | { |
1944 | 0 | LOCK(cs_main); |
1945 | 0 | CNodeState *node_state = State(nodeid); |
1946 | 0 | if (node_state == nullptr) { Branch (1946:17): [True: 0, False: 0]
|
1947 | 0 | break; |
1948 | 0 | } |
1949 | | |
1950 | | // Discourage outbound (but not inbound) peers if on an invalid chain. |
1951 | | // Exempt HB compact block peers. Manual connections are always protected from discouragement. |
1952 | 0 | if (!via_compact_block && !node_state->m_is_inbound) { Branch (1952:17): [True: 0, False: 0]
Branch (1952:39): [True: 0, False: 0]
|
1953 | 0 | if (peer) Misbehaving(*peer, message); Branch (1953:21): [True: 0, False: 0]
|
1954 | 0 | return; |
1955 | 0 | } |
1956 | 0 | break; |
1957 | 0 | } |
1958 | 0 | case BlockValidationResult::BLOCK_INVALID_HEADER: Branch (1958:5): [True: 0, False: 0]
|
1959 | 0 | case BlockValidationResult::BLOCK_CHECKPOINT: Branch (1959:5): [True: 0, False: 0]
|
1960 | 0 | case BlockValidationResult::BLOCK_INVALID_PREV: Branch (1960:5): [True: 0, False: 0]
|
1961 | 0 | if (peer) Misbehaving(*peer, message); Branch (1961:13): [True: 0, False: 0]
|
1962 | 0 | return; |
1963 | | // Conflicting (but not necessarily invalid) data or different policy: |
1964 | 0 | case BlockValidationResult::BLOCK_MISSING_PREV: Branch (1964:5): [True: 0, False: 0]
|
1965 | 0 | if (peer) Misbehaving(*peer, message); Branch (1965:13): [True: 0, False: 0]
|
1966 | 0 | return; |
1967 | 0 | case BlockValidationResult::BLOCK_RECENT_CONSENSUS_CHANGE: Branch (1967:5): [True: 0, False: 0]
|
1968 | 0 | case BlockValidationResult::BLOCK_TIME_FUTURE: Branch (1968:5): [True: 0, False: 0]
|
1969 | 0 | break; |
1970 | 0 | } |
1971 | 0 | if (message != "") { Branch (1971:9): [True: 0, False: 0]
|
1972 | 0 | LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message); |
1973 | 0 | } |
1974 | 0 | } |
1975 | | |
1976 | | void PeerManagerImpl::MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state) |
1977 | 0 | { |
1978 | 0 | PeerRef peer{GetPeerRef(nodeid)}; |
1979 | 0 | switch (state.GetResult()) { Branch (1979:13): [True: 0, False: 0]
|
1980 | 0 | case TxValidationResult::TX_RESULT_UNSET: Branch (1980:5): [True: 0, False: 0]
|
1981 | 0 | break; |
1982 | | // The node is providing invalid data: |
1983 | 0 | case TxValidationResult::TX_CONSENSUS: Branch (1983:5): [True: 0, False: 0]
|
1984 | 0 | if (peer) Misbehaving(*peer, ""); Branch (1984:13): [True: 0, False: 0]
|
1985 | 0 | return; |
1986 | | // Conflicting (but not necessarily invalid) data or different policy: |
1987 | 0 | case TxValidationResult::TX_RECENT_CONSENSUS_CHANGE: Branch (1987:5): [True: 0, False: 0]
|
1988 | 0 | case TxValidationResult::TX_INPUTS_NOT_STANDARD: Branch (1988:5): [True: 0, False: 0]
|
1989 | 0 | case TxValidationResult::TX_NOT_STANDARD: Branch (1989:5): [True: 0, False: 0]
|
1990 | 0 | case TxValidationResult::TX_MISSING_INPUTS: Branch (1990:5): [True: 0, False: 0]
|
1991 | 0 | case TxValidationResult::TX_PREMATURE_SPEND: Branch (1991:5): [True: 0, False: 0]
|
1992 | 0 | case TxValidationResult::TX_WITNESS_MUTATED: Branch (1992:5): [True: 0, False: 0]
|
1993 | 0 | case TxValidationResult::TX_WITNESS_STRIPPED: Branch (1993:5): [True: 0, False: 0]
|
1994 | 0 | case TxValidationResult::TX_CONFLICT: Branch (1994:5): [True: 0, False: 0]
|
1995 | 0 | case TxValidationResult::TX_MEMPOOL_POLICY: Branch (1995:5): [True: 0, False: 0]
|
1996 | 0 | case TxValidationResult::TX_NO_MEMPOOL: Branch (1996:5): [True: 0, False: 0]
|
1997 | 0 | case TxValidationResult::TX_RECONSIDERABLE: Branch (1997:5): [True: 0, False: 0]
|
1998 | 0 | case TxValidationResult::TX_UNKNOWN: Branch (1998:5): [True: 0, False: 0]
|
1999 | 0 | break; |
2000 | 0 | } |
2001 | 0 | } |
2002 | | |
2003 | | bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex) |
2004 | 0 | { |
2005 | 0 | AssertLockHeld(cs_main); |
2006 | 0 | if (m_chainman.ActiveChain().Contains(pindex)) return true; Branch (2006:9): [True: 0, False: 0]
|
2007 | 0 | return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (m_chainman.m_best_header != nullptr) && Branch (2007:12): [True: 0, False: 0]
Branch (2007:52): [True: 0, False: 0]
|
2008 | 0 | (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) && Branch (2008:12): [True: 0, False: 0]
|
2009 | 0 | (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT); Branch (2009:12): [True: 0, False: 0]
|
2010 | 0 | } |
2011 | | |
2012 | | std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index) |
2013 | 0 | { |
2014 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) return "Loading blocks ..."; Branch (2014:9): [True: 0, False: 0]
|
2015 | | |
2016 | | // Ensure this peer exists and hasn't been disconnected |
2017 | 0 | PeerRef peer = GetPeerRef(peer_id); |
2018 | 0 | if (peer == nullptr) return "Peer does not exist"; Branch (2018:9): [True: 0, False: 0]
|
2019 | | |
2020 | | // Ignore pre-segwit peers |
2021 | 0 | if (!CanServeWitnesses(*peer)) return "Pre-SegWit peer"; Branch (2021:9): [True: 0, False: 0]
|
2022 | | |
2023 | 0 | LOCK(cs_main); |
2024 | | |
2025 | | // Forget about all prior requests |
2026 | 0 | RemoveBlockRequest(block_index.GetBlockHash(), std::nullopt); |
2027 | | |
2028 | | // Mark block as in-flight |
2029 | 0 | if (!BlockRequested(peer_id, block_index)) return "Already requested from this peer"; Branch (2029:9): [True: 0, False: 0]
|
2030 | | |
2031 | | // Construct message to request the block |
2032 | 0 | const uint256& hash{block_index.GetBlockHash()}; |
2033 | 0 | std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)}; |
2034 | | |
2035 | | // Send block request message to the peer |
2036 | 0 | bool success = m_connman.ForNode(peer_id, [this, &invs](CNode* node) { |
2037 | 0 | this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs); |
2038 | 0 | return true; |
2039 | 0 | }); |
2040 | |
|
2041 | 0 | if (!success) return "Peer not fully connected"; Branch (2041:9): [True: 0, False: 0]
|
2042 | | |
2043 | 0 | LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n", |
2044 | 0 | hash.ToString(), peer_id); |
2045 | 0 | return std::nullopt; |
2046 | 0 | } |
2047 | | |
2048 | | std::unique_ptr<PeerManager> PeerManager::make(CConnman& connman, AddrMan& addrman, |
2049 | | BanMan* banman, ChainstateManager& chainman, |
2050 | | CTxMemPool& pool, node::Warnings& warnings, Options opts) |
2051 | 575 | { |
2052 | 575 | return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman, pool, warnings, opts); |
2053 | 575 | } |
2054 | | |
2055 | | PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman, |
2056 | | BanMan* banman, ChainstateManager& chainman, |
2057 | | CTxMemPool& pool, node::Warnings& warnings, Options opts) |
2058 | 575 | : m_rng{opts.deterministic_rng}, |
2059 | 575 | m_fee_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}, m_rng}, |
2060 | 575 | m_chainparams(chainman.GetParams()), |
2061 | 575 | m_connman(connman), |
2062 | 575 | m_addrman(addrman), |
2063 | 575 | m_banman(banman), |
2064 | 575 | m_chainman(chainman), |
2065 | 575 | m_mempool(pool), |
2066 | 575 | m_warnings{warnings}, |
2067 | 575 | m_opts{opts} |
2068 | 575 | { |
2069 | | // While Erlay support is incomplete, it must be enabled explicitly via -txreconciliation. |
2070 | | // This argument can go away after Erlay support is complete. |
2071 | 575 | if (opts.reconcile_txs) { Branch (2071:9): [True: 575, False: 0]
|
2072 | 575 | m_txreconciliation = std::make_unique<TxReconciliationTracker>(TXRECONCILIATION_VERSION); |
2073 | 575 | } |
2074 | 575 | } |
2075 | | |
2076 | | void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler) |
2077 | 0 | { |
2078 | | // Stale tip checking and peer eviction are on two different timers, but we |
2079 | | // don't want them to get out of sync due to drift in the scheduler, so we |
2080 | | // combine them in one function and schedule at the quicker (peer-eviction) |
2081 | | // timer. |
2082 | 0 | static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer"); |
2083 | 0 | scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL}); |
2084 | | |
2085 | | // schedule next run for 10-15 minutes in the future |
2086 | 0 | const auto delta = 10min + FastRandomContext().randrange<std::chrono::milliseconds>(5min); |
2087 | 0 | scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta); |
2088 | 0 | } |
2089 | | |
2090 | | /** |
2091 | | * Evict orphan txn pool entries based on a newly connected |
2092 | | * block, remember the recently confirmed transactions, and delete tracked |
2093 | | * announcements for them. Also save the time of the last tip update and |
2094 | | * possibly reduce dynamic block stalling timeout. |
2095 | | */ |
2096 | | void PeerManagerImpl::BlockConnected( |
2097 | | ChainstateRole role, |
2098 | | const std::shared_ptr<const CBlock>& pblock, |
2099 | | const CBlockIndex* pindex) |
2100 | 0 | { |
2101 | | // Update this for all chainstate roles so that we don't mistakenly see peers |
2102 | | // helping us do background IBD as having a stale tip. |
2103 | 0 | m_last_tip_update = GetTime<std::chrono::seconds>(); |
2104 | | |
2105 | | // In case the dynamic timeout was doubled once or more, reduce it slowly back to its default value |
2106 | 0 | auto stalling_timeout = m_block_stalling_timeout.load(); |
2107 | 0 | Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT); |
2108 | 0 | if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) { Branch (2108:9): [True: 0, False: 0]
|
2109 | 0 | const auto new_timeout = std::max(std::chrono::duration_cast<std::chrono::seconds>(stalling_timeout * 0.85), BLOCK_STALLING_TIMEOUT_DEFAULT); |
2110 | 0 | if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { Branch (2110:13): [True: 0, False: 0]
|
2111 | 0 | LogPrint(BCLog::NET, "Decreased stalling timeout to %d seconds\n", count_seconds(new_timeout)); |
2112 | 0 | } |
2113 | 0 | } |
2114 | | |
2115 | | // The following task can be skipped since we don't maintain a mempool for |
2116 | | // the ibd/background chainstate. |
2117 | 0 | if (role == ChainstateRole::BACKGROUND) { Branch (2117:9): [True: 0, False: 0]
|
2118 | 0 | return; |
2119 | 0 | } |
2120 | 0 | m_orphanage.EraseForBlock(*pblock); |
2121 | |
|
2122 | 0 | { |
2123 | 0 | LOCK(m_recent_confirmed_transactions_mutex); |
2124 | 0 | for (const auto& ptx : pblock->vtx) { Branch (2124:30): [True: 0, False: 0]
|
2125 | 0 | RecentConfirmedTransactionsFilter().insert(ptx->GetHash().ToUint256()); |
2126 | 0 | if (ptx->HasWitness()) { Branch (2126:17): [True: 0, False: 0]
|
2127 | 0 | RecentConfirmedTransactionsFilter().insert(ptx->GetWitnessHash().ToUint256()); |
2128 | 0 | } |
2129 | 0 | } |
2130 | 0 | } |
2131 | 0 | { |
2132 | 0 | LOCK(cs_main); |
2133 | 0 | for (const auto& ptx : pblock->vtx) { Branch (2133:30): [True: 0, False: 0]
|
2134 | 0 | m_txrequest.ForgetTxHash(ptx->GetHash()); |
2135 | 0 | m_txrequest.ForgetTxHash(ptx->GetWitnessHash()); |
2136 | 0 | } |
2137 | 0 | } |
2138 | 0 | } |
2139 | | |
2140 | | void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) |
2141 | 0 | { |
2142 | | // To avoid relay problems with transactions that were previously |
2143 | | // confirmed, clear our filter of recently confirmed transactions whenever |
2144 | | // there's a reorg. |
2145 | | // This means that in a 1-block reorg (where 1 block is disconnected and |
2146 | | // then another block reconnected), our filter will drop to having only one |
2147 | | // block's worth of transactions in it, but that should be fine, since |
2148 | | // presumably the most common case of relaying a confirmed transaction |
2149 | | // should be just after a new block containing it is found. |
2150 | 0 | LOCK(m_recent_confirmed_transactions_mutex); |
2151 | 0 | RecentConfirmedTransactionsFilter().reset(); |
2152 | 0 | } |
2153 | | |
2154 | | /** |
2155 | | * Maintain state about the best-seen block and fast-announce a compact block |
2156 | | * to compatible peers. |
2157 | | */ |
2158 | | void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) |
2159 | 0 | { |
2160 | 0 | auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock, FastRandomContext().rand64()); |
2161 | |
|
2162 | 0 | LOCK(cs_main); |
2163 | |
|
2164 | 0 | if (pindex->nHeight <= m_highest_fast_announce) Branch (2164:9): [True: 0, False: 0]
|
2165 | 0 | return; |
2166 | 0 | m_highest_fast_announce = pindex->nHeight; |
2167 | |
|
2168 | 0 | if (!DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) return; Branch (2168:9): [True: 0, False: 0]
|
2169 | | |
2170 | 0 | uint256 hashBlock(pblock->GetHash()); |
2171 | 0 | const std::shared_future<CSerializedNetMsg> lazy_ser{ |
2172 | 0 | std::async(std::launch::deferred, [&] { return NetMsg::Make(NetMsgType::CMPCTBLOCK, *pcmpctblock); })}; |
2173 | |
|
2174 | 0 | { |
2175 | 0 | auto most_recent_block_txs = std::make_unique<std::map<uint256, CTransactionRef>>(); |
2176 | 0 | for (const auto& tx : pblock->vtx) { Branch (2176:29): [True: 0, False: 0]
|
2177 | 0 | most_recent_block_txs->emplace(tx->GetHash(), tx); |
2178 | 0 | most_recent_block_txs->emplace(tx->GetWitnessHash(), tx); |
2179 | 0 | } |
2180 | |
|
2181 | 0 | LOCK(m_most_recent_block_mutex); |
2182 | 0 | m_most_recent_block_hash = hashBlock; |
2183 | 0 | m_most_recent_block = pblock; |
2184 | 0 | m_most_recent_compact_block = pcmpctblock; |
2185 | 0 | m_most_recent_block_txs = std::move(most_recent_block_txs); |
2186 | 0 | } |
2187 | |
|
2188 | 0 | m_connman.ForEachNode([this, pindex, &lazy_ser, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
2189 | 0 | AssertLockHeld(::cs_main); |
2190 | |
|
2191 | 0 | if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect) Branch (2191:13): [True: 0, False: 0]
Branch (2191:70): [True: 0, False: 0]
|
2192 | 0 | return; |
2193 | 0 | ProcessBlockAvailability(pnode->GetId()); |
2194 | 0 | CNodeState &state = *State(pnode->GetId()); |
2195 | | // If the peer has, or we announced to them the previous block already, |
2196 | | // but we don't think they have this one, go ahead and announce it |
2197 | 0 | if (state.m_requested_hb_cmpctblocks && !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) { Branch (2197:13): [True: 0, False: 0]
Branch (2197:49): [True: 0, False: 0]
Branch (2197:83): [True: 0, False: 0]
|
2198 | |
|
2199 | 0 | LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock", |
2200 | 0 | hashBlock.ToString(), pnode->GetId()); |
2201 | |
|
2202 | 0 | const CSerializedNetMsg& ser_cmpctblock{lazy_ser.get()}; |
2203 | 0 | PushMessage(*pnode, ser_cmpctblock.Copy()); |
2204 | 0 | state.pindexBestHeaderSent = pindex; |
2205 | 0 | } |
2206 | 0 | }); |
2207 | 0 | } |
2208 | | |
2209 | | /** |
2210 | | * Update our best height and announce any block hashes which weren't previously |
2211 | | * in m_chainman.ActiveChain() to our peers. |
2212 | | */ |
2213 | | void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) |
2214 | 0 | { |
2215 | 0 | SetBestBlock(pindexNew->nHeight, std::chrono::seconds{pindexNew->GetBlockTime()}); |
2216 | | |
2217 | | // Don't relay inventory during initial block download. |
2218 | 0 | if (fInitialDownload) return; Branch (2218:9): [True: 0, False: 0]
|
2219 | | |
2220 | | // Find the hashes of all blocks that weren't previously in the best chain. |
2221 | 0 | std::vector<uint256> vHashes; |
2222 | 0 | const CBlockIndex *pindexToAnnounce = pindexNew; |
2223 | 0 | while (pindexToAnnounce != pindexFork) { Branch (2223:12): [True: 0, False: 0]
|
2224 | 0 | vHashes.push_back(pindexToAnnounce->GetBlockHash()); |
2225 | 0 | pindexToAnnounce = pindexToAnnounce->pprev; |
2226 | 0 | if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) { Branch (2226:13): [True: 0, False: 0]
|
2227 | | // Limit announcements in case of a huge reorganization. |
2228 | | // Rely on the peer's synchronization mechanism in that case. |
2229 | 0 | break; |
2230 | 0 | } |
2231 | 0 | } |
2232 | |
|
2233 | 0 | { |
2234 | 0 | LOCK(m_peer_mutex); |
2235 | 0 | for (auto& it : m_peer_map) { Branch (2235:23): [True: 0, False: 0]
|
2236 | 0 | Peer& peer = *it.second; |
2237 | 0 | LOCK(peer.m_block_inv_mutex); |
2238 | 0 | for (const uint256& hash : reverse_iterate(vHashes)) { Branch (2238:38): [True: 0, False: 0]
|
2239 | 0 | peer.m_blocks_for_headers_relay.push_back(hash); |
2240 | 0 | } |
2241 | 0 | } |
2242 | 0 | } |
2243 | |
|
2244 | 0 | m_connman.WakeMessageHandler(); |
2245 | 0 | } |
2246 | | |
2247 | | /** |
2248 | | * Handle invalid block rejection and consequent peer discouragement, maintain which |
2249 | | * peers announce compact blocks. |
2250 | | */ |
2251 | | void PeerManagerImpl::BlockChecked(const CBlock& block, const BlockValidationState& state) |
2252 | 0 | { |
2253 | 0 | LOCK(cs_main); |
2254 | |
|
2255 | 0 | const uint256 hash(block.GetHash()); |
2256 | 0 | std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash); |
2257 | | |
2258 | | // If the block failed validation, we know where it came from and we're still connected |
2259 | | // to that peer, maybe punish. |
2260 | 0 | if (state.IsInvalid() && Branch (2260:9): [True: 0, False: 0]
Branch (2260:9): [True: 0, False: 0]
|
2261 | 0 | it != mapBlockSource.end() && Branch (2261:9): [True: 0, False: 0]
|
2262 | 0 | State(it->second.first)) { Branch (2262:9): [True: 0, False: 0]
|
2263 | 0 | MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second); |
2264 | 0 | } |
2265 | | // Check that: |
2266 | | // 1. The block is valid |
2267 | | // 2. We're not in initial block download |
2268 | | // 3. This is currently the best block we're aware of. We haven't updated |
2269 | | // the tip yet so we have no way to check this directly here. Instead we |
2270 | | // just check that there are currently no other blocks in flight. |
2271 | 0 | else if (state.IsValid() && Branch (2271:14): [True: 0, False: 0]
|
2272 | 0 | !m_chainman.IsInitialBlockDownload() && Branch (2272:14): [True: 0, False: 0]
|
2273 | 0 | mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) { Branch (2273:14): [True: 0, False: 0]
|
2274 | 0 | if (it != mapBlockSource.end()) { Branch (2274:13): [True: 0, False: 0]
|
2275 | 0 | MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first); |
2276 | 0 | } |
2277 | 0 | } |
2278 | 0 | if (it != mapBlockSource.end()) Branch (2278:9): [True: 0, False: 0]
|
2279 | 0 | mapBlockSource.erase(it); |
2280 | 0 | } |
2281 | | |
2282 | | ////////////////////////////////////////////////////////////////////////////// |
2283 | | // |
2284 | | // Messages |
2285 | | // |
2286 | | |
2287 | | |
2288 | | bool PeerManagerImpl::AlreadyHaveTx(const GenTxid& gtxid, bool include_reconsiderable) |
2289 | 0 | { |
2290 | 0 | if (m_chainman.ActiveChain().Tip()->GetBlockHash() != hashRecentRejectsChainTip) { Branch (2290:9): [True: 0, False: 0]
|
2291 | | // If the chain tip has changed previously rejected transactions |
2292 | | // might be now valid, e.g. due to a nLockTime'd tx becoming valid, |
2293 | | // or a double-spend. Reset the rejects filter and give those |
2294 | | // txs a second chance. |
2295 | 0 | hashRecentRejectsChainTip = m_chainman.ActiveChain().Tip()->GetBlockHash(); |
2296 | 0 | RecentRejectsFilter().reset(); |
2297 | 0 | RecentRejectsReconsiderableFilter().reset(); |
2298 | 0 | } |
2299 | |
|
2300 | 0 | const uint256& hash = gtxid.GetHash(); |
2301 | |
|
2302 | 0 | if (gtxid.IsWtxid()) { Branch (2302:9): [True: 0, False: 0]
|
2303 | | // Normal query by wtxid. |
2304 | 0 | if (m_orphanage.HaveTx(Wtxid::FromUint256(hash))) return true; Branch (2304:13): [True: 0, False: 0]
|
2305 | 0 | } else { |
2306 | | // Never query by txid: it is possible that the transaction in the orphanage has the same |
2307 | | // txid but a different witness, which would give us a false positive result. If we decided |
2308 | | // not to request the transaction based on this result, an attacker could prevent us from |
2309 | | // downloading a transaction by intentionally creating a malleated version of it. While |
2310 | | // only one (or none!) of these transactions can ultimately be confirmed, we have no way of |
2311 | | // discerning which one that is, so the orphanage can store multiple transactions with the |
2312 | | // same txid. |
2313 | | // |
2314 | | // While we won't query by txid, we can try to "guess" what the wtxid is based on the txid. |
2315 | | // A non-segwit transaction's txid == wtxid. Query this txid "casted" to a wtxid. This will |
2316 | | // help us find non-segwit transactions, saving bandwidth, and should have no false positives. |
2317 | 0 | if (m_orphanage.HaveTx(Wtxid::FromUint256(hash))) return true; Branch (2317:13): [True: 0, False: 0]
|
2318 | 0 | } |
2319 | | |
2320 | 0 | if (include_reconsiderable && RecentRejectsReconsiderableFilter().contains(hash)) return true; Branch (2320:9): [True: 0, False: 0]
Branch (2320:35): [True: 0, False: 0]
|
2321 | | |
2322 | 0 | { |
2323 | 0 | LOCK(m_recent_confirmed_transactions_mutex); |
2324 | 0 | if (RecentConfirmedTransactionsFilter().contains(hash)) return true; Branch (2324:13): [True: 0, False: 0]
|
2325 | 0 | } |
2326 | | |
2327 | 0 | return RecentRejectsFilter().contains(hash) || m_mempool.exists(gtxid); Branch (2327:12): [True: 0, False: 0]
Branch (2327:52): [True: 0, False: 0]
|
2328 | 0 | } |
2329 | | |
2330 | | bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash) |
2331 | 0 | { |
2332 | 0 | return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr; |
2333 | 0 | } |
2334 | | |
2335 | | void PeerManagerImpl::SendPings() |
2336 | 0 | { |
2337 | 0 | LOCK(m_peer_mutex); |
2338 | 0 | for(auto& it : m_peer_map) it.second->m_ping_queued = true; Branch (2338:18): [True: 0, False: 0]
|
2339 | 0 | } |
2340 | | |
2341 | | void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid) |
2342 | 0 | { |
2343 | 0 | LOCK(m_peer_mutex); |
2344 | 0 | for(auto& it : m_peer_map) { Branch (2344:18): [True: 0, False: 0]
|
2345 | 0 | Peer& peer = *it.second; |
2346 | 0 | auto tx_relay = peer.GetTxRelay(); |
2347 | 0 | if (!tx_relay) continue; Branch (2347:13): [True: 0, False: 0]
|
2348 | | |
2349 | 0 | LOCK(tx_relay->m_tx_inventory_mutex); |
2350 | | // Only queue transactions for announcement once the version handshake |
2351 | | // is completed. The time of arrival for these transactions is |
2352 | | // otherwise at risk of leaking to a spy, if the spy is able to |
2353 | | // distinguish transactions received during the handshake from the rest |
2354 | | // in the announcement. |
2355 | 0 | if (tx_relay->m_next_inv_send_time == 0s) continue; Branch (2355:13): [True: 0, False: 0]
|
2356 | | |
2357 | 0 | const uint256& hash{peer.m_wtxid_relay ? wtxid : txid}; Branch (2357:29): [True: 0, False: 0]
|
2358 | 0 | if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) { Branch (2358:13): [True: 0, False: 0]
|
2359 | 0 | tx_relay->m_tx_inventory_to_send.insert(hash); |
2360 | 0 | } |
2361 | 0 | }; |
2362 | 0 | } |
2363 | | |
2364 | | void PeerManagerImpl::RelayAddress(NodeId originator, |
2365 | | const CAddress& addr, |
2366 | | bool fReachable) |
2367 | 0 | { |
2368 | | // We choose the same nodes within a given 24h window (if the list of connected |
2369 | | // nodes does not change) and we don't relay to nodes that already know an |
2370 | | // address. So within 24h we will likely relay a given address once. This is to |
2371 | | // prevent a peer from unjustly giving their address better propagation by sending |
2372 | | // it to us repeatedly. |
2373 | |
|
2374 | 0 | if (!fReachable && !addr.IsRelayable()) return; Branch (2374:9): [True: 0, False: 0]
Branch (2374:24): [True: 0, False: 0]
|
2375 | | |
2376 | | // Relay to a limited number of other nodes |
2377 | | // Use deterministic randomness to send to the same nodes for 24 hours |
2378 | | // at a time so the m_addr_knowns of the chosen nodes prevent repeats |
2379 | 0 | const uint64_t hash_addr{CServiceHash(0, 0)(addr)}; |
2380 | 0 | const auto current_time{GetTime<std::chrono::seconds>()}; |
2381 | | // Adding address hash makes exact rotation time different per address, while preserving periodicity. |
2382 | 0 | const uint64_t time_addr{(static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) / count_seconds(ROTATE_ADDR_RELAY_DEST_INTERVAL)}; |
2383 | 0 | const CSipHasher hasher{m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY) |
2384 | 0 | .Write(hash_addr) |
2385 | 0 | .Write(time_addr)}; |
2386 | | |
2387 | | // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers. |
2388 | 0 | unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1; Branch (2388:33): [True: 0, False: 0]
Branch (2388:47): [True: 0, False: 0]
|
2389 | |
|
2390 | 0 | std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}}; |
2391 | 0 | assert(nRelayNodes <= best.size()); |
2392 | | |
2393 | 0 | LOCK(m_peer_mutex); |
2394 | |
|
2395 | 0 | for (auto& [id, peer] : m_peer_map) { Branch (2395:27): [True: 0, False: 0]
|
2396 | 0 | if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) { Branch (2396:13): [True: 0, False: 0]
Branch (2396:43): [True: 0, False: 0]
Branch (2396:63): [True: 0, False: 0]
|
2397 | 0 | uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize(); |
2398 | 0 | for (unsigned int i = 0; i < nRelayNodes; i++) { Branch (2398:38): [True: 0, False: 0]
|
2399 | 0 | if (hashKey > best[i].first) { Branch (2399:22): [True: 0, False: 0]
|
2400 | 0 | std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1); |
2401 | 0 | best[i] = std::make_pair(hashKey, peer.get()); |
2402 | 0 | break; |
2403 | 0 | } |
2404 | 0 | } |
2405 | 0 | } |
2406 | 0 | }; |
2407 | |
|
2408 | 0 | for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) { Branch (2408:30): [True: 0, False: 0]
Branch (2408:49): [True: 0, False: 0]
|
2409 | 0 | PushAddress(*best[i].second, addr); |
2410 | 0 | } |
2411 | 0 | } |
2412 | | |
2413 | | void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv) |
2414 | 0 | { |
2415 | 0 | std::shared_ptr<const CBlock> a_recent_block; |
2416 | 0 | std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block; |
2417 | 0 | { |
2418 | 0 | LOCK(m_most_recent_block_mutex); |
2419 | 0 | a_recent_block = m_most_recent_block; |
2420 | 0 | a_recent_compact_block = m_most_recent_compact_block; |
2421 | 0 | } |
2422 | |
|
2423 | 0 | bool need_activate_chain = false; |
2424 | 0 | { |
2425 | 0 | LOCK(cs_main); |
2426 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash); |
2427 | 0 | if (pindex) { Branch (2427:13): [True: 0, False: 0]
|
2428 | 0 | if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) && Branch (2428:17): [True: 0, False: 0]
Branch (2428:46): [True: 0, False: 0]
|
2429 | 0 | pindex->IsValid(BLOCK_VALID_TREE)) { Branch (2429:21): [True: 0, False: 0]
|
2430 | | // If we have the block and all of its parents, but have not yet validated it, |
2431 | | // we might be in the middle of connecting it (ie in the unlock of cs_main |
2432 | | // before ActivateBestChain but after AcceptBlock). |
2433 | | // In this case, we need to run ActivateBestChain prior to checking the relay |
2434 | | // conditions below. |
2435 | 0 | need_activate_chain = true; |
2436 | 0 | } |
2437 | 0 | } |
2438 | 0 | } // release cs_main before calling ActivateBestChain |
2439 | 0 | if (need_activate_chain) { Branch (2439:9): [True: 0, False: 0]
|
2440 | 0 | BlockValidationState state; |
2441 | 0 | if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) { Branch (2441:13): [True: 0, False: 0]
|
2442 | 0 | LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString()); |
2443 | 0 | } |
2444 | 0 | } |
2445 | |
|
2446 | 0 | const CBlockIndex* pindex{nullptr}; |
2447 | 0 | const CBlockIndex* tip{nullptr}; |
2448 | 0 | bool can_direct_fetch{false}; |
2449 | 0 | FlatFilePos block_pos{}; |
2450 | 0 | { |
2451 | 0 | LOCK(cs_main); |
2452 | 0 | pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash); |
2453 | 0 | if (!pindex) { Branch (2453:13): [True: 0, False: 0]
|
2454 | 0 | return; |
2455 | 0 | } |
2456 | 0 | if (!BlockRequestAllowed(pindex)) { Branch (2456:13): [True: 0, False: 0]
|
2457 | 0 | LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId()); |
2458 | 0 | return; |
2459 | 0 | } |
2460 | | // disconnect node in case we have reached the outbound limit for serving historical blocks |
2461 | 0 | if (m_connman.OutboundTargetReached(true) && Branch (2461:13): [True: 0, False: 0]
|
2462 | 0 | (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) && Branch (2462:15): [True: 0, False: 0]
Branch (2462:56): [True: 0, False: 0]
Branch (2462:151): [True: 0, False: 0]
|
2463 | 0 | !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target Branch (2463:13): [True: 0, False: 0]
|
2464 | 0 | ) { |
2465 | 0 | LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom.GetId()); |
2466 | 0 | pfrom.fDisconnect = true; |
2467 | 0 | return; |
2468 | 0 | } |
2469 | 0 | tip = m_chainman.ActiveChain().Tip(); |
2470 | | // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold |
2471 | 0 | if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && ( Branch (2471:13): [True: 0, False: 0]
|
2472 | 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 */) ) Branch (2472:18): [True: 0, False: 0]
Branch (2472:92): [True: 0, False: 0]
Branch (2472:150): [True: 0, False: 0]
|
2473 | 0 | )) { |
2474 | 0 | LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, disconnect peer=%d\n", pfrom.GetId()); |
2475 | | //disconnect node and prevent it from stalling (would otherwise wait for the missing block) |
2476 | 0 | pfrom.fDisconnect = true; |
2477 | 0 | return; |
2478 | 0 | } |
2479 | | // Pruned nodes may have deleted the block, so check whether |
2480 | | // it's available before trying to send. |
2481 | 0 | if (!(pindex->nStatus & BLOCK_HAVE_DATA)) { Branch (2481:13): [True: 0, False: 0]
|
2482 | 0 | return; |
2483 | 0 | } |
2484 | 0 | can_direct_fetch = CanDirectFetch(); |
2485 | 0 | block_pos = pindex->GetBlockPos(); |
2486 | 0 | } |
2487 | | |
2488 | 0 | std::shared_ptr<const CBlock> pblock; |
2489 | 0 | if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) { Branch (2489:9): [True: 0, False: 0]
Branch (2489:9): [True: 0, False: 0]
Branch (2489:27): [True: 0, False: 0]
|
2490 | 0 | pblock = a_recent_block; |
2491 | 0 | } else if (inv.IsMsgWitnessBlk()) { Branch (2491:16): [True: 0, False: 0]
|
2492 | | // Fast-path: in this case it is possible to serve the block directly from disk, |
2493 | | // as the network format matches the format on disk |
2494 | 0 | std::vector<uint8_t> block_data; |
2495 | 0 | if (!m_chainman.m_blockman.ReadRawBlockFromDisk(block_data, block_pos)) { Branch (2495:13): [True: 0, False: 0]
|
2496 | 0 | if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) { |
2497 | 0 | LogPrint(BCLog::NET, "Block was pruned before it could be read, disconnect peer=%s\n", pfrom.GetId()); |
2498 | 0 | } else { |
2499 | 0 | LogError("Cannot load block from disk, disconnect peer=%d\n", pfrom.GetId()); |
2500 | 0 | } |
2501 | 0 | pfrom.fDisconnect = true; |
2502 | 0 | return; |
2503 | 0 | } |
2504 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, Span{block_data}); |
2505 | | // Don't set pblock as we've sent the block |
2506 | 0 | } else { |
2507 | | // Send block from disk |
2508 | 0 | std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>(); |
2509 | 0 | if (!m_chainman.m_blockman.ReadBlockFromDisk(*pblockRead, block_pos)) { Branch (2509:13): [True: 0, False: 0]
|
2510 | 0 | if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) { |
2511 | 0 | LogPrint(BCLog::NET, "Block was pruned before it could be read, disconnect peer=%s\n", pfrom.GetId()); |
2512 | 0 | } else { |
2513 | 0 | LogError("Cannot load block from disk, disconnect peer=%d\n", pfrom.GetId()); |
2514 | 0 | } |
2515 | 0 | pfrom.fDisconnect = true; |
2516 | 0 | return; |
2517 | 0 | } |
2518 | 0 | pblock = pblockRead; |
2519 | 0 | } |
2520 | 0 | if (pblock) { Branch (2520:9): [True: 0, False: 0]
|
2521 | 0 | if (inv.IsMsgBlk()) { Branch (2521:13): [True: 0, False: 0]
|
2522 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_NO_WITNESS(*pblock)); |
2523 | 0 | } else if (inv.IsMsgWitnessBlk()) { Branch (2523:20): [True: 0, False: 0]
|
2524 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock)); |
2525 | 0 | } else if (inv.IsMsgFilteredBlk()) { Branch (2525:20): [True: 0, False: 0]
|
2526 | 0 | bool sendMerkleBlock = false; |
2527 | 0 | CMerkleBlock merkleBlock; |
2528 | 0 | if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) { Branch (2528:52): [True: 0, False: 0]
|
2529 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); |
2530 | 0 | if (tx_relay->m_bloom_filter) { Branch (2530:21): [True: 0, False: 0]
|
2531 | 0 | sendMerkleBlock = true; |
2532 | 0 | merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter); |
2533 | 0 | } |
2534 | 0 | } |
2535 | 0 | if (sendMerkleBlock) { Branch (2535:17): [True: 0, False: 0]
|
2536 | 0 | MakeAndPushMessage(pfrom, NetMsgType::MERKLEBLOCK, merkleBlock); |
2537 | | // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see |
2538 | | // This avoids hurting performance by pointlessly requiring a round-trip |
2539 | | // Note that there is currently no way for a node to request any single transactions we didn't send here - |
2540 | | // they must either disconnect and retry or request the full block. |
2541 | | // Thus, the protocol spec specified allows for us to provide duplicate txn here, |
2542 | | // however we MUST always provide at least what the remote peer needs |
2543 | 0 | typedef std::pair<unsigned int, uint256> PairType; |
2544 | 0 | for (PairType& pair : merkleBlock.vMatchedTxn) Branch (2544:37): [True: 0, False: 0]
|
2545 | 0 | MakeAndPushMessage(pfrom, NetMsgType::TX, TX_NO_WITNESS(*pblock->vtx[pair.first])); |
2546 | 0 | } |
2547 | | // else |
2548 | | // no response |
2549 | 0 | } else if (inv.IsMsgCmpctBlk()) { Branch (2549:20): [True: 0, False: 0]
|
2550 | | // If a peer is asking for old blocks, we're almost guaranteed |
2551 | | // they won't have a useful mempool to match against a compact block, |
2552 | | // and we don't feel like constructing the object for them, so |
2553 | | // instead we respond with the full, non-compact block. |
2554 | 0 | if (can_direct_fetch && pindex->nHeight >= tip->nHeight - MAX_CMPCTBLOCK_DEPTH) { Branch (2554:17): [True: 0, False: 0]
Branch (2554:37): [True: 0, False: 0]
|
2555 | 0 | if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) { Branch (2555:21): [True: 0, False: 0]
Branch (2555:21): [True: 0, False: 0]
Branch (2555:47): [True: 0, False: 0]
|
2556 | 0 | MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, *a_recent_compact_block); |
2557 | 0 | } else { |
2558 | 0 | CBlockHeaderAndShortTxIDs cmpctblock{*pblock, FastRandomContext().rand64()}; |
2559 | 0 | MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, cmpctblock); |
2560 | 0 | } |
2561 | 0 | } else { |
2562 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock)); |
2563 | 0 | } |
2564 | 0 | } |
2565 | 0 | } |
2566 | |
|
2567 | 0 | { |
2568 | 0 | LOCK(peer.m_block_inv_mutex); |
2569 | | // Trigger the peer node to send a getblocks request for the next batch of inventory |
2570 | 0 | if (inv.hash == peer.m_continuation_block) { Branch (2570:13): [True: 0, False: 0]
|
2571 | | // Send immediately. This must send even if redundant, |
2572 | | // and we want it right after the last block so they don't |
2573 | | // wait for other stuff first. |
2574 | 0 | std::vector<CInv> vInv; |
2575 | 0 | vInv.emplace_back(MSG_BLOCK, tip->GetBlockHash()); |
2576 | 0 | MakeAndPushMessage(pfrom, NetMsgType::INV, vInv); |
2577 | 0 | peer.m_continuation_block.SetNull(); |
2578 | 0 | } |
2579 | 0 | } |
2580 | 0 | } |
2581 | | |
2582 | | CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid) |
2583 | 0 | { |
2584 | | // If a tx was in the mempool prior to the last INV for this peer, permit the request. |
2585 | 0 | auto txinfo = m_mempool.info_for_relay(gtxid, tx_relay.m_last_inv_sequence); |
2586 | 0 | if (txinfo.tx) { Branch (2586:9): [True: 0, False: 0]
|
2587 | 0 | return std::move(txinfo.tx); |
2588 | 0 | } |
2589 | | |
2590 | | // Or it might be from the most recent block |
2591 | 0 | { |
2592 | 0 | LOCK(m_most_recent_block_mutex); |
2593 | 0 | if (m_most_recent_block_txs != nullptr) { Branch (2593:13): [True: 0, False: 0]
|
2594 | 0 | auto it = m_most_recent_block_txs->find(gtxid.GetHash()); |
2595 | 0 | if (it != m_most_recent_block_txs->end()) return it->second; Branch (2595:17): [True: 0, False: 0]
|
2596 | 0 | } |
2597 | 0 | } |
2598 | | |
2599 | 0 | return {}; |
2600 | 0 | } |
2601 | | |
2602 | | void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) |
2603 | 0 | { |
2604 | 0 | AssertLockNotHeld(cs_main); |
2605 | |
|
2606 | 0 | auto tx_relay = peer.GetTxRelay(); |
2607 | |
|
2608 | 0 | std::deque<CInv>::iterator it = peer.m_getdata_requests.begin(); |
2609 | 0 | std::vector<CInv> vNotFound; |
2610 | | |
2611 | | // Process as many TX items from the front of the getdata queue as |
2612 | | // possible, since they're common and it's efficient to batch process |
2613 | | // them. |
2614 | 0 | while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) { Branch (2614:12): [True: 0, False: 0]
Branch (2614:12): [True: 0, False: 0]
Branch (2614:51): [True: 0, False: 0]
|
2615 | 0 | if (interruptMsgProc) return; Branch (2615:13): [True: 0, False: 0]
|
2616 | | // The send buffer provides backpressure. If there's no space in |
2617 | | // the buffer, pause processing until the next call. |
2618 | 0 | if (pfrom.fPauseSend) break; Branch (2618:13): [True: 0, False: 0]
|
2619 | | |
2620 | 0 | const CInv &inv = *it++; |
2621 | |
|
2622 | 0 | if (tx_relay == nullptr) { Branch (2622:13): [True: 0, False: 0]
|
2623 | | // Ignore GETDATA requests for transactions from block-relay-only |
2624 | | // peers and peers that asked us not to announce transactions. |
2625 | 0 | continue; |
2626 | 0 | } |
2627 | | |
2628 | 0 | CTransactionRef tx = FindTxForGetData(*tx_relay, ToGenTxid(inv)); |
2629 | 0 | if (tx) { Branch (2629:13): [True: 0, False: 0]
|
2630 | | // WTX and WITNESS_TX imply we serialize with witness |
2631 | 0 | const auto maybe_with_witness = (inv.IsMsgTx() ? TX_NO_WITNESS : TX_WITH_WITNESS); Branch (2631:46): [True: 0, False: 0]
|
2632 | 0 | MakeAndPushMessage(pfrom, NetMsgType::TX, maybe_with_witness(*tx)); |
2633 | 0 | m_mempool.RemoveUnbroadcastTx(tx->GetHash()); |
2634 | 0 | } else { |
2635 | 0 | vNotFound.push_back(inv); |
2636 | 0 | } |
2637 | 0 | } |
2638 | | |
2639 | | // Only process one BLOCK item per call, since they're uncommon and can be |
2640 | | // expensive to process. |
2641 | 0 | if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) { Branch (2641:9): [True: 0, False: 0]
Branch (2641:9): [True: 0, False: 0]
Branch (2641:48): [True: 0, False: 0]
|
2642 | 0 | const CInv &inv = *it++; |
2643 | 0 | if (inv.IsGenBlkMsg()) { Branch (2643:13): [True: 0, False: 0]
|
2644 | 0 | ProcessGetBlockData(pfrom, peer, inv); |
2645 | 0 | } |
2646 | | // else: If the first item on the queue is an unknown type, we erase it |
2647 | | // and continue processing the queue on the next call. |
2648 | 0 | } |
2649 | |
|
2650 | 0 | peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it); |
2651 | |
|
2652 | 0 | if (!vNotFound.empty()) { Branch (2652:9): [True: 0, False: 0]
|
2653 | | // Let the peer know that we didn't find what it asked for, so it doesn't |
2654 | | // have to wait around forever. |
2655 | | // SPV clients care about this message: it's needed when they are |
2656 | | // recursively walking the dependencies of relevant unconfirmed |
2657 | | // transactions. SPV clients want to do that because they want to know |
2658 | | // about (and store and rebroadcast and risk analyze) the dependencies |
2659 | | // of transactions relevant to them, without having to download the |
2660 | | // entire memory pool. |
2661 | | // Also, other nodes can use these messages to automatically request a |
2662 | | // transaction from some other peer that announced it, and stop |
2663 | | // waiting for us to respond. |
2664 | | // In normal operation, we often send NOTFOUND messages for parents of |
2665 | | // transactions that we relay; if a peer is missing a parent, they may |
2666 | | // assume we have them and request the parents from us. |
2667 | 0 | MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound); |
2668 | 0 | } |
2669 | 0 | } |
2670 | | |
2671 | | uint32_t PeerManagerImpl::GetFetchFlags(const Peer& peer) const |
2672 | 0 | { |
2673 | 0 | uint32_t nFetchFlags = 0; |
2674 | 0 | if (CanServeWitnesses(peer)) { Branch (2674:9): [True: 0, False: 0]
|
2675 | 0 | nFetchFlags |= MSG_WITNESS_FLAG; |
2676 | 0 | } |
2677 | 0 | return nFetchFlags; |
2678 | 0 | } |
2679 | | |
2680 | | void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req) |
2681 | 0 | { |
2682 | 0 | BlockTransactions resp(req); |
2683 | 0 | for (size_t i = 0; i < req.indexes.size(); i++) { Branch (2683:24): [True: 0, False: 0]
|
2684 | 0 | if (req.indexes[i] >= block.vtx.size()) { Branch (2684:13): [True: 0, False: 0]
|
2685 | 0 | Misbehaving(peer, "getblocktxn with out-of-bounds tx indices"); |
2686 | 0 | return; |
2687 | 0 | } |
2688 | 0 | resp.txn[i] = block.vtx[req.indexes[i]]; |
2689 | 0 | } |
2690 | | |
2691 | 0 | MakeAndPushMessage(pfrom, NetMsgType::BLOCKTXN, resp); |
2692 | 0 | } |
2693 | | |
2694 | | bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer) |
2695 | 0 | { |
2696 | | // Do these headers have proof-of-work matching what's claimed? |
2697 | 0 | if (!HasValidProofOfWork(headers, consensusParams)) { Branch (2697:9): [True: 0, False: 0]
|
2698 | 0 | Misbehaving(peer, "header with invalid proof of work"); |
2699 | 0 | return false; |
2700 | 0 | } |
2701 | | |
2702 | | // Are these headers connected to each other? |
2703 | 0 | if (!CheckHeadersAreContinuous(headers)) { Branch (2703:9): [True: 0, False: 0]
|
2704 | 0 | Misbehaving(peer, "non-continuous headers sequence"); |
2705 | 0 | return false; |
2706 | 0 | } |
2707 | 0 | return true; |
2708 | 0 | } |
2709 | | |
2710 | | arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold() |
2711 | 0 | { |
2712 | 0 | arith_uint256 near_chaintip_work = 0; |
2713 | 0 | LOCK(cs_main); |
2714 | 0 | if (m_chainman.ActiveChain().Tip() != nullptr) { Branch (2714:9): [True: 0, False: 0]
|
2715 | 0 | const CBlockIndex *tip = m_chainman.ActiveChain().Tip(); |
2716 | | // Use a 144 block buffer, so that we'll accept headers that fork from |
2717 | | // near our tip. |
2718 | 0 | near_chaintip_work = tip->nChainWork - std::min<arith_uint256>(144*GetBlockProof(*tip), tip->nChainWork); |
2719 | 0 | } |
2720 | 0 | return std::max(near_chaintip_work, m_chainman.MinimumChainWork()); |
2721 | 0 | } |
2722 | | |
2723 | | /** |
2724 | | * Special handling for unconnecting headers that might be part of a block |
2725 | | * announcement. |
2726 | | * |
2727 | | * We'll send a getheaders message in response to try to connect the chain. |
2728 | | */ |
2729 | | void PeerManagerImpl::HandleUnconnectingHeaders(CNode& pfrom, Peer& peer, |
2730 | | const std::vector<CBlockHeader>& headers) |
2731 | 0 | { |
2732 | | // Try to fill in the missing headers. |
2733 | 0 | const CBlockIndex* best_header{WITH_LOCK(cs_main, return m_chainman.m_best_header)}; |
2734 | 0 | if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) { Branch (2734:9): [True: 0, False: 0]
|
2735 | 0 | LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d)\n", |
2736 | 0 | headers[0].GetHash().ToString(), |
2737 | 0 | headers[0].hashPrevBlock.ToString(), |
2738 | 0 | best_header->nHeight, |
2739 | 0 | pfrom.GetId()); |
2740 | 0 | } |
2741 | | |
2742 | | // Set hashLastUnknownBlock for this peer, so that if we |
2743 | | // eventually get the headers - even from a different peer - |
2744 | | // we can use this peer to download. |
2745 | 0 | WITH_LOCK(cs_main, UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash())); |
2746 | 0 | } |
2747 | | |
2748 | | bool PeerManagerImpl::CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const |
2749 | 0 | { |
2750 | 0 | uint256 hashLastBlock; |
2751 | 0 | for (const CBlockHeader& header : headers) { Branch (2751:37): [True: 0, False: 0]
|
2752 | 0 | if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) { Branch (2752:13): [True: 0, False: 0]
Branch (2752:40): [True: 0, False: 0]
|
2753 | 0 | return false; |
2754 | 0 | } |
2755 | 0 | hashLastBlock = header.GetHash(); |
2756 | 0 | } |
2757 | 0 | return true; |
2758 | 0 | } |
2759 | | |
2760 | | bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers) |
2761 | 0 | { |
2762 | 0 | if (peer.m_headers_sync) { Branch (2762:9): [True: 0, False: 0]
|
2763 | 0 | auto result = peer.m_headers_sync->ProcessNextHeaders(headers, headers.size() == MAX_HEADERS_RESULTS); |
2764 | | // If it is a valid continuation, we should treat the existing getheaders request as responded to. |
2765 | 0 | if (result.success) peer.m_last_getheaders_timestamp = {}; Branch (2765:13): [True: 0, False: 0]
|
2766 | 0 | if (result.request_more) { Branch (2766:13): [True: 0, False: 0]
|
2767 | 0 | auto locator = peer.m_headers_sync->NextHeadersRequestLocator(); |
2768 | | // If we were instructed to ask for a locator, it should not be empty. |
2769 | 0 | Assume(!locator.vHave.empty()); |
2770 | | // We can only be instructed to request more if processing was successful. |
2771 | 0 | Assume(result.success); |
2772 | 0 | if (!locator.vHave.empty()) { Branch (2772:17): [True: 0, False: 0]
|
2773 | | // It should be impossible for the getheaders request to fail, |
2774 | | // because we just cleared the last getheaders timestamp. |
2775 | 0 | bool sent_getheaders = MaybeSendGetHeaders(pfrom, locator, peer); |
2776 | 0 | Assume(sent_getheaders); |
2777 | 0 | LogPrint(BCLog::NET, "more getheaders (from %s) to peer=%d\n", |
2778 | 0 | locator.vHave.front().ToString(), pfrom.GetId()); |
2779 | 0 | } |
2780 | 0 | } |
2781 | |
|
2782 | 0 | if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) { Branch (2782:13): [True: 0, False: 0]
|
2783 | 0 | peer.m_headers_sync.reset(nullptr); |
2784 | | |
2785 | | // Delete this peer's entry in m_headers_presync_stats. |
2786 | | // If this is m_headers_presync_bestpeer, it will be replaced later |
2787 | | // by the next peer that triggers the else{} branch below. |
2788 | 0 | LOCK(m_headers_presync_mutex); |
2789 | 0 | m_headers_presync_stats.erase(pfrom.GetId()); |
2790 | 0 | } else { |
2791 | | // Build statistics for this peer's sync. |
2792 | 0 | HeadersPresyncStats stats; |
2793 | 0 | stats.first = peer.m_headers_sync->GetPresyncWork(); |
2794 | 0 | if (peer.m_headers_sync->GetState() == HeadersSyncState::State::PRESYNC) { Branch (2794:17): [True: 0, False: 0]
|
2795 | 0 | stats.second = {peer.m_headers_sync->GetPresyncHeight(), |
2796 | 0 | peer.m_headers_sync->GetPresyncTime()}; |
2797 | 0 | } |
2798 | | |
2799 | | // Update statistics in stats. |
2800 | 0 | LOCK(m_headers_presync_mutex); |
2801 | 0 | m_headers_presync_stats[pfrom.GetId()] = stats; |
2802 | 0 | auto best_it = m_headers_presync_stats.find(m_headers_presync_bestpeer); |
2803 | 0 | bool best_updated = false; |
2804 | 0 | if (best_it == m_headers_presync_stats.end()) { Branch (2804:17): [True: 0, False: 0]
|
2805 | | // If the cached best peer is outdated, iterate over all remaining ones (including |
2806 | | // newly updated one) to find the best one. |
2807 | 0 | NodeId peer_best{-1}; |
2808 | 0 | const HeadersPresyncStats* stat_best{nullptr}; |
2809 | 0 | for (const auto& [peer, stat] : m_headers_presync_stats) { Branch (2809:47): [True: 0, False: 0]
|
2810 | 0 | if (!stat_best || stat > *stat_best) { Branch (2810:25): [True: 0, False: 0]
Branch (2810:39): [True: 0, False: 0]
|
2811 | 0 | peer_best = peer; |
2812 | 0 | stat_best = &stat; |
2813 | 0 | } |
2814 | 0 | } |
2815 | 0 | m_headers_presync_bestpeer = peer_best; |
2816 | 0 | best_updated = (peer_best == pfrom.GetId()); |
2817 | 0 | } else if (best_it->first == pfrom.GetId() || stats > best_it->second) { Branch (2817:24): [True: 0, False: 0]
Branch (2817:59): [True: 0, False: 0]
|
2818 | | // pfrom was and remains the best peer, or pfrom just became best. |
2819 | 0 | m_headers_presync_bestpeer = pfrom.GetId(); |
2820 | 0 | best_updated = true; |
2821 | 0 | } |
2822 | 0 | if (best_updated && stats.second.has_value()) { Branch (2822:17): [True: 0, False: 0]
Branch (2822:33): [True: 0, False: 0]
|
2823 | | // If the best peer updated, and it is in its first phase, signal. |
2824 | 0 | m_headers_presync_should_signal = true; |
2825 | 0 | } |
2826 | 0 | } |
2827 | |
|
2828 | 0 | if (result.success) { Branch (2828:13): [True: 0, False: 0]
|
2829 | | // We only overwrite the headers passed in if processing was |
2830 | | // successful. |
2831 | 0 | headers.swap(result.pow_validated_headers); |
2832 | 0 | } |
2833 | |
|
2834 | 0 | return result.success; |
2835 | 0 | } |
2836 | | // Either we didn't have a sync in progress, or something went wrong |
2837 | | // processing these headers, or we are returning headers to the caller to |
2838 | | // process. |
2839 | 0 | return false; |
2840 | 0 | } |
2841 | | |
2842 | | bool PeerManagerImpl::TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex* chain_start_header, std::vector<CBlockHeader>& headers) |
2843 | 0 | { |
2844 | | // Calculate the claimed total work on this chain. |
2845 | 0 | arith_uint256 total_work = chain_start_header->nChainWork + CalculateClaimedHeadersWork(headers); |
2846 | | |
2847 | | // Our dynamic anti-DoS threshold (minimum work required on a headers chain |
2848 | | // before we'll store it) |
2849 | 0 | arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold(); |
2850 | | |
2851 | | // Avoid DoS via low-difficulty-headers by only processing if the headers |
2852 | | // are part of a chain with sufficient work. |
2853 | 0 | if (total_work < minimum_chain_work) { Branch (2853:9): [True: 0, False: 0]
|
2854 | | // Only try to sync with this peer if their headers message was full; |
2855 | | // otherwise they don't have more headers after this so no point in |
2856 | | // trying to sync their too-little-work chain. |
2857 | 0 | if (headers.size() == MAX_HEADERS_RESULTS) { Branch (2857:13): [True: 0, False: 0]
|
2858 | | // Note: we could advance to the last header in this set that is |
2859 | | // known to us, rather than starting at the first header (which we |
2860 | | // may already have); however this is unlikely to matter much since |
2861 | | // ProcessHeadersMessage() already handles the case where all |
2862 | | // headers in a received message are already known and are |
2863 | | // ancestors of m_best_header or chainActive.Tip(), by skipping |
2864 | | // this logic in that case. So even if the first header in this set |
2865 | | // of headers is known, some header in this set must be new, so |
2866 | | // advancing to the first unknown header would be a small effect. |
2867 | 0 | LOCK(peer.m_headers_sync_mutex); |
2868 | 0 | peer.m_headers_sync.reset(new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(), |
2869 | 0 | chain_start_header, minimum_chain_work)); |
2870 | | |
2871 | | // Now a HeadersSyncState object for tracking this synchronization |
2872 | | // is created, process the headers using it as normal. Failures are |
2873 | | // handled inside of IsContinuationOfLowWorkHeadersSync. |
2874 | 0 | (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers); |
2875 | 0 | } else { |
2876 | 0 | LogPrint(BCLog::NET, "Ignoring low-work chain (height=%u) from peer=%d\n", chain_start_header->nHeight + headers.size(), pfrom.GetId()); |
2877 | 0 | } |
2878 | | |
2879 | | // The peer has not yet given us a chain that meets our work threshold, |
2880 | | // so we want to prevent further processing of the headers in any case. |
2881 | 0 | headers = {}; |
2882 | 0 | return true; |
2883 | 0 | } |
2884 | | |
2885 | 0 | return false; |
2886 | 0 | } |
2887 | | |
2888 | | bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) |
2889 | 0 | { |
2890 | 0 | if (header == nullptr) { Branch (2890:9): [True: 0, False: 0]
|
2891 | 0 | return false; |
2892 | 0 | } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) { Branch (2892:16): [True: 0, False: 0]
Branch (2892:55): [True: 0, False: 0]
|
2893 | 0 | return true; |
2894 | 0 | } else if (m_chainman.ActiveChain().Contains(header)) { Branch (2894:16): [True: 0, False: 0]
|
2895 | 0 | return true; |
2896 | 0 | } |
2897 | 0 | return false; |
2898 | 0 | } |
2899 | | |
2900 | | bool PeerManagerImpl::MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) |
2901 | 85 | { |
2902 | 85 | const auto current_time = NodeClock::now(); |
2903 | | |
2904 | | // Only allow a new getheaders message to go out if we don't have a recent |
2905 | | // one already in-flight |
2906 | 85 | if (current_time - peer.m_last_getheaders_timestamp > HEADERS_RESPONSE_TIME) { Branch (2906:9): [True: 85, False: 0]
|
2907 | 85 | MakeAndPushMessage(pfrom, NetMsgType::GETHEADERS, locator, uint256()); |
2908 | 85 | peer.m_last_getheaders_timestamp = current_time; |
2909 | 85 | return true; |
2910 | 85 | } |
2911 | 0 | return false; |
2912 | 85 | } |
2913 | | |
2914 | | /* |
2915 | | * Given a new headers tip ending in last_header, potentially request blocks towards that tip. |
2916 | | * We require that the given tip have at least as much work as our tip, and for |
2917 | | * our current tip to be "close to synced" (see CanDirectFetch()). |
2918 | | */ |
2919 | | void PeerManagerImpl::HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header) |
2920 | 0 | { |
2921 | 0 | LOCK(cs_main); |
2922 | 0 | CNodeState *nodestate = State(pfrom.GetId()); |
2923 | |
|
2924 | 0 | if (CanDirectFetch() && last_header.IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork) { Branch (2924:9): [True: 0, False: 0]
Branch (2924:29): [True: 0, False: 0]
Branch (2924:70): [True: 0, False: 0]
|
2925 | 0 | std::vector<const CBlockIndex*> vToFetch; |
2926 | 0 | const CBlockIndex* pindexWalk{&last_header}; |
2927 | | // Calculate all the blocks we'd need to switch to last_header, up to a limit. |
2928 | 0 | while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { Branch (2928:16): [True: 0, False: 0]
Branch (2928:30): [True: 0, False: 0]
Branch (2928:80): [True: 0, False: 0]
|
2929 | 0 | if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) && Branch (2929:17): [True: 0, False: 0]
Branch (2929:17): [True: 0, False: 0]
|
2930 | 0 | !IsBlockRequested(pindexWalk->GetBlockHash()) && Branch (2930:21): [True: 0, False: 0]
|
2931 | 0 | (!DeploymentActiveAt(*pindexWalk, m_chainman, Consensus::DEPLOYMENT_SEGWIT) || CanServeWitnesses(peer))) { Branch (2931:22): [True: 0, False: 0]
Branch (2931:100): [True: 0, False: 0]
|
2932 | | // We don't have this block, and it's not yet in flight. |
2933 | 0 | vToFetch.push_back(pindexWalk); |
2934 | 0 | } |
2935 | 0 | pindexWalk = pindexWalk->pprev; |
2936 | 0 | } |
2937 | | // If pindexWalk still isn't on our main chain, we're looking at a |
2938 | | // very large reorg at a time we think we're close to caught up to |
2939 | | // the main chain -- this shouldn't really happen. Bail out on the |
2940 | | // direct fetch and rely on parallel download instead. |
2941 | 0 | if (!m_chainman.ActiveChain().Contains(pindexWalk)) { Branch (2941:13): [True: 0, False: 0]
|
2942 | 0 | LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n", |
2943 | 0 | last_header.GetBlockHash().ToString(), |
2944 | 0 | last_header.nHeight); |
2945 | 0 | } else { |
2946 | 0 | std::vector<CInv> vGetData; |
2947 | | // Download as much as possible, from earliest to latest. |
2948 | 0 | for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) { Branch (2948:44): [True: 0, False: 0]
|
2949 | 0 | if (nodestate->vBlocksInFlight.size() >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { Branch (2949:21): [True: 0, False: 0]
|
2950 | | // Can't download any more from this peer |
2951 | 0 | break; |
2952 | 0 | } |
2953 | 0 | uint32_t nFetchFlags = GetFetchFlags(peer); |
2954 | 0 | vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()); |
2955 | 0 | BlockRequested(pfrom.GetId(), *pindex); |
2956 | 0 | LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n", |
2957 | 0 | pindex->GetBlockHash().ToString(), pfrom.GetId()); |
2958 | 0 | } |
2959 | 0 | if (vGetData.size() > 1) { Branch (2959:17): [True: 0, False: 0]
|
2960 | 0 | LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n", |
2961 | 0 | last_header.GetBlockHash().ToString(), |
2962 | 0 | last_header.nHeight); |
2963 | 0 | } |
2964 | 0 | if (vGetData.size() > 0) { Branch (2964:17): [True: 0, False: 0]
|
2965 | 0 | if (!m_opts.ignore_incoming_txs && Branch (2965:21): [True: 0, False: 0]
|
2966 | 0 | nodestate->m_provides_cmpctblocks && Branch (2966:25): [True: 0, False: 0]
|
2967 | 0 | vGetData.size() == 1 && Branch (2967:25): [True: 0, False: 0]
|
2968 | 0 | mapBlocksInFlight.size() == 1 && Branch (2968:25): [True: 0, False: 0]
|
2969 | 0 | last_header.pprev->IsValid(BLOCK_VALID_CHAIN)) { Branch (2969:25): [True: 0, False: 0]
|
2970 | | // In any case, we want to download using a compact block, not a regular one |
2971 | 0 | vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash); |
2972 | 0 | } |
2973 | 0 | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vGetData); |
2974 | 0 | } |
2975 | 0 | } |
2976 | 0 | } |
2977 | 0 | } |
2978 | | |
2979 | | /** |
2980 | | * Given receipt of headers from a peer ending in last_header, along with |
2981 | | * whether that header was new and whether the headers message was full, |
2982 | | * update the state we keep for the peer. |
2983 | | */ |
2984 | | void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, |
2985 | | const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers) |
2986 | 0 | { |
2987 | 0 | LOCK(cs_main); |
2988 | 0 | CNodeState *nodestate = State(pfrom.GetId()); |
2989 | |
|
2990 | 0 | UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash()); |
2991 | | |
2992 | | // From here, pindexBestKnownBlock should be guaranteed to be non-null, |
2993 | | // because it is set in UpdateBlockAvailability. Some nullptr checks |
2994 | | // are still present, however, as belt-and-suspenders. |
2995 | |
|
2996 | 0 | if (received_new_header && last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) { Branch (2996:9): [True: 0, False: 0]
Branch (2996:32): [True: 0, False: 0]
|
2997 | 0 | nodestate->m_last_block_announcement = GetTime(); |
2998 | 0 | } |
2999 | | |
3000 | | // If we're in IBD, we want outbound peers that will serve us a useful |
3001 | | // chain. Disconnect peers that are on chains with insufficient work. |
3002 | 0 | if (m_chainman.IsInitialBlockDownload() && !may_have_more_headers) { Branch (3002:9): [True: 0, False: 0]
Branch (3002:48): [True: 0, False: 0]
|
3003 | | // If the peer has no more headers to give us, then we know we have |
3004 | | // their tip. |
3005 | 0 | if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) { Branch (3005:13): [True: 0, False: 0]
Branch (3005:48): [True: 0, False: 0]
|
3006 | | // This peer has too little work on their headers chain to help |
3007 | | // us sync -- disconnect if it is an outbound disconnection |
3008 | | // candidate. |
3009 | | // Note: We compare their tip to the minimum chain work (rather than |
3010 | | // m_chainman.ActiveChain().Tip()) because we won't start block download |
3011 | | // until we have a headers chain that has at least |
3012 | | // the minimum chain work, even if a peer has a chain past our tip, |
3013 | | // as an anti-DoS measure. |
3014 | 0 | if (pfrom.IsOutboundOrBlockRelayConn()) { Branch (3014:17): [True: 0, False: 0]
|
3015 | 0 | LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom.GetId()); |
3016 | 0 | pfrom.fDisconnect = true; |
3017 | 0 | } |
3018 | 0 | } |
3019 | 0 | } |
3020 | | |
3021 | | // If this is an outbound full-relay peer, check to see if we should protect |
3022 | | // it from the bad/lagging chain logic. |
3023 | | // Note that outbound block-relay peers are excluded from this protection, and |
3024 | | // thus always subject to eviction under the bad/lagging chain logic. |
3025 | | // See ChainSyncTimeoutState. |
3026 | 0 | if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) { Branch (3026:9): [True: 0, False: 0]
Branch (3026:31): [True: 0, False: 0]
Branch (3026:61): [True: 0, False: 0]
|
3027 | 0 | if (m_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) { Branch (3027:13): [True: 0, False: 0]
Branch (3027:110): [True: 0, False: 0]
Branch (3027:203): [True: 0, False: 0]
|
3028 | 0 | LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId()); |
3029 | 0 | nodestate->m_chain_sync.m_protect = true; |
3030 | 0 | ++m_outbound_peers_with_protect_from_disconnect; |
3031 | 0 | } |
3032 | 0 | } |
3033 | 0 | } |
3034 | | |
3035 | | void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, Peer& peer, |
3036 | | std::vector<CBlockHeader>&& headers, |
3037 | | bool via_compact_block) |
3038 | 0 | { |
3039 | 0 | size_t nCount = headers.size(); |
3040 | |
|
3041 | 0 | if (nCount == 0) { Branch (3041:9): [True: 0, False: 0]
|
3042 | | // Nothing interesting. Stop asking this peers for more headers. |
3043 | | // If we were in the middle of headers sync, receiving an empty headers |
3044 | | // message suggests that the peer suddenly has nothing to give us |
3045 | | // (perhaps it reorged to our chain). Clear download state for this peer. |
3046 | 0 | LOCK(peer.m_headers_sync_mutex); |
3047 | 0 | if (peer.m_headers_sync) { Branch (3047:13): [True: 0, False: 0]
|
3048 | 0 | peer.m_headers_sync.reset(nullptr); |
3049 | 0 | LOCK(m_headers_presync_mutex); |
3050 | 0 | m_headers_presync_stats.erase(pfrom.GetId()); |
3051 | 0 | } |
3052 | | // A headers message with no headers cannot be an announcement, so assume |
3053 | | // it is a response to our last getheaders request, if there is one. |
3054 | 0 | peer.m_last_getheaders_timestamp = {}; |
3055 | 0 | return; |
3056 | 0 | } |
3057 | | |
3058 | | // Before we do any processing, make sure these pass basic sanity checks. |
3059 | | // We'll rely on headers having valid proof-of-work further down, as an |
3060 | | // anti-DoS criteria (note: this check is required before passing any |
3061 | | // headers into HeadersSyncState). |
3062 | 0 | if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) { Branch (3062:9): [True: 0, False: 0]
|
3063 | | // Misbehaving() calls are handled within CheckHeadersPoW(), so we can |
3064 | | // just return. (Note that even if a header is announced via compact |
3065 | | // block, the header itself should be valid, so this type of error can |
3066 | | // always be punished.) |
3067 | 0 | return; |
3068 | 0 | } |
3069 | | |
3070 | 0 | const CBlockIndex *pindexLast = nullptr; |
3071 | | |
3072 | | // We'll set already_validated_work to true if these headers are |
3073 | | // successfully processed as part of a low-work headers sync in progress |
3074 | | // (either in PRESYNC or REDOWNLOAD phase). |
3075 | | // If true, this will mean that any headers returned to us (ie during |
3076 | | // REDOWNLOAD) can be validated without further anti-DoS checks. |
3077 | 0 | bool already_validated_work = false; |
3078 | | |
3079 | | // If we're in the middle of headers sync, let it do its magic. |
3080 | 0 | bool have_headers_sync = false; |
3081 | 0 | { |
3082 | 0 | LOCK(peer.m_headers_sync_mutex); |
3083 | |
|
3084 | 0 | already_validated_work = IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers); |
3085 | | |
3086 | | // The headers we passed in may have been: |
3087 | | // - untouched, perhaps if no headers-sync was in progress, or some |
3088 | | // failure occurred |
3089 | | // - erased, such as if the headers were successfully processed and no |
3090 | | // additional headers processing needs to take place (such as if we |
3091 | | // are still in PRESYNC) |
3092 | | // - replaced with headers that are now ready for validation, such as |
3093 | | // during the REDOWNLOAD phase of a low-work headers sync. |
3094 | | // So just check whether we still have headers that we need to process, |
3095 | | // or not. |
3096 | 0 | if (headers.empty()) { Branch (3096:13): [True: 0, False: 0]
|
3097 | 0 | return; |
3098 | 0 | } |
3099 | | |
3100 | 0 | have_headers_sync = !!peer.m_headers_sync; |
3101 | 0 | } |
3102 | | |
3103 | | // Do these headers connect to something in our block index? |
3104 | 0 | const CBlockIndex *chain_start_header{WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock))}; |
3105 | 0 | bool headers_connect_blockindex{chain_start_header != nullptr}; |
3106 | |
|
3107 | 0 | if (!headers_connect_blockindex) { Branch (3107:9): [True: 0, False: 0]
|
3108 | | // This could be a BIP 130 block announcement, use |
3109 | | // special logic for handling headers that don't connect, as this |
3110 | | // could be benign. |
3111 | 0 | HandleUnconnectingHeaders(pfrom, peer, headers); |
3112 | 0 | return; |
3113 | 0 | } |
3114 | | |
3115 | | // If headers connect, assume that this is in response to any outstanding getheaders |
3116 | | // request we may have sent, and clear out the time of our last request. Non-connecting |
3117 | | // headers cannot be a response to a getheaders request. |
3118 | 0 | peer.m_last_getheaders_timestamp = {}; |
3119 | | |
3120 | | // If the headers we received are already in memory and an ancestor of |
3121 | | // m_best_header or our tip, skip anti-DoS checks. These headers will not |
3122 | | // use any more memory (and we are not leaking information that could be |
3123 | | // used to fingerprint us). |
3124 | 0 | const CBlockIndex *last_received_header{nullptr}; |
3125 | 0 | { |
3126 | 0 | LOCK(cs_main); |
3127 | 0 | last_received_header = m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash()); |
3128 | 0 | if (IsAncestorOfBestHeaderOrTip(last_received_header)) { Branch (3128:13): [True: 0, False: 0]
|
3129 | 0 | already_validated_work = true; |
3130 | 0 | } |
3131 | 0 | } |
3132 | | |
3133 | | // If our peer has NetPermissionFlags::NoBan privileges, then bypass our |
3134 | | // anti-DoS logic (this saves bandwidth when we connect to a trusted peer |
3135 | | // on startup). |
3136 | 0 | if (pfrom.HasPermission(NetPermissionFlags::NoBan)) { Branch (3136:9): [True: 0, False: 0]
|
3137 | 0 | already_validated_work = true; |
3138 | 0 | } |
3139 | | |
3140 | | // At this point, the headers connect to something in our block index. |
3141 | | // Do anti-DoS checks to determine if we should process or store for later |
3142 | | // processing. |
3143 | 0 | if (!already_validated_work && TryLowWorkHeadersSync(peer, pfrom, Branch (3143:9): [True: 0, False: 0]
Branch (3143:36): [True: 0, False: 0]
|
3144 | 0 | chain_start_header, headers)) { |
3145 | | // If we successfully started a low-work headers sync, then there |
3146 | | // should be no headers to process any further. |
3147 | 0 | Assume(headers.empty()); |
3148 | 0 | return; |
3149 | 0 | } |
3150 | | |
3151 | | // At this point, we have a set of headers with sufficient work on them |
3152 | | // which can be processed. |
3153 | | |
3154 | | // If we don't have the last header, then this peer will have given us |
3155 | | // something new (if these headers are valid). |
3156 | 0 | bool received_new_header{last_received_header == nullptr}; |
3157 | | |
3158 | | // Now process all the headers. |
3159 | 0 | BlockValidationState state; |
3160 | 0 | if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true, state, &pindexLast)) { Branch (3160:9): [True: 0, False: 0]
|
3161 | 0 | if (state.IsInvalid()) { Branch (3161:13): [True: 0, False: 0]
|
3162 | 0 | MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received"); |
3163 | 0 | return; |
3164 | 0 | } |
3165 | 0 | } |
3166 | 0 | assert(pindexLast); |
3167 | | |
3168 | | // Consider fetching more headers if we are not using our headers-sync mechanism. |
3169 | 0 | if (nCount == MAX_HEADERS_RESULTS && !have_headers_sync) { Branch (3169:9): [True: 0, False: 0]
Branch (3169:42): [True: 0, False: 0]
|
3170 | | // Headers message had its maximum size; the peer may have more headers. |
3171 | 0 | if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) { Branch (3171:13): [True: 0, False: 0]
|
3172 | 0 | LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", |
3173 | 0 | pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height); |
3174 | 0 | } |
3175 | 0 | } |
3176 | |
|
3177 | 0 | UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast, received_new_header, nCount == MAX_HEADERS_RESULTS); |
3178 | | |
3179 | | // Consider immediately downloading blocks. |
3180 | 0 | HeadersDirectFetchBlocks(pfrom, peer, *pindexLast); |
3181 | |
|
3182 | 0 | return; |
3183 | 0 | } |
3184 | | |
3185 | | void PeerManagerImpl::ProcessInvalidTx(NodeId nodeid, const CTransactionRef& ptx, const TxValidationState& state, |
3186 | | bool maybe_add_extra_compact_tx) |
3187 | 0 | { |
3188 | 0 | AssertLockNotHeld(m_peer_mutex); |
3189 | 0 | AssertLockHeld(g_msgproc_mutex); |
3190 | 0 | AssertLockHeld(cs_main); |
3191 | |
|
3192 | 0 | LogDebug(BCLog::MEMPOOLREJ, "%s (wtxid=%s) from peer=%d was not accepted: %s\n", |
3193 | 0 | ptx->GetHash().ToString(), |
3194 | 0 | ptx->GetWitnessHash().ToString(), |
3195 | 0 | nodeid, |
3196 | 0 | state.ToString()); |
3197 | |
|
3198 | 0 | if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) { Branch (3198:9): [True: 0, False: 0]
|
3199 | 0 | return; |
3200 | 0 | } else if (state.GetResult() != TxValidationResult::TX_WITNESS_STRIPPED) { Branch (3200:16): [True: 0, False: 0]
|
3201 | | // We can add the wtxid of this transaction to our reject filter. |
3202 | | // Do not add txids of witness transactions or witness-stripped |
3203 | | // transactions to the filter, as they can have been malleated; |
3204 | | // adding such txids to the reject filter would potentially |
3205 | | // interfere with relay of valid transactions from peers that |
3206 | | // do not support wtxid-based relay. See |
3207 | | // https://github.com/bitcoin/bitcoin/issues/8279 for details. |
3208 | | // We can remove this restriction (and always add wtxids to |
3209 | | // the filter even for witness stripped transactions) once |
3210 | | // wtxid-based relay is broadly deployed. |
3211 | | // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034 |
3212 | | // for concerns around weakening security of unupgraded nodes |
3213 | | // if we start doing this too early. |
3214 | 0 | if (state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) { Branch (3214:13): [True: 0, False: 0]
|
3215 | | // If the result is TX_RECONSIDERABLE, add it to m_recent_rejects_reconsiderable |
3216 | | // because we should not download or submit this transaction by itself again, but may |
3217 | | // submit it as part of a package later. |
3218 | 0 | RecentRejectsReconsiderableFilter().insert(ptx->GetWitnessHash().ToUint256()); |
3219 | 0 | } else { |
3220 | 0 | RecentRejectsFilter().insert(ptx->GetWitnessHash().ToUint256()); |
3221 | 0 | } |
3222 | 0 | m_txrequest.ForgetTxHash(ptx->GetWitnessHash()); |
3223 | | // If the transaction failed for TX_INPUTS_NOT_STANDARD, |
3224 | | // then we know that the witness was irrelevant to the policy |
3225 | | // failure, since this check depends only on the txid |
3226 | | // (the scriptPubKey being spent is covered by the txid). |
3227 | | // Add the txid to the reject filter to prevent repeated |
3228 | | // processing of this transaction in the event that child |
3229 | | // transactions are later received (resulting in |
3230 | | // parent-fetching by txid via the orphan-handling logic). |
3231 | | // We only add the txid if it differs from the wtxid, to avoid wasting entries in the |
3232 | | // rolling bloom filter. |
3233 | 0 | if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && ptx->HasWitness()) { Branch (3233:13): [True: 0, False: 0]
Branch (3233:80): [True: 0, False: 0]
|
3234 | 0 | RecentRejectsFilter().insert(ptx->GetHash().ToUint256()); |
3235 | 0 | m_txrequest.ForgetTxHash(ptx->GetHash()); |
3236 | 0 | } |
3237 | 0 | if (maybe_add_extra_compact_tx && RecursiveDynamicUsage(*ptx) < 100000) { Branch (3237:13): [True: 0, False: 0]
Branch (3237:43): [True: 0, False: 0]
|
3238 | 0 | AddToCompactExtraTransactions(ptx); |
3239 | 0 | } |
3240 | 0 | } |
3241 | | |
3242 | 0 | MaybePunishNodeForTx(nodeid, state); |
3243 | | |
3244 | | // If the tx failed in ProcessOrphanTx, it should be removed from the orphanage unless the |
3245 | | // tx was still missing inputs. If the tx was not in the orphanage, EraseTx does nothing and returns 0. |
3246 | 0 | if (Assume(state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) && m_orphanage.EraseTx(ptx->GetWitnessHash()) > 0) { Branch (3246:9): [True: 0, False: 0]
Branch (3246:79): [True: 0, False: 0]
|
3247 | 0 | LogDebug(BCLog::TXPACKAGES, " removed orphan tx %s (wtxid=%s)\n", ptx->GetHash().ToString(), ptx->GetWitnessHash().ToString()); |
3248 | 0 | } |
3249 | 0 | } |
3250 | | |
3251 | | void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions) |
3252 | 0 | { |
3253 | 0 | AssertLockNotHeld(m_peer_mutex); |
3254 | 0 | AssertLockHeld(g_msgproc_mutex); |
3255 | 0 | AssertLockHeld(cs_main); |
3256 | | |
3257 | | // As this version of the transaction was acceptable, we can forget about any requests for it. |
3258 | | // No-op if the tx is not in txrequest. |
3259 | 0 | m_txrequest.ForgetTxHash(tx->GetHash()); |
3260 | 0 | m_txrequest.ForgetTxHash(tx->GetWitnessHash()); |
3261 | |
|
3262 | 0 | m_orphanage.AddChildrenToWorkSet(*tx); |
3263 | | // If it came from the orphanage, remove it. No-op if the tx is not in txorphanage. |
3264 | 0 | m_orphanage.EraseTx(tx->GetWitnessHash()); |
3265 | |
|
3266 | 0 | LogDebug(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (wtxid=%s) (poolsz %u txn, %u kB)\n", |
3267 | 0 | nodeid, |
3268 | 0 | tx->GetHash().ToString(), |
3269 | 0 | tx->GetWitnessHash().ToString(), |
3270 | 0 | m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000); |
3271 | |
|
3272 | 0 | RelayTransaction(tx->GetHash(), tx->GetWitnessHash()); |
3273 | |
|
3274 | 0 | for (const CTransactionRef& removedTx : replaced_transactions) { Branch (3274:43): [True: 0, False: 0]
|
3275 | 0 | AddToCompactExtraTransactions(removedTx); |
3276 | 0 | } |
3277 | 0 | } |
3278 | | |
3279 | | void PeerManagerImpl::ProcessPackageResult(const PackageToValidate& package_to_validate, const PackageMempoolAcceptResult& package_result) |
3280 | 0 | { |
3281 | 0 | AssertLockNotHeld(m_peer_mutex); |
3282 | 0 | AssertLockHeld(g_msgproc_mutex); |
3283 | 0 | AssertLockHeld(cs_main); |
3284 | |
|
3285 | 0 | const auto& package = package_to_validate.m_txns; |
3286 | 0 | const auto& senders = package_to_validate.m_senders; |
3287 | |
|
3288 | 0 | if (package_result.m_state.IsInvalid()) { Branch (3288:9): [True: 0, False: 0]
|
3289 | 0 | RecentRejectsReconsiderableFilter().insert(GetPackageHash(package)); |
3290 | 0 | } |
3291 | | // We currently only expect to process 1-parent-1-child packages. Remove if this changes. |
3292 | 0 | if (!Assume(package.size() == 2)) return; Branch (3292:9): [True: 0, False: 0]
|
3293 | | |
3294 | | // Iterate backwards to erase in-package descendants from the orphanage before they become |
3295 | | // relevant in AddChildrenToWorkSet. |
3296 | 0 | auto package_iter = package.rbegin(); |
3297 | 0 | auto senders_iter = senders.rbegin(); |
3298 | 0 | while (package_iter != package.rend()) { Branch (3298:12): [True: 0, False: 0]
|
3299 | 0 | const auto& tx = *package_iter; |
3300 | 0 | const NodeId nodeid = *senders_iter; |
3301 | 0 | const auto it_result{package_result.m_tx_results.find(tx->GetWitnessHash())}; |
3302 | | |
3303 | | // It is not guaranteed that a result exists for every transaction. |
3304 | 0 | if (it_result != package_result.m_tx_results.end()) { Branch (3304:13): [True: 0, False: 0]
|
3305 | 0 | const auto& tx_result = it_result->second; |
3306 | 0 | switch (tx_result.m_result_type) { Branch (3306:21): [True: 0, False: 0]
|
3307 | 0 | case MempoolAcceptResult::ResultType::VALID: Branch (3307:17): [True: 0, False: 0]
|
3308 | 0 | { |
3309 | 0 | ProcessValidTx(nodeid, tx, tx_result.m_replaced_transactions); |
3310 | 0 | break; |
3311 | 0 | } |
3312 | 0 | case MempoolAcceptResult::ResultType::INVALID: Branch (3312:17): [True: 0, False: 0]
|
3313 | 0 | case MempoolAcceptResult::ResultType::DIFFERENT_WITNESS: Branch (3313:17): [True: 0, False: 0]
|
3314 | 0 | { |
3315 | | // Don't add to vExtraTxnForCompact, as these transactions should have already been |
3316 | | // added there when added to the orphanage or rejected for TX_RECONSIDERABLE. |
3317 | | // This should be updated if package submission is ever used for transactions |
3318 | | // that haven't already been validated before. |
3319 | 0 | ProcessInvalidTx(nodeid, tx, tx_result.m_state, /*maybe_add_extra_compact_tx=*/false); |
3320 | 0 | break; |
3321 | 0 | } |
3322 | 0 | case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY: Branch (3322:17): [True: 0, False: 0]
|
3323 | 0 | { |
3324 | | // AlreadyHaveTx() should be catching transactions that are already in mempool. |
3325 | 0 | Assume(false); |
3326 | 0 | break; |
3327 | 0 | } |
3328 | 0 | } |
3329 | 0 | } |
3330 | 0 | package_iter++; |
3331 | 0 | senders_iter++; |
3332 | 0 | } |
3333 | 0 | } |
3334 | | |
3335 | | std::optional<PeerManagerImpl::PackageToValidate> PeerManagerImpl::Find1P1CPackage(const CTransactionRef& ptx, NodeId nodeid) |
3336 | 0 | { |
3337 | 0 | AssertLockNotHeld(m_peer_mutex); |
3338 | 0 | AssertLockHeld(g_msgproc_mutex); |
3339 | 0 | AssertLockHeld(cs_main); |
3340 | |
|
3341 | 0 | const auto& parent_wtxid{ptx->GetWitnessHash()}; |
3342 | |
|
3343 | 0 | Assume(RecentRejectsReconsiderableFilter().contains(parent_wtxid.ToUint256())); |
3344 | | |
3345 | | // Prefer children from this peer. This helps prevent censorship attempts in which an attacker |
3346 | | // sends lots of fake children for the parent, and we (unluckily) keep selecting the fake |
3347 | | // children instead of the real one provided by the honest peer. |
3348 | 0 | const auto cpfp_candidates_same_peer{m_orphanage.GetChildrenFromSamePeer(ptx, nodeid)}; |
3349 | | |
3350 | | // These children should be sorted from newest to oldest. In the (probably uncommon) case |
3351 | | // of children that replace each other, this helps us accept the highest feerate (probably the |
3352 | | // most recent) one efficiently. |
3353 | 0 | for (const auto& child : cpfp_candidates_same_peer) { Branch (3353:28): [True: 0, False: 0]
|
3354 | 0 | Package maybe_cpfp_package{ptx, child}; |
3355 | 0 | if (!RecentRejectsReconsiderableFilter().contains(GetPackageHash(maybe_cpfp_package))) { Branch (3355:13): [True: 0, False: 0]
|
3356 | 0 | return PeerManagerImpl::PackageToValidate{ptx, child, nodeid, nodeid}; |
3357 | 0 | } |
3358 | 0 | } |
3359 | | |
3360 | | // If no suitable candidate from the same peer is found, also try children that were provided by |
3361 | | // a different peer. This is useful because sometimes multiple peers announce both transactions |
3362 | | // to us, and we happen to download them from different peers (we wouldn't have known that these |
3363 | | // 2 transactions are related). We still want to find 1p1c packages then. |
3364 | | // |
3365 | | // If we start tracking all announcers of orphans, we can restrict this logic to parent + child |
3366 | | // pairs in which both were provided by the same peer, i.e. delete this step. |
3367 | 0 | const auto cpfp_candidates_different_peer{m_orphanage.GetChildrenFromDifferentPeer(ptx, nodeid)}; |
3368 | | |
3369 | | // Find the first 1p1c that hasn't already been rejected. We randomize the order to not |
3370 | | // create a bias that attackers can use to delay package acceptance. |
3371 | | // |
3372 | | // Create a random permutation of the indices. |
3373 | 0 | std::vector<size_t> tx_indices(cpfp_candidates_different_peer.size()); |
3374 | 0 | std::iota(tx_indices.begin(), tx_indices.end(), 0); |
3375 | 0 | Shuffle(tx_indices.begin(), tx_indices.end(), m_rng); |
3376 | |
|
3377 | 0 | for (const auto index : tx_indices) { Branch (3377:27): [True: 0, False: 0]
|
3378 | | // If we already tried a package and failed for any reason, the combined hash was |
3379 | | // cached in RecentRejectsReconsiderableFilter(). |
3380 | 0 | const auto [child_tx, child_sender] = cpfp_candidates_different_peer.at(index); |
3381 | 0 | Package maybe_cpfp_package{ptx, child_tx}; |
3382 | 0 | if (!RecentRejectsReconsiderableFilter().contains(GetPackageHash(maybe_cpfp_package))) { Branch (3382:13): [True: 0, False: 0]
|
3383 | 0 | return PeerManagerImpl::PackageToValidate{ptx, child_tx, nodeid, child_sender}; |
3384 | 0 | } |
3385 | 0 | } |
3386 | 0 | return std::nullopt; |
3387 | 0 | } |
3388 | | |
3389 | | bool PeerManagerImpl::ProcessOrphanTx(Peer& peer) |
3390 | 5.64k | { |
3391 | 5.64k | AssertLockHeld(g_msgproc_mutex); |
3392 | 5.64k | LOCK(cs_main); |
3393 | | |
3394 | 5.64k | CTransactionRef porphanTx = nullptr; |
3395 | | |
3396 | 5.64k | while (CTransactionRef porphanTx = m_orphanage.GetTxToReconsider(peer.m_id)) { Branch (3396:28): [True: 0, False: 5.64k]
|
3397 | 0 | const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx); |
3398 | 0 | const TxValidationState& state = result.m_state; |
3399 | 0 | const Txid& orphanHash = porphanTx->GetHash(); |
3400 | 0 | const Wtxid& orphan_wtxid = porphanTx->GetWitnessHash(); |
3401 | |
|
3402 | 0 | if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) { Branch (3402:13): [True: 0, False: 0]
|
3403 | 0 | LogPrint(BCLog::TXPACKAGES, " accepted orphan tx %s (wtxid=%s)\n", orphanHash.ToString(), orphan_wtxid.ToString()); |
3404 | 0 | ProcessValidTx(peer.m_id, porphanTx, result.m_replaced_transactions); |
3405 | 0 | return true; |
3406 | 0 | } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) { Branch (3406:20): [True: 0, False: 0]
|
3407 | 0 | LogPrint(BCLog::TXPACKAGES, " invalid orphan tx %s (wtxid=%s) from peer=%d. %s\n", |
3408 | 0 | orphanHash.ToString(), |
3409 | 0 | orphan_wtxid.ToString(), |
3410 | 0 | peer.m_id, |
3411 | 0 | state.ToString()); |
3412 | |
|
3413 | 0 | if (Assume(state.IsInvalid() && |
3414 | 0 | state.GetResult() != TxValidationResult::TX_UNKNOWN && |
3415 | 0 | state.GetResult() != TxValidationResult::TX_NO_MEMPOOL && |
3416 | 0 | state.GetResult() != TxValidationResult::TX_RESULT_UNSET)) { |
3417 | 0 | ProcessInvalidTx(peer.m_id, porphanTx, state, /*maybe_add_extra_compact_tx=*/false); |
3418 | 0 | } |
3419 | 0 | return true; |
3420 | 0 | } |
3421 | 0 | } |
3422 | | |
3423 | 5.64k | return false; |
3424 | 5.64k | } |
3425 | | |
3426 | | bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& node, Peer& peer, |
3427 | | BlockFilterType filter_type, uint32_t start_height, |
3428 | | const uint256& stop_hash, uint32_t max_height_diff, |
3429 | | const CBlockIndex*& stop_index, |
3430 | | BlockFilterIndex*& filter_index) |
3431 | 0 | { |
3432 | 0 | const bool supported_filter_type = |
3433 | 0 | (filter_type == BlockFilterType::BASIC && Branch (3433:10): [True: 0, False: 0]
|
3434 | 0 | (peer.m_our_services & NODE_COMPACT_FILTERS)); Branch (3434:10): [True: 0, False: 0]
|
3435 | 0 | if (!supported_filter_type) { Branch (3435:9): [True: 0, False: 0]
|
3436 | 0 | LogPrint(BCLog::NET, "peer %d requested unsupported block filter type: %d\n", |
3437 | 0 | node.GetId(), static_cast<uint8_t>(filter_type)); |
3438 | 0 | node.fDisconnect = true; |
3439 | 0 | return false; |
3440 | 0 | } |
3441 | | |
3442 | 0 | { |
3443 | 0 | LOCK(cs_main); |
3444 | 0 | stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash); |
3445 | | |
3446 | | // Check that the stop block exists and the peer would be allowed to fetch it. |
3447 | 0 | if (!stop_index || !BlockRequestAllowed(stop_index)) { Branch (3447:13): [True: 0, False: 0]
Branch (3447:28): [True: 0, False: 0]
|
3448 | 0 | LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n", |
3449 | 0 | node.GetId(), stop_hash.ToString()); |
3450 | 0 | node.fDisconnect = true; |
3451 | 0 | return false; |
3452 | 0 | } |
3453 | 0 | } |
3454 | | |
3455 | 0 | uint32_t stop_height = stop_index->nHeight; |
3456 | 0 | if (start_height > stop_height) { Branch (3456:9): [True: 0, False: 0]
|
3457 | 0 | LogPrint(BCLog::NET, "peer %d sent invalid getcfilters/getcfheaders with " |
3458 | 0 | "start height %d and stop height %d\n", |
3459 | 0 | node.GetId(), start_height, stop_height); |
3460 | 0 | node.fDisconnect = true; |
3461 | 0 | return false; |
3462 | 0 | } |
3463 | 0 | if (stop_height - start_height >= max_height_diff) { Branch (3463:9): [True: 0, False: 0]
|
3464 | 0 | LogPrint(BCLog::NET, "peer %d requested too many cfilters/cfheaders: %d / %d\n", |
3465 | 0 | node.GetId(), stop_height - start_height + 1, max_height_diff); |
3466 | 0 | node.fDisconnect = true; |
3467 | 0 | return false; |
3468 | 0 | } |
3469 | | |
3470 | 0 | filter_index = GetBlockFilterIndex(filter_type); |
3471 | 0 | if (!filter_index) { Branch (3471:9): [True: 0, False: 0]
|
3472 | 0 | LogPrint(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type)); |
3473 | 0 | return false; |
3474 | 0 | } |
3475 | | |
3476 | 0 | return true; |
3477 | 0 | } |
3478 | | |
3479 | | void PeerManagerImpl::ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv) |
3480 | 0 | { |
3481 | 0 | uint8_t filter_type_ser; |
3482 | 0 | uint32_t start_height; |
3483 | 0 | uint256 stop_hash; |
3484 | |
|
3485 | 0 | vRecv >> filter_type_ser >> start_height >> stop_hash; |
3486 | |
|
3487 | 0 | const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); |
3488 | |
|
3489 | 0 | const CBlockIndex* stop_index; |
3490 | 0 | BlockFilterIndex* filter_index; |
3491 | 0 | if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash, Branch (3491:9): [True: 0, False: 0]
|
3492 | 0 | MAX_GETCFILTERS_SIZE, stop_index, filter_index)) { |
3493 | 0 | return; |
3494 | 0 | } |
3495 | | |
3496 | 0 | std::vector<BlockFilter> filters; |
3497 | 0 | if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) { Branch (3497:9): [True: 0, False: 0]
|
3498 | 0 | LogPrint(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n", |
3499 | 0 | BlockFilterTypeName(filter_type), start_height, stop_hash.ToString()); |
3500 | 0 | return; |
3501 | 0 | } |
3502 | | |
3503 | 0 | for (const auto& filter : filters) { Branch (3503:29): [True: 0, False: 0]
|
3504 | 0 | MakeAndPushMessage(node, NetMsgType::CFILTER, filter); |
3505 | 0 | } |
3506 | 0 | } |
3507 | | |
3508 | | void PeerManagerImpl::ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv) |
3509 | 0 | { |
3510 | 0 | uint8_t filter_type_ser; |
3511 | 0 | uint32_t start_height; |
3512 | 0 | uint256 stop_hash; |
3513 | |
|
3514 | 0 | vRecv >> filter_type_ser >> start_height >> stop_hash; |
3515 | |
|
3516 | 0 | const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); |
3517 | |
|
3518 | 0 | const CBlockIndex* stop_index; |
3519 | 0 | BlockFilterIndex* filter_index; |
3520 | 0 | if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash, Branch (3520:9): [True: 0, False: 0]
|
3521 | 0 | MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) { |
3522 | 0 | return; |
3523 | 0 | } |
3524 | | |
3525 | 0 | uint256 prev_header; |
3526 | 0 | if (start_height > 0) { Branch (3526:9): [True: 0, False: 0]
|
3527 | 0 | const CBlockIndex* const prev_block = |
3528 | 0 | stop_index->GetAncestor(static_cast<int>(start_height - 1)); |
3529 | 0 | if (!filter_index->LookupFilterHeader(prev_block, prev_header)) { Branch (3529:13): [True: 0, False: 0]
|
3530 | 0 | LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n", |
3531 | 0 | BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString()); |
3532 | 0 | return; |
3533 | 0 | } |
3534 | 0 | } |
3535 | | |
3536 | 0 | std::vector<uint256> filter_hashes; |
3537 | 0 | if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) { Branch (3537:9): [True: 0, False: 0]
|
3538 | 0 | LogPrint(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n", |
3539 | 0 | BlockFilterTypeName(filter_type), start_height, stop_hash.ToString()); |
3540 | 0 | return; |
3541 | 0 | } |
3542 | | |
3543 | 0 | MakeAndPushMessage(node, NetMsgType::CFHEADERS, |
3544 | 0 | filter_type_ser, |
3545 | 0 | stop_index->GetBlockHash(), |
3546 | 0 | prev_header, |
3547 | 0 | filter_hashes); |
3548 | 0 | } |
3549 | | |
3550 | | void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv) |
3551 | 0 | { |
3552 | 0 | uint8_t filter_type_ser; |
3553 | 0 | uint256 stop_hash; |
3554 | |
|
3555 | 0 | vRecv >> filter_type_ser >> stop_hash; |
3556 | |
|
3557 | 0 | const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); |
3558 | |
|
3559 | 0 | const CBlockIndex* stop_index; |
3560 | 0 | BlockFilterIndex* filter_index; |
3561 | 0 | if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash, Branch (3561:9): [True: 0, False: 0]
|
3562 | 0 | /*max_height_diff=*/std::numeric_limits<uint32_t>::max(), |
3563 | 0 | stop_index, filter_index)) { |
3564 | 0 | return; |
3565 | 0 | } |
3566 | | |
3567 | 0 | std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL); |
3568 | | |
3569 | | // Populate headers. |
3570 | 0 | const CBlockIndex* block_index = stop_index; |
3571 | 0 | for (int i = headers.size() - 1; i >= 0; i--) { Branch (3571:38): [True: 0, False: 0]
|
3572 | 0 | int height = (i + 1) * CFCHECKPT_INTERVAL; |
3573 | 0 | block_index = block_index->GetAncestor(height); |
3574 | |
|
3575 | 0 | if (!filter_index->LookupFilterHeader(block_index, headers[i])) { Branch (3575:13): [True: 0, False: 0]
|
3576 | 0 | LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n", |
3577 | 0 | BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString()); |
3578 | 0 | return; |
3579 | 0 | } |
3580 | 0 | } |
3581 | | |
3582 | 0 | MakeAndPushMessage(node, NetMsgType::CFCHECKPT, |
3583 | 0 | filter_type_ser, |
3584 | 0 | stop_index->GetBlockHash(), |
3585 | 0 | headers); |
3586 | 0 | } |
3587 | | |
3588 | | void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked) |
3589 | 0 | { |
3590 | 0 | bool new_block{false}; |
3591 | 0 | m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block); |
3592 | 0 | if (new_block) { Branch (3592:9): [True: 0, False: 0]
|
3593 | 0 | node.m_last_block_time = GetTime<std::chrono::seconds>(); |
3594 | | // In case this block came from a different peer than we requested |
3595 | | // from, we can erase the block request now anyway (as we just stored |
3596 | | // this block to disk). |
3597 | 0 | LOCK(cs_main); |
3598 | 0 | RemoveBlockRequest(block->GetHash(), std::nullopt); |
3599 | 0 | } else { |
3600 | 0 | LOCK(cs_main); |
3601 | 0 | mapBlockSource.erase(block->GetHash()); |
3602 | 0 | } |
3603 | 0 | } |
3604 | | |
3605 | | void PeerManagerImpl::ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions) |
3606 | 0 | { |
3607 | 0 | std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); |
3608 | 0 | bool fBlockRead{false}; |
3609 | 0 | { |
3610 | 0 | LOCK(cs_main); |
3611 | |
|
3612 | 0 | auto range_flight = mapBlocksInFlight.equal_range(block_transactions.blockhash); |
3613 | 0 | size_t already_in_flight = std::distance(range_flight.first, range_flight.second); |
3614 | 0 | bool requested_block_from_this_peer{false}; |
3615 | | |
3616 | | // Multimap ensures ordering of outstanding requests. It's either empty or first in line. |
3617 | 0 | bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId()); Branch (3617:32): [True: 0, False: 0]
Branch (3617:58): [True: 0, False: 0]
|
3618 | |
|
3619 | 0 | while (range_flight.first != range_flight.second) { Branch (3619:16): [True: 0, False: 0]
|
3620 | 0 | auto [node_id, block_it] = range_flight.first->second; |
3621 | 0 | if (node_id == pfrom.GetId() && block_it->partialBlock) { Branch (3621:17): [True: 0, False: 0]
Branch (3621:45): [True: 0, False: 0]
|
3622 | 0 | requested_block_from_this_peer = true; |
3623 | 0 | break; |
3624 | 0 | } |
3625 | 0 | range_flight.first++; |
3626 | 0 | } |
3627 | |
|
3628 | 0 | if (!requested_block_from_this_peer) { Branch (3628:13): [True: 0, False: 0]
|
3629 | 0 | LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId()); |
3630 | 0 | return; |
3631 | 0 | } |
3632 | | |
3633 | 0 | PartiallyDownloadedBlock& partialBlock = *range_flight.first->second.second->partialBlock; |
3634 | 0 | ReadStatus status = partialBlock.FillBlock(*pblock, block_transactions.txn); |
3635 | 0 | if (status == READ_STATUS_INVALID) { Branch (3635:13): [True: 0, False: 0]
|
3636 | 0 | RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect |
3637 | 0 | Misbehaving(peer, "invalid compact block/non-matching block transactions"); |
3638 | 0 | return; |
3639 | 0 | } else if (status == READ_STATUS_FAILED) { Branch (3639:20): [True: 0, False: 0]
|
3640 | 0 | if (first_in_flight) { Branch (3640:17): [True: 0, False: 0]
|
3641 | | // Might have collided, fall back to getdata now :( |
3642 | 0 | std::vector<CInv> invs; |
3643 | 0 | invs.emplace_back(MSG_BLOCK | GetFetchFlags(peer), block_transactions.blockhash); |
3644 | 0 | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, invs); |
3645 | 0 | } else { |
3646 | 0 | RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); |
3647 | 0 | LogPrint(BCLog::NET, "Peer %d sent us a compact block but it failed to reconstruct, waiting on first download to complete\n", pfrom.GetId()); |
3648 | 0 | return; |
3649 | 0 | } |
3650 | 0 | } else { |
3651 | | // Block is either okay, or possibly we received |
3652 | | // READ_STATUS_CHECKBLOCK_FAILED. |
3653 | | // Note that CheckBlock can only fail for one of a few reasons: |
3654 | | // 1. bad-proof-of-work (impossible here, because we've already |
3655 | | // accepted the header) |
3656 | | // 2. merkleroot doesn't match the transactions given (already |
3657 | | // caught in FillBlock with READ_STATUS_FAILED, so |
3658 | | // impossible here) |
3659 | | // 3. the block is otherwise invalid (eg invalid coinbase, |
3660 | | // block is too big, too many legacy sigops, etc). |
3661 | | // So if CheckBlock failed, #3 is the only possibility. |
3662 | | // Under BIP 152, we don't discourage the peer unless proof of work is |
3663 | | // invalid (we don't require all the stateless checks to have |
3664 | | // been run). This is handled below, so just treat this as |
3665 | | // though the block was successfully read, and rely on the |
3666 | | // handling in ProcessNewBlock to ensure the block index is |
3667 | | // updated, etc. |
3668 | 0 | RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // it is now an empty pointer |
3669 | 0 | fBlockRead = true; |
3670 | | // mapBlockSource is used for potentially punishing peers and |
3671 | | // updating which peers send us compact blocks, so the race |
3672 | | // between here and cs_main in ProcessNewBlock is fine. |
3673 | | // BIP 152 permits peers to relay compact blocks after validating |
3674 | | // the header only; we should not punish peers if the block turns |
3675 | | // out to be invalid. |
3676 | 0 | mapBlockSource.emplace(block_transactions.blockhash, std::make_pair(pfrom.GetId(), false)); |
3677 | 0 | } |
3678 | 0 | } // Don't hold cs_main when we call into ProcessNewBlock |
3679 | 0 | if (fBlockRead) { Branch (3679:9): [True: 0, False: 0]
|
3680 | | // Since we requested this block (it was in mapBlocksInFlight), force it to be processed, |
3681 | | // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc) |
3682 | | // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent |
3683 | | // disk-space attacks), but this should be safe due to the |
3684 | | // protections in the compact block handler -- see related comment |
3685 | | // in compact block optimistic reconstruction handling. |
3686 | 0 | ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true); |
3687 | 0 | } |
3688 | 0 | return; |
3689 | 0 | } |
3690 | | |
3691 | | void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, |
3692 | | const std::chrono::microseconds time_received, |
3693 | | const std::atomic<bool>& interruptMsgProc) |
3694 | 5.64k | { |
3695 | 5.64k | AssertLockHeld(g_msgproc_mutex); |
3696 | | |
3697 | 5.64k | LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId()); |
3698 | | |
3699 | 5.64k | PeerRef peer = GetPeerRef(pfrom.GetId()); |
3700 | 5.64k | if (peer == nullptr) return; Branch (3700:9): [True: 0, False: 5.64k]
|
3701 | | |
3702 | 5.64k | if (msg_type == NetMsgType::VERSION) { Branch (3702:9): [True: 2.58k, False: 3.06k]
|
3703 | 2.58k | if (pfrom.nVersion != 0) { Branch (3703:13): [True: 349, False: 2.23k]
|
3704 | 349 | LogPrint(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId()); |
3705 | 349 | return; |
3706 | 349 | } |
3707 | | |
3708 | 2.23k | int64_t nTime; |
3709 | 2.23k | CService addrMe; |
3710 | 2.23k | uint64_t nNonce = 1; |
3711 | 2.23k | ServiceFlags nServices; |
3712 | 2.23k | int nVersion; |
3713 | 2.23k | std::string cleanSubVer; |
3714 | 2.23k | int starting_height = -1; |
3715 | 2.23k | bool fRelay = true; |
3716 | | |
3717 | 2.23k | vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime; |
3718 | 2.23k | if (nTime < 0) { Branch (3718:13): [True: 219, False: 2.01k]
|
3719 | 219 | nTime = 0; |
3720 | 219 | } |
3721 | 2.23k | vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer |
3722 | 2.23k | vRecv >> CNetAddr::V1(addrMe); |
3723 | 2.23k | if (!pfrom.IsInboundConn()) Branch (3723:13): [True: 1.03k, False: 1.19k]
|
3724 | 1.03k | { |
3725 | | // Overwrites potentially existing services. In contrast to this, |
3726 | | // unvalidated services received via gossip relay in ADDR/ADDRV2 |
3727 | | // messages are only ever added but cannot replace existing ones. |
3728 | 1.03k | m_addrman.SetServices(pfrom.addr, nServices); |
3729 | 1.03k | } |
3730 | 2.23k | if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices)) Branch (3730:13): [True: 382, False: 1.85k]
Branch (3730:47): [True: 14, False: 368]
|
3731 | 14 | { |
3732 | 14 | LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom.GetId(), nServices, GetDesirableServiceFlags(nServices)); |
3733 | 14 | pfrom.fDisconnect = true; |
3734 | 14 | return; |
3735 | 14 | } |
3736 | | |
3737 | 2.21k | if (nVersion < MIN_PEER_PROTO_VERSION) { Branch (3737:13): [True: 8, False: 2.21k]
|
3738 | | // disconnect from peers older than this proto version |
3739 | 8 | LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom.GetId(), nVersion); |
3740 | 8 | pfrom.fDisconnect = true; |
3741 | 8 | return; |
3742 | 8 | } |
3743 | | |
3744 | 2.21k | if (!vRecv.empty()) { Branch (3744:13): [True: 1.13k, False: 1.07k]
|
3745 | | // The version message includes information about the sending node which we don't use: |
3746 | | // - 8 bytes (service bits) |
3747 | | // - 16 bytes (ipv6 address) |
3748 | | // - 2 bytes (port) |
3749 | 1.13k | vRecv.ignore(26); |
3750 | 1.13k | vRecv >> nNonce; |
3751 | 1.13k | } |
3752 | 2.21k | if (!vRecv.empty()) { Branch (3752:13): [True: 937, False: 1.27k]
|
3753 | 937 | std::string strSubVer; |
3754 | 937 | vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH); |
3755 | 937 | cleanSubVer = SanitizeString(strSubVer); |
3756 | 937 | } |
3757 | 2.21k | if (!vRecv.empty()) { Branch (3757:13): [True: 394, False: 1.81k]
|
3758 | 394 | vRecv >> starting_height; |
3759 | 394 | } |
3760 | 2.21k | if (!vRecv.empty()) Branch (3760:13): [True: 258, False: 1.95k]
|
3761 | 258 | vRecv >> fRelay; |
3762 | | // Disconnect if we connected to ourself |
3763 | 2.21k | if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce)) Branch (3763:13): [True: 144, False: 2.06k]
Branch (3763:38): [True: 10, False: 134]
|
3764 | 10 | { |
3765 | 10 | LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToStringAddrPort()); |
3766 | 10 | pfrom.fDisconnect = true; |
3767 | 10 | return; |
3768 | 10 | } |
3769 | | |
3770 | 2.20k | if (pfrom.IsInboundConn() && addrMe.IsRoutable()) Branch (3770:13): [True: 134, False: 2.06k]
Branch (3770:38): [True: 122, False: 12]
|
3771 | 122 | { |
3772 | 122 | SeenLocal(addrMe); |
3773 | 122 | } |
3774 | | |
3775 | | // Inbound peers send us their version message when they connect. |
3776 | | // We send our version message in response. |
3777 | 2.20k | if (pfrom.IsInboundConn()) { Branch (3777:13): [True: 134, False: 2.06k]
|
3778 | 134 | PushNodeVersion(pfrom, *peer); |
3779 | 134 | } |
3780 | | |
3781 | | // Change version |
3782 | 2.20k | const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION); |
3783 | 2.20k | pfrom.SetCommonVersion(greatest_common_version); |
3784 | 2.20k | pfrom.nVersion = nVersion; |
3785 | | |
3786 | 2.20k | if (greatest_common_version >= WTXID_RELAY_VERSION) { Branch (3786:13): [True: 385, False: 1.81k]
|
3787 | 385 | MakeAndPushMessage(pfrom, NetMsgType::WTXIDRELAY); |
3788 | 385 | } |
3789 | | |
3790 | | // Signal ADDRv2 support (BIP155). |
3791 | 2.20k | if (greatest_common_version >= 70016) { Branch (3791:13): [True: 385, False: 1.81k]
|
3792 | | // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some |
3793 | | // implementations reject messages they don't know. As a courtesy, don't send |
3794 | | // it to nodes with a version before 70016, as no software is known to support |
3795 | | // BIP155 that doesn't announce at least that protocol version number. |
3796 | 385 | MakeAndPushMessage(pfrom, NetMsgType::SENDADDRV2); |
3797 | 385 | } |
3798 | | |
3799 | 2.20k | pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices); |
3800 | 2.20k | peer->m_their_services = nServices; |
3801 | 2.20k | pfrom.SetAddrLocal(addrMe); |
3802 | 2.20k | { |
3803 | 2.20k | LOCK(pfrom.m_subver_mutex); |
3804 | 2.20k | pfrom.cleanSubVer = cleanSubVer; |
3805 | 2.20k | } |
3806 | 2.20k | peer->m_starting_height = starting_height; |
3807 | | |
3808 | | // Only initialize the Peer::TxRelay m_relay_txs data structure if: |
3809 | | // - this isn't an outbound block-relay-only connection, and |
3810 | | // - this isn't an outbound feeler connection, and |
3811 | | // - fRelay=true (the peer wishes to receive transaction announcements) |
3812 | | // or we're offering NODE_BLOOM to this peer. NODE_BLOOM means that |
3813 | | // the peer may turn on transaction relay later. |
3814 | 2.20k | if (!pfrom.IsBlockOnlyConn() && Branch (3814:13): [True: 397, False: 1.80k]
|
3815 | 2.20k | !pfrom.IsFeelerConn() && Branch (3815:13): [True: 361, False: 36]
|
3816 | 2.20k | (fRelay || (peer->m_our_services & NODE_BLOOM))) { Branch (3816:14): [True: 310, False: 51]
Branch (3816:24): [True: 21, False: 30]
|
3817 | 331 | auto* const tx_relay = peer->SetTxRelay(); |
3818 | 331 | { |
3819 | 331 | LOCK(tx_relay->m_bloom_filter_mutex); |
3820 | 331 | tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message |
3821 | 331 | } |
3822 | 331 | if (fRelay) pfrom.m_relays_txs = true; Branch (3822:17): [True: 310, False: 21]
|
3823 | 331 | } |
3824 | | |
3825 | 2.20k | if (greatest_common_version >= WTXID_RELAY_VERSION && m_txreconciliation) { Branch (3825:13): [True: 385, False: 1.81k]
Branch (3825:63): [True: 385, False: 0]
|
3826 | | // Per BIP-330, we announce txreconciliation support if: |
3827 | | // - protocol version per the peer's VERSION message supports WTXID_RELAY; |
3828 | | // - transaction relay is supported per the peer's VERSION message |
3829 | | // - this is not a block-relay-only connection and not a feeler |
3830 | | // - this is not an addr fetch connection; |
3831 | | // - we are not in -blocksonly mode. |
3832 | 385 | const auto* tx_relay = peer->GetTxRelay(); |
3833 | 385 | if (tx_relay && WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs) && Branch (3833:17): [True: 300, False: 85]
Branch (3833:17): [True: 264, False: 121]
|
3834 | 385 | !pfrom.IsAddrFetchConn() && !m_opts.ignore_incoming_txs) { Branch (3834:17): [True: 264, False: 17]
Branch (3834:45): [True: 264, False: 0]
|
3835 | 264 | const uint64_t recon_salt = m_txreconciliation->PreRegisterPeer(pfrom.GetId()); |
3836 | 264 | MakeAndPushMessage(pfrom, NetMsgType::SENDTXRCNCL, |
3837 | 264 | TXRECONCILIATION_VERSION, recon_salt); |
3838 | 264 | } |
3839 | 385 | } |
3840 | | |
3841 | 2.20k | MakeAndPushMessage(pfrom, NetMsgType::VERACK); |
3842 | | |
3843 | | // Potentially mark this peer as a preferred download peer. |
3844 | 2.20k | { |
3845 | 2.20k | LOCK(cs_main); |
3846 | 2.20k | CNodeState* state = State(pfrom.GetId()); |
3847 | 2.20k | state->fPreferredDownload = (!pfrom.IsInboundConn() || pfrom.HasPermission(NetPermissionFlags::NoBan)) && !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer); Branch (3847:42): [True: 2.06k, False: 134]
Branch (3847:68): [True: 15, False: 119]
Branch (3847:119): [True: 283, False: 19]
Branch (3847:147): [True: 242, False: 41]
|
3848 | 2.20k | m_num_preferred_download_peers += state->fPreferredDownload; |
3849 | 2.20k | } |
3850 | | |
3851 | | // Attempt to initialize address relay for outbound peers and use result |
3852 | | // to decide whether to send GETADDR, so that we don't send it to |
3853 | | // inbound or outbound block-relay-only peers. |
3854 | 2.20k | bool send_getaddr{false}; |
3855 | 2.20k | if (!pfrom.IsInboundConn()) { Branch (3855:13): [True: 287, False: 1.91k]
|
3856 | 287 | send_getaddr = SetupAddressRelay(pfrom, *peer); |
3857 | 287 | } |
3858 | 2.20k | if (send_getaddr) { Branch (3858:13): [True: 263, False: 1.93k]
|
3859 | | // Do a one-time address fetch to help populate/update our addrman. |
3860 | | // If we're starting up for the first time, our addrman may be pretty |
3861 | | // empty, so this mechanism is important to help us connect to the network. |
3862 | | // We skip this for block-relay-only peers. We want to avoid |
3863 | | // potentially leaking addr information and we do not want to |
3864 | | // indicate to the peer that we will participate in addr relay. |
3865 | 263 | MakeAndPushMessage(pfrom, NetMsgType::GETADDR); |
3866 | 263 | peer->m_getaddr_sent = true; |
3867 | | // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response |
3868 | | // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit). |
3869 | 263 | peer->m_addr_token_bucket += MAX_ADDR_TO_SEND; |
3870 | 263 | } |
3871 | | |
3872 | 2.20k | if (!pfrom.IsInboundConn()) { Branch (3872:13): [True: 287, False: 1.91k]
|
3873 | | // For non-inbound connections, we update the addrman to record |
3874 | | // connection success so that addrman will have an up-to-date |
3875 | | // notion of which peers are online and available. |
3876 | | // |
3877 | | // While we strive to not leak information about block-relay-only |
3878 | | // connections via the addrman, not moving an address to the tried |
3879 | | // table is also potentially detrimental because new-table entries |
3880 | | // are subject to eviction in the event of addrman collisions. We |
3881 | | // mitigate the information-leak by never calling |
3882 | | // AddrMan::Connected() on block-relay-only peers; see |
3883 | | // FinalizeNode(). |
3884 | | // |
3885 | | // This moves an address from New to Tried table in Addrman, |
3886 | | // resolves tried-table collisions, etc. |
3887 | 287 | m_addrman.Good(pfrom.addr); |
3888 | 287 | } |
3889 | | |
3890 | 2.20k | std::string remoteAddr; |
3891 | 2.20k | if (fLogIPs) Branch (3891:13): [True: 0, False: 2.20k]
|
3892 | 0 | remoteAddr = ", peeraddr=" + pfrom.addr.ToStringAddrPort(); |
3893 | | |
3894 | 2.20k | const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)}; |
3895 | 2.20k | LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s%s\n", |
3896 | 2.20k | cleanSubVer, pfrom.nVersion, |
3897 | 2.20k | peer->m_starting_height, addrMe.ToStringAddrPort(), fRelay, pfrom.GetId(), |
3898 | 2.20k | remoteAddr, (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : "")); |
3899 | | |
3900 | 2.20k | peer->m_time_offset = NodeSeconds{std::chrono::seconds{nTime}} - Now<NodeSeconds>(); |
3901 | 2.20k | if (!pfrom.IsInboundConn()) { Branch (3901:13): [True: 287, False: 1.91k]
|
3902 | | // Don't use timedata samples from inbound peers to make it |
3903 | | // harder for others to create false warnings about our clock being out of sync. |
3904 | 287 | m_outbound_time_offsets.Add(peer->m_time_offset); |
3905 | 287 | m_outbound_time_offsets.WarnIfOutOfSync(); |
3906 | 287 | } |
3907 | | |
3908 | | // If the peer is old enough to have the old alert system, send it the final alert. |
3909 | 2.20k | if (greatest_common_version <= 70012) { Branch (3909:13): [True: 35, False: 2.16k]
|
3910 | 35 | const auto finalAlert{ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50")}; |
3911 | 35 | MakeAndPushMessage(pfrom, "alert", Span{finalAlert}); |
3912 | 35 | } |
3913 | | |
3914 | | // Feeler connections exist only to verify if address is online. |
3915 | 2.20k | if (pfrom.IsFeelerConn()) { Branch (3915:13): [True: 36, False: 2.16k]
|
3916 | 36 | LogPrint(BCLog::NET, "feeler connection completed peer=%d; disconnecting\n", pfrom.GetId()); |
3917 | 36 | pfrom.fDisconnect = true; |
3918 | 36 | } |
3919 | 2.20k | return; |
3920 | 2.21k | } |
3921 | | |
3922 | 3.06k | if (pfrom.nVersion == 0) { Branch (3922:9): [True: 1.12k, False: 1.93k]
|
3923 | | // Must have a version message before anything else |
3924 | 1.12k | LogPrint(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); |
3925 | 1.12k | return; |
3926 | 1.12k | } |
3927 | | |
3928 | 1.93k | if (msg_type == NetMsgType::VERACK) { Branch (3928:9): [True: 163, False: 1.77k]
|
3929 | 163 | if (pfrom.fSuccessfullyConnected) { Branch (3929:13): [True: 0, False: 163]
|
3930 | 0 | LogPrint(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId()); |
3931 | 0 | return; |
3932 | 0 | } |
3933 | | |
3934 | | // Log successful connections unconditionally for outbound, but not for inbound as those |
3935 | | // can be triggered by an attacker at high rate. |
3936 | 163 | if (!pfrom.IsInboundConn() || LogAcceptCategory(BCLog::NET, BCLog::Level::Debug)) { Branch (3936:13): [True: 127, False: 36]
Branch (3936:39): [True: 0, False: 36]
|
3937 | 127 | const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)}; |
3938 | 127 | LogPrintf("New %s %s peer connected: version: %d, blocks=%d, peer=%d%s%s\n", |
3939 | 127 | pfrom.ConnectionTypeAsString(), |
3940 | 127 | TransportTypeAsString(pfrom.m_transport->GetInfo().transport_type), |
3941 | 127 | pfrom.nVersion.load(), peer->m_starting_height, |
3942 | 127 | pfrom.GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToStringAddrPort()) : ""), |
3943 | 127 | (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : "")); |
3944 | 127 | } |
3945 | | |
3946 | 163 | if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) { Branch (3946:13): [True: 157, False: 6]
|
3947 | | // Tell our peer we are willing to provide version 2 cmpctblocks. |
3948 | | // However, we do not request new block announcements using |
3949 | | // cmpctblock messages. |
3950 | | // We send this to non-NODE NETWORK peers as well, because |
3951 | | // they may wish to request compact blocks from us |
3952 | 157 | MakeAndPushMessage(pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION); |
3953 | 157 | } |
3954 | | |
3955 | 163 | if (m_txreconciliation) { Branch (3955:13): [True: 163, False: 0]
|
3956 | 163 | if (!peer->m_wtxid_relay || !m_txreconciliation->IsPeerRegistered(pfrom.GetId())) { Branch (3956:17): [True: 155, False: 8]
Branch (3956:41): [True: 7, False: 1]
|
3957 | | // We could have optimistically pre-registered/registered the peer. In that case, |
3958 | | // we should forget about the reconciliation state here if this wasn't followed |
3959 | | // by WTXIDRELAY (since WTXIDRELAY can't be announced later). |
3960 | 162 | m_txreconciliation->ForgetPeer(pfrom.GetId()); |
3961 | 162 | } |
3962 | 163 | } |
3963 | | |
3964 | 163 | if (auto tx_relay = peer->GetTxRelay()) { Branch (3964:18): [True: 134, False: 29]
|
3965 | | // `TxRelay::m_tx_inventory_to_send` must be empty before the |
3966 | | // version handshake is completed as |
3967 | | // `TxRelay::m_next_inv_send_time` is first initialised in |
3968 | | // `SendMessages` after the verack is received. Any transactions |
3969 | | // received during the version handshake would otherwise |
3970 | | // immediately be advertised without random delay, potentially |
3971 | | // leaking the time of arrival to a spy. |
3972 | 134 | Assume(WITH_LOCK( |
3973 | 134 | tx_relay->m_tx_inventory_mutex, |
3974 | 134 | return tx_relay->m_tx_inventory_to_send.empty() && |
3975 | 134 | tx_relay->m_next_inv_send_time == 0s)); |
3976 | 134 | } |
3977 | | |
3978 | 163 | pfrom.fSuccessfullyConnected = true; |
3979 | 163 | return; |
3980 | 163 | } |
3981 | | |
3982 | 1.77k | if (msg_type == NetMsgType::SENDHEADERS) { Branch (3982:9): [True: 79, False: 1.69k]
|
3983 | 79 | peer->m_prefers_headers = true; |
3984 | 79 | return; |
3985 | 79 | } |
3986 | | |
3987 | 1.69k | if (msg_type == NetMsgType::SENDCMPCT) { Branch (3987:9): [True: 304, False: 1.39k]
|
3988 | 304 | bool sendcmpct_hb{false}; |
3989 | 304 | uint64_t sendcmpct_version{0}; |
3990 | 304 | vRecv >> sendcmpct_hb >> sendcmpct_version; |
3991 | | |
3992 | | // Only support compact block relay with witnesses |
3993 | 304 | if (sendcmpct_version != CMPCTBLOCKS_VERSION) return; Branch (3993:13): [True: 123, False: 181]
|
3994 | | |
3995 | 181 | LOCK(cs_main); |
3996 | 181 | CNodeState* nodestate = State(pfrom.GetId()); |
3997 | 181 | nodestate->m_provides_cmpctblocks = true; |
3998 | 181 | nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb; |
3999 | | // save whether peer selects us as BIP152 high-bandwidth peer |
4000 | | // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth) |
4001 | 181 | pfrom.m_bip152_highbandwidth_from = sendcmpct_hb; |
4002 | 181 | return; |
4003 | 304 | } |
4004 | | |
4005 | | // BIP339 defines feature negotiation of wtxidrelay, which must happen between |
4006 | | // VERSION and VERACK to avoid relay problems from switching after a connection is up. |
4007 | 1.39k | if (msg_type == NetMsgType::WTXIDRELAY) { Branch (4007:9): [True: 168, False: 1.22k]
|
4008 | 168 | if (pfrom.fSuccessfullyConnected) { Branch (4008:13): [True: 0, False: 168]
|
4009 | | // Disconnect peers that send a wtxidrelay message after VERACK. |
4010 | 0 | LogPrint(BCLog::NET, "wtxidrelay received after verack from peer=%d; disconnecting\n", pfrom.GetId()); |
4011 | 0 | pfrom.fDisconnect = true; |
4012 | 0 | return; |
4013 | 0 | } |
4014 | 168 | if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) { Branch (4014:13): [True: 95, False: 73]
|
4015 | 95 | if (!peer->m_wtxid_relay) { Branch (4015:17): [True: 20, False: 75]
|
4016 | 20 | peer->m_wtxid_relay = true; |
4017 | 20 | m_wtxid_relay_peers++; |
4018 | 75 | } else { |
4019 | 75 | LogPrint(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId()); |
4020 | 75 | } |
4021 | 95 | } else { |
4022 | 73 | LogPrint(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId()); |
4023 | 73 | } |
4024 | 168 | return; |
4025 | 168 | } |
4026 | | |
4027 | | // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen |
4028 | | // between VERSION and VERACK. |
4029 | 1.22k | if (msg_type == NetMsgType::SENDADDRV2) { Branch (4029:9): [True: 137, False: 1.08k]
|
4030 | 137 | if (pfrom.fSuccessfullyConnected) { Branch (4030:13): [True: 0, False: 137]
|
4031 | | // Disconnect peers that send a SENDADDRV2 message after VERACK. |
4032 | 0 | LogPrint(BCLog::NET, "sendaddrv2 received after verack from peer=%d; disconnecting\n", pfrom.GetId()); |
4033 | 0 | pfrom.fDisconnect = true; |
4034 | 0 | return; |
4035 | 0 | } |
4036 | 137 | peer->m_wants_addrv2 = true; |
4037 | 137 | return; |
4038 | 137 | } |
4039 | | |
4040 | | // Received from a peer demonstrating readiness to announce transactions via reconciliations. |
4041 | | // This feature negotiation must happen between VERSION and VERACK to avoid relay problems |
4042 | | // from switching announcement protocols after the connection is up. |
4043 | 1.08k | if (msg_type == NetMsgType::SENDTXRCNCL) { Branch (4043:9): [True: 296, False: 790]
|
4044 | 296 | if (!m_txreconciliation) { Branch (4044:13): [True: 0, False: 296]
|
4045 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl from peer=%d ignored, as our node does not have txreconciliation enabled\n", pfrom.GetId()); |
4046 | 0 | return; |
4047 | 0 | } |
4048 | | |
4049 | 296 | if (pfrom.fSuccessfullyConnected) { Branch (4049:13): [True: 0, False: 296]
|
4050 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received after verack from peer=%d; disconnecting\n", pfrom.GetId()); |
4051 | 0 | pfrom.fDisconnect = true; |
4052 | 0 | return; |
4053 | 0 | } |
4054 | | |
4055 | | // Peer must not offer us reconciliations if we specified no tx relay support in VERSION. |
4056 | 296 | if (RejectIncomingTxs(pfrom)) { Branch (4056:13): [True: 3, False: 293]
|
4057 | 3 | LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received from peer=%d to which we indicated no tx relay; disconnecting\n", pfrom.GetId()); |
4058 | 3 | pfrom.fDisconnect = true; |
4059 | 3 | return; |
4060 | 3 | } |
4061 | | |
4062 | | // Peer must not offer us reconciliations if they specified no tx relay support in VERSION. |
4063 | | // This flag might also be false in other cases, but the RejectIncomingTxs check above |
4064 | | // eliminates them, so that this flag fully represents what we are looking for. |
4065 | 293 | const auto* tx_relay = peer->GetTxRelay(); |
4066 | 293 | if (!tx_relay || !WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs)) { Branch (4066:13): [True: 3, False: 290]
Branch (4066:13): [True: 9, False: 284]
Branch (4066:26): [True: 6, False: 284]
|
4067 | 9 | LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received from peer=%d which indicated no tx relay to us; disconnecting\n", pfrom.GetId()); |
4068 | 9 | pfrom.fDisconnect = true; |
4069 | 9 | return; |
4070 | 9 | } |
4071 | | |
4072 | 284 | uint32_t peer_txreconcl_version; |
4073 | 284 | uint64_t remote_salt; |
4074 | 284 | vRecv >> peer_txreconcl_version >> remote_salt; |
4075 | | |
4076 | 284 | const ReconciliationRegisterResult result = m_txreconciliation->RegisterPeer(pfrom.GetId(), pfrom.IsInboundConn(), |
4077 | 284 | peer_txreconcl_version, remote_salt); |
4078 | 284 | switch (result) { Branch (4078:17): [True: 121, False: 163]
|
4079 | 142 | case ReconciliationRegisterResult::NOT_FOUND: Branch (4079:9): [True: 142, False: 142]
|
4080 | 142 | LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "Ignore unexpected txreconciliation signal from peer=%d\n", pfrom.GetId()); |
4081 | 142 | break; |
4082 | 14 | case ReconciliationRegisterResult::SUCCESS: Branch (4082:9): [True: 14, False: 270]
|
4083 | 14 | break; |
4084 | 6 | case ReconciliationRegisterResult::ALREADY_REGISTERED: Branch (4084:9): [True: 6, False: 278]
|
4085 | 6 | LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "txreconciliation protocol violation from peer=%d (sendtxrcncl received from already registered peer); disconnecting\n", pfrom.GetId()); |
4086 | 6 | pfrom.fDisconnect = true; |
4087 | 6 | return; |
4088 | 1 | case ReconciliationRegisterResult::PROTOCOL_VIOLATION: Branch (4088:9): [True: 1, False: 283]
|
4089 | 1 | LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "txreconciliation protocol violation from peer=%d; disconnecting\n", pfrom.GetId()); |
4090 | 1 | pfrom.fDisconnect = true; |
4091 | 1 | return; |
4092 | 284 | } |
4093 | 156 | return; |
4094 | 284 | } |
4095 | | |
4096 | 790 | if (!pfrom.fSuccessfullyConnected) { Branch (4096:9): [True: 790, False: 0]
|
4097 | 790 | LogPrint(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); |
4098 | 790 | return; |
4099 | 790 | } |
4100 | | |
4101 | 0 | if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) { Branch (4101:9): [True: 0, False: 0]
Branch (4101:41): [True: 0, False: 0]
|
4102 | 0 | const auto ser_params{ |
4103 | 0 | msg_type == NetMsgType::ADDRV2 ? Branch (4103:13): [True: 0, False: 0]
|
4104 | | // Set V2 param so that the CNetAddr and CAddress |
4105 | | // unserialize methods know that an address in v2 format is coming. |
4106 | 0 | CAddress::V2_NETWORK : |
4107 | 0 | CAddress::V1_NETWORK, |
4108 | 0 | }; |
4109 | |
|
4110 | 0 | std::vector<CAddress> vAddr; |
4111 | |
|
4112 | 0 | vRecv >> ser_params(vAddr); |
4113 | |
|
4114 | 0 | if (!SetupAddressRelay(pfrom, *peer)) { Branch (4114:13): [True: 0, False: 0]
|
4115 | 0 | LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId()); |
4116 | 0 | return; |
4117 | 0 | } |
4118 | | |
4119 | 0 | if (vAddr.size() > MAX_ADDR_TO_SEND) Branch (4119:13): [True: 0, False: 0]
|
4120 | 0 | { |
4121 | 0 | Misbehaving(*peer, strprintf("%s message size = %u", msg_type, vAddr.size())); |
4122 | 0 | return; |
4123 | 0 | } |
4124 | | |
4125 | | // Store the new addresses |
4126 | 0 | std::vector<CAddress> vAddrOk; |
4127 | 0 | const auto current_a_time{Now<NodeSeconds>()}; |
4128 | | |
4129 | | // Update/increment addr rate limiting bucket. |
4130 | 0 | const auto current_time{GetTime<std::chrono::microseconds>()}; |
4131 | 0 | if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) { Branch (4131:13): [True: 0, False: 0]
|
4132 | | // Don't increment bucket if it's already full |
4133 | 0 | const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us); |
4134 | 0 | const double increment = Ticks<SecondsDouble>(time_diff) * MAX_ADDR_RATE_PER_SECOND; |
4135 | 0 | peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET); |
4136 | 0 | } |
4137 | 0 | peer->m_addr_token_timestamp = current_time; |
4138 | |
|
4139 | 0 | const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr); |
4140 | 0 | uint64_t num_proc = 0; |
4141 | 0 | uint64_t num_rate_limit = 0; |
4142 | 0 | Shuffle(vAddr.begin(), vAddr.end(), m_rng); |
4143 | 0 | for (CAddress& addr : vAddr) Branch (4143:29): [True: 0, False: 0]
|
4144 | 0 | { |
4145 | 0 | if (interruptMsgProc) Branch (4145:17): [True: 0, False: 0]
|
4146 | 0 | return; |
4147 | | |
4148 | | // Apply rate limiting. |
4149 | 0 | if (peer->m_addr_token_bucket < 1.0) { Branch (4149:17): [True: 0, False: 0]
|
4150 | 0 | if (rate_limited) { Branch (4150:21): [True: 0, False: 0]
|
4151 | 0 | ++num_rate_limit; |
4152 | 0 | continue; |
4153 | 0 | } |
4154 | 0 | } else { |
4155 | 0 | peer->m_addr_token_bucket -= 1.0; |
4156 | 0 | } |
4157 | | // We only bother storing full nodes, though this may include |
4158 | | // things which we would not make an outbound connection to, in |
4159 | | // part because we may make feeler connections to them. |
4160 | 0 | if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices)) Branch (4160:17): [True: 0, False: 0]
Branch (4160:60): [True: 0, False: 0]
|
4161 | 0 | continue; |
4162 | | |
4163 | 0 | if (addr.nTime <= NodeSeconds{100000000s} || addr.nTime > current_a_time + 10min) { Branch (4163:17): [True: 0, False: 0]
Branch (4163:17): [True: 0, False: 0]
Branch (4163:58): [True: 0, False: 0]
|
4164 | 0 | addr.nTime = current_a_time - 5 * 24h; |
4165 | 0 | } |
4166 | 0 | AddAddressKnown(*peer, addr); |
4167 | 0 | if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) { Branch (4167:17): [True: 0, False: 0]
Branch (4167:30): [True: 0, False: 0]
Branch (4167:63): [True: 0, False: 0]
|
4168 | | // Do not process banned/discouraged addresses beyond remembering we received them |
4169 | 0 | continue; |
4170 | 0 | } |
4171 | 0 | ++num_proc; |
4172 | 0 | const bool reachable{g_reachable_nets.Contains(addr)}; |
4173 | 0 | if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) { Branch (4173:17): [True: 0, False: 0]
Branch (4173:17): [True: 0, False: 0]
Branch (4173:56): [True: 0, False: 0]
Branch (4173:81): [True: 0, False: 0]
Branch (4173:103): [True: 0, False: 0]
|
4174 | | // Relay to a limited number of other nodes |
4175 | 0 | RelayAddress(pfrom.GetId(), addr, reachable); |
4176 | 0 | } |
4177 | | // Do not store addresses outside our network |
4178 | 0 | if (reachable) { Branch (4178:17): [True: 0, False: 0]
|
4179 | 0 | vAddrOk.push_back(addr); |
4180 | 0 | } |
4181 | 0 | } |
4182 | 0 | peer->m_addr_processed += num_proc; |
4183 | 0 | peer->m_addr_rate_limited += num_rate_limit; |
4184 | 0 | LogPrint(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n", |
4185 | 0 | vAddr.size(), num_proc, num_rate_limit, pfrom.GetId()); |
4186 | |
|
4187 | 0 | m_addrman.Add(vAddrOk, pfrom.addr, 2h); |
4188 | 0 | if (vAddr.size() < 1000) peer->m_getaddr_sent = false; Branch (4188:13): [True: 0, False: 0]
|
4189 | | |
4190 | | // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements |
4191 | 0 | if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) { Branch (4191:13): [True: 0, False: 0]
Branch (4191:40): [True: 0, False: 0]
|
4192 | 0 | LogPrint(BCLog::NET, "addrfetch connection completed peer=%d; disconnecting\n", pfrom.GetId()); |
4193 | 0 | pfrom.fDisconnect = true; |
4194 | 0 | } |
4195 | 0 | return; |
4196 | 0 | } |
4197 | | |
4198 | 0 | if (msg_type == NetMsgType::INV) { Branch (4198:9): [True: 0, False: 0]
|
4199 | 0 | std::vector<CInv> vInv; |
4200 | 0 | vRecv >> vInv; |
4201 | 0 | if (vInv.size() > MAX_INV_SZ) Branch (4201:13): [True: 0, False: 0]
|
4202 | 0 | { |
4203 | 0 | Misbehaving(*peer, strprintf("inv message size = %u", vInv.size())); |
4204 | 0 | return; |
4205 | 0 | } |
4206 | | |
4207 | 0 | const bool reject_tx_invs{RejectIncomingTxs(pfrom)}; |
4208 | |
|
4209 | 0 | LOCK(cs_main); |
4210 | |
|
4211 | 0 | const auto current_time{GetTime<std::chrono::microseconds>()}; |
4212 | 0 | uint256* best_block{nullptr}; |
4213 | |
|
4214 | 0 | for (CInv& inv : vInv) { Branch (4214:24): [True: 0, False: 0]
|
4215 | 0 | if (interruptMsgProc) return; Branch (4215:17): [True: 0, False: 0]
|
4216 | | |
4217 | | // Ignore INVs that don't match wtxidrelay setting. |
4218 | | // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting. |
4219 | | // This is fine as no INV messages are involved in that process. |
4220 | 0 | if (peer->m_wtxid_relay) { Branch (4220:17): [True: 0, False: 0]
|
4221 | 0 | if (inv.IsMsgTx()) continue; Branch (4221:21): [True: 0, False: 0]
|
4222 | 0 | } else { |
4223 | 0 | if (inv.IsMsgWtx()) continue; Branch (4223:21): [True: 0, False: 0]
|
4224 | 0 | } |
4225 | | |
4226 | 0 | if (inv.IsMsgBlk()) { Branch (4226:17): [True: 0, False: 0]
|
4227 | 0 | const bool fAlreadyHave = AlreadyHaveBlock(inv.hash); |
4228 | 0 | LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); |
4229 | |
|
4230 | 0 | UpdateBlockAvailability(pfrom.GetId(), inv.hash); |
4231 | 0 | if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() && !IsBlockRequested(inv.hash)) { Branch (4231:21): [True: 0, False: 0]
Branch (4231:38): [True: 0, False: 0]
Branch (4231:80): [True: 0, False: 0]
|
4232 | | // Headers-first is the primary method of announcement on |
4233 | | // the network. If a node fell back to sending blocks by |
4234 | | // inv, it may be for a re-org, or because we haven't |
4235 | | // completed initial headers sync. The final block hash |
4236 | | // provided should be the highest, so send a getheaders and |
4237 | | // then fetch the blocks we need to catch up. |
4238 | 0 | best_block = &inv.hash; |
4239 | 0 | } |
4240 | 0 | } else if (inv.IsGenTxMsg()) { Branch (4240:24): [True: 0, False: 0]
|
4241 | 0 | if (reject_tx_invs) { Branch (4241:21): [True: 0, False: 0]
|
4242 | 0 | LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId()); |
4243 | 0 | pfrom.fDisconnect = true; |
4244 | 0 | return; |
4245 | 0 | } |
4246 | 0 | const GenTxid gtxid = ToGenTxid(inv); |
4247 | 0 | const bool fAlreadyHave = AlreadyHaveTx(gtxid, /*include_reconsiderable=*/true); |
4248 | 0 | LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); |
4249 | |
|
4250 | 0 | AddKnownTx(*peer, inv.hash); |
4251 | 0 | if (!fAlreadyHave && !m_chainman.IsInitialBlockDownload()) { Branch (4251:21): [True: 0, False: 0]
Branch (4251:38): [True: 0, False: 0]
|
4252 | 0 | AddTxAnnouncement(pfrom, gtxid, current_time); |
4253 | 0 | } |
4254 | 0 | } else { |
4255 | 0 | LogPrint(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId()); |
4256 | 0 | } |
4257 | 0 | } |
4258 | | |
4259 | 0 | if (best_block != nullptr) { Branch (4259:13): [True: 0, False: 0]
|
4260 | | // If we haven't started initial headers-sync with this peer, then |
4261 | | // consider sending a getheaders now. On initial startup, there's a |
4262 | | // reliability vs bandwidth tradeoff, where we are only trying to do |
4263 | | // initial headers sync with one peer at a time, with a long |
4264 | | // timeout (at which point, if the sync hasn't completed, we will |
4265 | | // disconnect the peer and then choose another). In the meantime, |
4266 | | // as new blocks are found, we are willing to add one new peer per |
4267 | | // block to sync with as well, to sync quicker in the case where |
4268 | | // our initial peer is unresponsive (but less bandwidth than we'd |
4269 | | // use if we turned on sync with all peers). |
4270 | 0 | CNodeState& state{*Assert(State(pfrom.GetId()))}; |
4271 | 0 | if (state.fSyncStarted || (!peer->m_inv_triggered_getheaders_before_sync && *best_block != m_last_block_inv_triggering_headers_sync)) { Branch (4271:17): [True: 0, False: 0]
Branch (4271:40): [True: 0, False: 0]
Branch (4271:89): [True: 0, False: 0]
|
4272 | 0 | if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer)) { Branch (4272:21): [True: 0, False: 0]
|
4273 | 0 | LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", |
4274 | 0 | m_chainman.m_best_header->nHeight, best_block->ToString(), |
4275 | 0 | pfrom.GetId()); |
4276 | 0 | } |
4277 | 0 | if (!state.fSyncStarted) { Branch (4277:21): [True: 0, False: 0]
|
4278 | 0 | peer->m_inv_triggered_getheaders_before_sync = true; |
4279 | | // Update the last block hash that triggered a new headers |
4280 | | // sync, so that we don't turn on headers sync with more |
4281 | | // than 1 new peer every new block. |
4282 | 0 | m_last_block_inv_triggering_headers_sync = *best_block; |
4283 | 0 | } |
4284 | 0 | } |
4285 | 0 | } |
4286 | |
|
4287 | 0 | return; |
4288 | 0 | } |
4289 | | |
4290 | 0 | if (msg_type == NetMsgType::GETDATA) { Branch (4290:9): [True: 0, False: 0]
|
4291 | 0 | std::vector<CInv> vInv; |
4292 | 0 | vRecv >> vInv; |
4293 | 0 | if (vInv.size() > MAX_INV_SZ) Branch (4293:13): [True: 0, False: 0]
|
4294 | 0 | { |
4295 | 0 | Misbehaving(*peer, strprintf("getdata message size = %u", vInv.size())); |
4296 | 0 | return; |
4297 | 0 | } |
4298 | | |
4299 | 0 | LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId()); |
4300 | |
|
4301 | 0 | if (vInv.size() > 0) { Branch (4301:13): [True: 0, False: 0]
|
4302 | 0 | LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId()); |
4303 | 0 | } |
4304 | |
|
4305 | 0 | { |
4306 | 0 | LOCK(peer->m_getdata_requests_mutex); |
4307 | 0 | peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end()); |
4308 | 0 | ProcessGetData(pfrom, *peer, interruptMsgProc); |
4309 | 0 | } |
4310 | |
|
4311 | 0 | return; |
4312 | 0 | } |
4313 | | |
4314 | 0 | if (msg_type == NetMsgType::GETBLOCKS) { Branch (4314:9): [True: 0, False: 0]
|
4315 | 0 | CBlockLocator locator; |
4316 | 0 | uint256 hashStop; |
4317 | 0 | vRecv >> locator >> hashStop; |
4318 | |
|
4319 | 0 | if (locator.vHave.size() > MAX_LOCATOR_SZ) { Branch (4319:13): [True: 0, False: 0]
|
4320 | 0 | LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId()); |
4321 | 0 | pfrom.fDisconnect = true; |
4322 | 0 | return; |
4323 | 0 | } |
4324 | | |
4325 | | // We might have announced the currently-being-connected tip using a |
4326 | | // compact block, which resulted in the peer sending a getblocks |
4327 | | // request, which we would otherwise respond to without the new block. |
4328 | | // To avoid this situation we simply verify that we are on our best |
4329 | | // known chain now. This is super overkill, but we handle it better |
4330 | | // for getheaders requests, and there are no known nodes which support |
4331 | | // compact blocks but still use getblocks to request blocks. |
4332 | 0 | { |
4333 | 0 | std::shared_ptr<const CBlock> a_recent_block; |
4334 | 0 | { |
4335 | 0 | LOCK(m_most_recent_block_mutex); |
4336 | 0 | a_recent_block = m_most_recent_block; |
4337 | 0 | } |
4338 | 0 | BlockValidationState state; |
4339 | 0 | if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) { Branch (4339:17): [True: 0, False: 0]
|
4340 | 0 | LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString()); |
4341 | 0 | } |
4342 | 0 | } |
4343 | |
|
4344 | 0 | LOCK(cs_main); |
4345 | | |
4346 | | // Find the last block the caller has in the main chain |
4347 | 0 | const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator); |
4348 | | |
4349 | | // Send the rest of the chain |
4350 | 0 | if (pindex) Branch (4350:13): [True: 0, False: 0]
|
4351 | 0 | pindex = m_chainman.ActiveChain().Next(pindex); |
4352 | 0 | int nLimit = 500; |
4353 | 0 | LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom.GetId()); |
4354 | 0 | for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) Branch (4354:16): [True: 0, False: 0]
|
4355 | 0 | { |
4356 | 0 | if (pindex->GetBlockHash() == hashStop) Branch (4356:17): [True: 0, False: 0]
|
4357 | 0 | { |
4358 | 0 | LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); |
4359 | 0 | break; |
4360 | 0 | } |
4361 | | // If pruning, don't inv blocks unless we have on disk and are likely to still have |
4362 | | // for some reasonable time window (1 hour) that block relay might require. |
4363 | 0 | const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing; |
4364 | 0 | if (m_chainman.m_blockman.IsPruneMode() && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave)) { Branch (4364:17): [True: 0, False: 0]
Branch (4364:57): [True: 0, False: 0]
Branch (4364:97): [True: 0, False: 0]
|
4365 | 0 | LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); |
4366 | 0 | break; |
4367 | 0 | } |
4368 | 0 | WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash())); |
4369 | 0 | if (--nLimit <= 0) { Branch (4369:17): [True: 0, False: 0]
|
4370 | | // When this block is requested, we'll send an inv that'll |
4371 | | // trigger the peer to getblocks the next batch of inventory. |
4372 | 0 | LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); |
4373 | 0 | WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();}); |
4374 | 0 | break; |
4375 | 0 | } |
4376 | 0 | } |
4377 | 0 | return; |
4378 | 0 | } |
4379 | | |
4380 | 0 | if (msg_type == NetMsgType::GETBLOCKTXN) { Branch (4380:9): [True: 0, False: 0]
|
4381 | 0 | BlockTransactionsRequest req; |
4382 | 0 | vRecv >> req; |
4383 | |
|
4384 | 0 | std::shared_ptr<const CBlock> recent_block; |
4385 | 0 | { |
4386 | 0 | LOCK(m_most_recent_block_mutex); |
4387 | 0 | if (m_most_recent_block_hash == req.blockhash) Branch (4387:17): [True: 0, False: 0]
|
4388 | 0 | recent_block = m_most_recent_block; |
4389 | | // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion |
4390 | 0 | } |
4391 | 0 | if (recent_block) { Branch (4391:13): [True: 0, False: 0]
|
4392 | 0 | SendBlockTransactions(pfrom, *peer, *recent_block, req); |
4393 | 0 | return; |
4394 | 0 | } |
4395 | | |
4396 | 0 | FlatFilePos block_pos{}; |
4397 | 0 | { |
4398 | 0 | LOCK(cs_main); |
4399 | |
|
4400 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash); |
4401 | 0 | if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) { Branch (4401:17): [True: 0, False: 0]
Branch (4401:28): [True: 0, False: 0]
|
4402 | 0 | LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId()); |
4403 | 0 | return; |
4404 | 0 | } |
4405 | | |
4406 | 0 | if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) { Branch (4406:17): [True: 0, False: 0]
|
4407 | 0 | block_pos = pindex->GetBlockPos(); |
4408 | 0 | } |
4409 | 0 | } |
4410 | | |
4411 | 0 | if (!block_pos.IsNull()) { Branch (4411:13): [True: 0, False: 0]
|
4412 | 0 | CBlock block; |
4413 | 0 | const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(block, block_pos)}; |
4414 | | // If height is above MAX_BLOCKTXN_DEPTH then this block cannot get |
4415 | | // pruned after we release cs_main above, so this read should never fail. |
4416 | 0 | assert(ret); |
4417 | | |
4418 | 0 | SendBlockTransactions(pfrom, *peer, block, req); |
4419 | 0 | return; |
4420 | 0 | } |
4421 | | |
4422 | | // If an older block is requested (should never happen in practice, |
4423 | | // but can happen in tests) send a block response instead of a |
4424 | | // blocktxn response. Sending a full block response instead of a |
4425 | | // small blocktxn response is preferable in the case where a peer |
4426 | | // might maliciously send lots of getblocktxn requests to trigger |
4427 | | // expensive disk reads, because it will require the peer to |
4428 | | // actually receive all the data read from disk over the network. |
4429 | 0 | LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH); |
4430 | 0 | CInv inv{MSG_WITNESS_BLOCK, req.blockhash}; |
4431 | 0 | WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv)); |
4432 | | // The message processing loop will go around again (without pausing) and we'll respond then |
4433 | 0 | return; |
4434 | 0 | } |
4435 | | |
4436 | 0 | if (msg_type == NetMsgType::GETHEADERS) { Branch (4436:9): [True: 0, False: 0]
|
4437 | 0 | CBlockLocator locator; |
4438 | 0 | uint256 hashStop; |
4439 | 0 | vRecv >> locator >> hashStop; |
4440 | |
|
4441 | 0 | if (locator.vHave.size() > MAX_LOCATOR_SZ) { Branch (4441:13): [True: 0, False: 0]
|
4442 | 0 | LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId()); |
4443 | 0 | pfrom.fDisconnect = true; |
4444 | 0 | return; |
4445 | 0 | } |
4446 | | |
4447 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) { Branch (4447:13): [True: 0, False: 0]
|
4448 | 0 | LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId()); |
4449 | 0 | return; |
4450 | 0 | } |
4451 | | |
4452 | 0 | LOCK(cs_main); |
4453 | | |
4454 | | // Note that if we were to be on a chain that forks from the checkpointed |
4455 | | // chain, then serving those headers to a peer that has seen the |
4456 | | // checkpointed chain would cause that peer to disconnect us. Requiring |
4457 | | // that our chainwork exceed the minimum chain work is a protection against |
4458 | | // being fed a bogus chain when we started up for the first time and |
4459 | | // getting partitioned off the honest network for serving that chain to |
4460 | | // others. |
4461 | 0 | if (m_chainman.ActiveTip() == nullptr || Branch (4461:13): [True: 0, False: 0]
|
4462 | 0 | (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && !pfrom.HasPermission(NetPermissionFlags::Download))) { Branch (4462:18): [True: 0, False: 0]
Branch (4462:88): [True: 0, False: 0]
|
4463 | 0 | LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId()); |
4464 | | // Just respond with an empty headers message, to tell the peer to |
4465 | | // go away but not treat us as unresponsive. |
4466 | 0 | MakeAndPushMessage(pfrom, NetMsgType::HEADERS, std::vector<CBlockHeader>()); |
4467 | 0 | return; |
4468 | 0 | } |
4469 | | |
4470 | 0 | CNodeState *nodestate = State(pfrom.GetId()); |
4471 | 0 | const CBlockIndex* pindex = nullptr; |
4472 | 0 | if (locator.IsNull()) Branch (4472:13): [True: 0, False: 0]
|
4473 | 0 | { |
4474 | | // If locator is null, return the hashStop block |
4475 | 0 | pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop); |
4476 | 0 | if (!pindex) { Branch (4476:17): [True: 0, False: 0]
|
4477 | 0 | return; |
4478 | 0 | } |
4479 | | |
4480 | 0 | if (!BlockRequestAllowed(pindex)) { Branch (4480:17): [True: 0, False: 0]
|
4481 | 0 | LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId()); |
4482 | 0 | return; |
4483 | 0 | } |
4484 | 0 | } |
4485 | 0 | else |
4486 | 0 | { |
4487 | | // Find the last block the caller has in the main chain |
4488 | 0 | pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator); |
4489 | 0 | if (pindex) Branch (4489:17): [True: 0, False: 0]
|
4490 | 0 | pindex = m_chainman.ActiveChain().Next(pindex); |
4491 | 0 | } |
4492 | | |
4493 | | // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end |
4494 | 0 | std::vector<CBlock> vHeaders; |
4495 | 0 | int nLimit = MAX_HEADERS_RESULTS; |
4496 | 0 | LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId()); |
4497 | 0 | for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) Branch (4497:16): [True: 0, False: 0]
|
4498 | 0 | { |
4499 | 0 | vHeaders.emplace_back(pindex->GetBlockHeader()); |
4500 | 0 | if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) Branch (4500:17): [True: 0, False: 0]
Branch (4500:17): [True: 0, False: 0]
Branch (4500:34): [True: 0, False: 0]
|
4501 | 0 | break; |
4502 | 0 | } |
4503 | | // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR |
4504 | | // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty |
4505 | | // headers message). In both cases it's safe to update |
4506 | | // pindexBestHeaderSent to be our tip. |
4507 | | // |
4508 | | // It is important that we simply reset the BestHeaderSent value here, |
4509 | | // and not max(BestHeaderSent, newHeaderSent). We might have announced |
4510 | | // the currently-being-connected tip using a compact block, which |
4511 | | // resulted in the peer sending a headers request, which we respond to |
4512 | | // without the new block. By resetting the BestHeaderSent, we ensure we |
4513 | | // will re-announce the new block via headers (or compact blocks again) |
4514 | | // in the SendMessages logic. |
4515 | 0 | nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip(); Branch (4515:43): [True: 0, False: 0]
|
4516 | 0 | MakeAndPushMessage(pfrom, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders)); |
4517 | 0 | return; |
4518 | 0 | } |
4519 | | |
4520 | 0 | if (msg_type == NetMsgType::TX) { Branch (4520:9): [True: 0, False: 0]
|
4521 | 0 | if (RejectIncomingTxs(pfrom)) { Branch (4521:13): [True: 0, False: 0]
|
4522 | 0 | LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom.GetId()); |
4523 | 0 | pfrom.fDisconnect = true; |
4524 | 0 | return; |
4525 | 0 | } |
4526 | | |
4527 | | // Stop processing the transaction early if we are still in IBD since we don't |
4528 | | // have enough information to validate it yet. Sending unsolicited transactions |
4529 | | // is not considered a protocol violation, so don't punish the peer. |
4530 | 0 | if (m_chainman.IsInitialBlockDownload()) return; Branch (4530:13): [True: 0, False: 0]
|
4531 | | |
4532 | 0 | CTransactionRef ptx; |
4533 | 0 | vRecv >> TX_WITH_WITNESS(ptx); |
4534 | 0 | const CTransaction& tx = *ptx; |
4535 | |
|
4536 | 0 | const uint256& txid = ptx->GetHash(); |
4537 | 0 | const uint256& wtxid = ptx->GetWitnessHash(); |
4538 | |
|
4539 | 0 | const uint256& hash = peer->m_wtxid_relay ? wtxid : txid; Branch (4539:31): [True: 0, False: 0]
|
4540 | 0 | AddKnownTx(*peer, hash); |
4541 | |
|
4542 | 0 | LOCK(cs_main); |
4543 | |
|
4544 | 0 | m_txrequest.ReceivedResponse(pfrom.GetId(), txid); |
4545 | 0 | if (tx.HasWitness()) m_txrequest.ReceivedResponse(pfrom.GetId(), wtxid); Branch (4545:13): [True: 0, False: 0]
|
4546 | | |
4547 | | // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the |
4548 | | // absence of witness malleation, this is strictly better, because the |
4549 | | // recent rejects filter may contain the wtxid but rarely contains |
4550 | | // the txid of a segwit transaction that has been rejected. |
4551 | | // In the presence of witness malleation, it's possible that by only |
4552 | | // doing the check with wtxid, we could overlook a transaction which |
4553 | | // was confirmed with a different witness, or exists in our mempool |
4554 | | // with a different witness, but this has limited downside: |
4555 | | // mempool validation does its own lookup of whether we have the txid |
4556 | | // already; and an adversary can already relay us old transactions |
4557 | | // (older than our recency filter) if trying to DoS us, without any need |
4558 | | // for witness malleation. |
4559 | 0 | if (AlreadyHaveTx(GenTxid::Wtxid(wtxid), /*include_reconsiderable=*/true)) { Branch (4559:13): [True: 0, False: 0]
|
4560 | 0 | if (pfrom.HasPermission(NetPermissionFlags::ForceRelay)) { Branch (4560:17): [True: 0, False: 0]
|
4561 | | // Always relay transactions received from peers with forcerelay |
4562 | | // permission, even if they were already in the mempool, allowing |
4563 | | // the node to function as a gateway for nodes hidden behind it. |
4564 | 0 | if (!m_mempool.exists(GenTxid::Txid(tx.GetHash()))) { Branch (4564:21): [True: 0, False: 0]
|
4565 | 0 | LogPrintf("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n", |
4566 | 0 | tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId()); |
4567 | 0 | } else { |
4568 | 0 | LogPrintf("Force relaying tx %s (wtxid=%s) from peer=%d\n", |
4569 | 0 | tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId()); |
4570 | 0 | RelayTransaction(tx.GetHash(), tx.GetWitnessHash()); |
4571 | 0 | } |
4572 | 0 | } |
4573 | |
|
4574 | 0 | if (RecentRejectsReconsiderableFilter().contains(wtxid)) { Branch (4574:17): [True: 0, False: 0]
|
4575 | | // When a transaction is already in m_recent_rejects_reconsiderable, we shouldn't submit |
4576 | | // it by itself again. However, look for a matching child in the orphanage, as it is |
4577 | | // possible that they succeed as a package. |
4578 | 0 | LogPrint(BCLog::TXPACKAGES, "found tx %s (wtxid=%s) in reconsiderable rejects, looking for child in orphanage\n", |
4579 | 0 | txid.ToString(), wtxid.ToString()); |
4580 | 0 | if (auto package_to_validate{Find1P1CPackage(ptx, pfrom.GetId())}) { Branch (4580:26): [True: 0, False: 0]
|
4581 | 0 | const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)}; |
4582 | 0 | LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(), |
4583 | 0 | package_result.m_state.IsValid() ? "package accepted" : "package rejected"); |
4584 | 0 | ProcessPackageResult(package_to_validate.value(), package_result); |
4585 | 0 | } |
4586 | 0 | } |
4587 | | // If a tx is detected by m_recent_rejects it is ignored. Because we haven't |
4588 | | // submitted the tx to our mempool, we won't have computed a DoS |
4589 | | // score for it or determined exactly why we consider it invalid. |
4590 | | // |
4591 | | // This means we won't penalize any peer subsequently relaying a DoSy |
4592 | | // tx (even if we penalized the first peer who gave it to us) because |
4593 | | // we have to account for m_recent_rejects showing false positives. In |
4594 | | // other words, we shouldn't penalize a peer if we aren't *sure* they |
4595 | | // submitted a DoSy tx. |
4596 | | // |
4597 | | // Note that m_recent_rejects doesn't just record DoSy or invalid |
4598 | | // transactions, but any tx not accepted by the mempool, which may be |
4599 | | // due to node policy (vs. consensus). So we can't blanket penalize a |
4600 | | // peer simply for relaying a tx that our m_recent_rejects has caught, |
4601 | | // regardless of false positives. |
4602 | 0 | return; |
4603 | 0 | } |
4604 | | |
4605 | 0 | const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx); |
4606 | 0 | const TxValidationState& state = result.m_state; |
4607 | |
|
4608 | 0 | if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) { Branch (4608:13): [True: 0, False: 0]
|
4609 | 0 | ProcessValidTx(pfrom.GetId(), ptx, result.m_replaced_transactions); |
4610 | 0 | pfrom.m_last_tx_time = GetTime<std::chrono::seconds>(); |
4611 | 0 | } |
4612 | 0 | else if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) Branch (4612:18): [True: 0, False: 0]
|
4613 | 0 | { |
4614 | 0 | bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected |
4615 | | |
4616 | | // Deduplicate parent txids, so that we don't have to loop over |
4617 | | // the same parent txid more than once down below. |
4618 | 0 | std::vector<uint256> unique_parents; |
4619 | 0 | unique_parents.reserve(tx.vin.size()); |
4620 | 0 | for (const CTxIn& txin : tx.vin) { Branch (4620:36): [True: 0, False: 0]
|
4621 | | // We start with all parents, and then remove duplicates below. |
4622 | 0 | unique_parents.push_back(txin.prevout.hash); |
4623 | 0 | } |
4624 | 0 | std::sort(unique_parents.begin(), unique_parents.end()); |
4625 | 0 | unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end()); |
4626 | | |
4627 | | // Distinguish between parents in m_recent_rejects and RecentRejectsReconsiderableFilter(). |
4628 | | // We can tolerate having up to 1 parent in m_recent_rejects_reconsiderable since we |
4629 | | // submit 1p1c packages. However, fail immediately if any are in RecentRejectsFilter(). |
4630 | 0 | std::optional<uint256> rejected_parent_reconsiderable; |
4631 | 0 | for (const uint256& parent_txid : unique_parents) { Branch (4631:45): [True: 0, False: 0]
|
4632 | 0 | if (RecentRejectsFilter().contains(parent_txid)) { Branch (4632:21): [True: 0, False: 0]
|
4633 | 0 | fRejectedParents = true; |
4634 | 0 | break; |
4635 | 0 | } else if (RecentRejectsReconsiderableFilter().contains(parent_txid) && !m_mempool.exists(GenTxid::Txid(parent_txid))) { Branch (4635:28): [True: 0, False: 0]
Branch (4635:28): [True: 0, False: 0]
Branch (4635:89): [True: 0, False: 0]
|
4636 | | // More than 1 parent in m_recent_rejects_reconsiderable: 1p1c will not be |
4637 | | // sufficient to accept this package, so just give up here. |
4638 | 0 | if (rejected_parent_reconsiderable.has_value()) { Branch (4638:25): [True: 0, False: 0]
|
4639 | 0 | fRejectedParents = true; |
4640 | 0 | break; |
4641 | 0 | } |
4642 | 0 | rejected_parent_reconsiderable = parent_txid; |
4643 | 0 | } |
4644 | 0 | } |
4645 | 0 | if (!fRejectedParents) { Branch (4645:17): [True: 0, False: 0]
|
4646 | 0 | const auto current_time{GetTime<std::chrono::microseconds>()}; |
4647 | |
|
4648 | 0 | for (const uint256& parent_txid : unique_parents) { Branch (4648:49): [True: 0, False: 0]
|
4649 | | // Here, we only have the txid (and not wtxid) of the |
4650 | | // inputs, so we only request in txid mode, even for |
4651 | | // wtxidrelay peers. |
4652 | | // Eventually we should replace this with an improved |
4653 | | // protocol for getting all unconfirmed parents. |
4654 | 0 | const auto gtxid{GenTxid::Txid(parent_txid)}; |
4655 | 0 | AddKnownTx(*peer, parent_txid); |
4656 | | // Exclude m_recent_rejects_reconsiderable: the missing parent may have been |
4657 | | // previously rejected for being too low feerate. This orphan might CPFP it. |
4658 | 0 | if (!AlreadyHaveTx(gtxid, /*include_reconsiderable=*/false)) AddTxAnnouncement(pfrom, gtxid, current_time); Branch (4658:25): [True: 0, False: 0]
|
4659 | 0 | } |
4660 | |
|
4661 | 0 | if (m_orphanage.AddTx(ptx, pfrom.GetId())) { Branch (4661:21): [True: 0, False: 0]
|
4662 | 0 | AddToCompactExtraTransactions(ptx); |
4663 | 0 | } |
4664 | | |
4665 | | // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore. |
4666 | 0 | m_txrequest.ForgetTxHash(tx.GetHash()); |
4667 | 0 | m_txrequest.ForgetTxHash(tx.GetWitnessHash()); |
4668 | | |
4669 | | // DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789) |
4670 | 0 | m_orphanage.LimitOrphans(m_opts.max_orphan_txs, m_rng); |
4671 | 0 | } else { |
4672 | 0 | LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s (wtxid=%s)\n", |
4673 | 0 | tx.GetHash().ToString(), |
4674 | 0 | tx.GetWitnessHash().ToString()); |
4675 | | // We will continue to reject this tx since it has rejected |
4676 | | // parents so avoid re-requesting it from other peers. |
4677 | | // Here we add both the txid and the wtxid, as we know that |
4678 | | // regardless of what witness is provided, we will not accept |
4679 | | // this, so we don't need to allow for redownload of this txid |
4680 | | // from any of our non-wtxidrelay peers. |
4681 | 0 | RecentRejectsFilter().insert(tx.GetHash().ToUint256()); |
4682 | 0 | RecentRejectsFilter().insert(tx.GetWitnessHash().ToUint256()); |
4683 | 0 | m_txrequest.ForgetTxHash(tx.GetHash()); |
4684 | 0 | m_txrequest.ForgetTxHash(tx.GetWitnessHash()); |
4685 | 0 | } |
4686 | 0 | } |
4687 | 0 | if (state.IsInvalid()) { Branch (4687:13): [True: 0, False: 0]
|
4688 | 0 | ProcessInvalidTx(pfrom.GetId(), ptx, state, /*maybe_add_extra_compact_tx=*/true); |
4689 | 0 | } |
4690 | | // When a transaction fails for TX_RECONSIDERABLE, look for a matching child in the |
4691 | | // orphanage, as it is possible that they succeed as a package. |
4692 | 0 | if (state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) { Branch (4692:13): [True: 0, False: 0]
|
4693 | 0 | LogPrint(BCLog::TXPACKAGES, "tx %s (wtxid=%s) failed but reconsiderable, looking for child in orphanage\n", |
4694 | 0 | txid.ToString(), wtxid.ToString()); |
4695 | 0 | if (auto package_to_validate{Find1P1CPackage(ptx, pfrom.GetId())}) { Branch (4695:22): [True: 0, False: 0]
|
4696 | 0 | const auto package_result{ProcessNewPackage(m_chainman.ActiveChainstate(), m_mempool, package_to_validate->m_txns, /*test_accept=*/false, /*client_maxfeerate=*/std::nullopt)}; |
4697 | 0 | LogDebug(BCLog::TXPACKAGES, "package evaluation for %s: %s\n", package_to_validate->ToString(), |
4698 | 0 | package_result.m_state.IsValid() ? "package accepted" : "package rejected"); |
4699 | 0 | ProcessPackageResult(package_to_validate.value(), package_result); |
4700 | 0 | } |
4701 | 0 | } |
4702 | |
|
4703 | 0 | return; |
4704 | 0 | } |
4705 | | |
4706 | 0 | if (msg_type == NetMsgType::CMPCTBLOCK) Branch (4706:9): [True: 0, False: 0]
|
4707 | 0 | { |
4708 | | // Ignore cmpctblock received while importing |
4709 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) { Branch (4709:13): [True: 0, False: 0]
|
4710 | 0 | LogPrint(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId()); |
4711 | 0 | return; |
4712 | 0 | } |
4713 | | |
4714 | 0 | CBlockHeaderAndShortTxIDs cmpctblock; |
4715 | 0 | vRecv >> cmpctblock; |
4716 | |
|
4717 | 0 | bool received_new_header = false; |
4718 | 0 | const auto blockhash = cmpctblock.header.GetHash(); |
4719 | |
|
4720 | 0 | { |
4721 | 0 | LOCK(cs_main); |
4722 | |
|
4723 | 0 | const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock); |
4724 | 0 | if (!prev_block) { Branch (4724:13): [True: 0, False: 0]
|
4725 | | // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers |
4726 | 0 | if (!m_chainman.IsInitialBlockDownload()) { Branch (4726:17): [True: 0, False: 0]
|
4727 | 0 | MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer); |
4728 | 0 | } |
4729 | 0 | return; |
4730 | 0 | } else if (prev_block->nChainWork + CalculateClaimedHeadersWork({cmpctblock.header}) < GetAntiDoSWorkThreshold()) { Branch (4730:20): [True: 0, False: 0]
|
4731 | | // If we get a low-work header in a compact block, we can ignore it. |
4732 | 0 | LogPrint(BCLog::NET, "Ignoring low-work compact block from peer %d\n", pfrom.GetId()); |
4733 | 0 | return; |
4734 | 0 | } |
4735 | | |
4736 | 0 | if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) { Branch (4736:13): [True: 0, False: 0]
|
4737 | 0 | received_new_header = true; |
4738 | 0 | } |
4739 | 0 | } |
4740 | | |
4741 | 0 | const CBlockIndex *pindex = nullptr; |
4742 | 0 | BlockValidationState state; |
4743 | 0 | if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header}, /*min_pow_checked=*/true, state, &pindex)) { Branch (4743:13): [True: 0, False: 0]
|
4744 | 0 | if (state.IsInvalid()) { Branch (4744:17): [True: 0, False: 0]
|
4745 | 0 | MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block=*/true, "invalid header via cmpctblock"); |
4746 | 0 | return; |
4747 | 0 | } |
4748 | 0 | } |
4749 | | |
4750 | 0 | if (received_new_header) { Branch (4750:13): [True: 0, False: 0]
|
4751 | 0 | LogInfo("Saw new cmpctblock header hash=%s peer=%d\n", |
4752 | 0 | blockhash.ToString(), pfrom.GetId()); |
4753 | 0 | } |
4754 | |
|
4755 | 0 | bool fProcessBLOCKTXN = false; |
4756 | | |
4757 | | // If we end up treating this as a plain headers message, call that as well |
4758 | | // without cs_main. |
4759 | 0 | bool fRevertToHeaderProcessing = false; |
4760 | | |
4761 | | // Keep a CBlock for "optimistic" compactblock reconstructions (see |
4762 | | // below) |
4763 | 0 | std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); |
4764 | 0 | bool fBlockReconstructed = false; |
4765 | |
|
4766 | 0 | { |
4767 | 0 | LOCK(cs_main); |
4768 | | // If AcceptBlockHeader returned true, it set pindex |
4769 | 0 | assert(pindex); |
4770 | 0 | UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash()); |
4771 | |
|
4772 | 0 | CNodeState *nodestate = State(pfrom.GetId()); |
4773 | | |
4774 | | // If this was a new header with more work than our tip, update the |
4775 | | // peer's last block announcement time |
4776 | 0 | if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) { Branch (4776:13): [True: 0, False: 0]
Branch (4776:36): [True: 0, False: 0]
|
4777 | 0 | nodestate->m_last_block_announcement = GetTime(); |
4778 | 0 | } |
4779 | |
|
4780 | 0 | if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here Branch (4780:13): [True: 0, False: 0]
|
4781 | 0 | return; |
4782 | | |
4783 | 0 | auto range_flight = mapBlocksInFlight.equal_range(pindex->GetBlockHash()); |
4784 | 0 | size_t already_in_flight = std::distance(range_flight.first, range_flight.second); |
4785 | 0 | bool requested_block_from_this_peer{false}; |
4786 | | |
4787 | | // Multimap ensures ordering of outstanding requests. It's either empty or first in line. |
4788 | 0 | bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId()); Branch (4788:32): [True: 0, False: 0]
Branch (4788:58): [True: 0, False: 0]
|
4789 | |
|
4790 | 0 | while (range_flight.first != range_flight.second) { Branch (4790:16): [True: 0, False: 0]
|
4791 | 0 | if (range_flight.first->second.first == pfrom.GetId()) { Branch (4791:17): [True: 0, False: 0]
|
4792 | 0 | requested_block_from_this_peer = true; |
4793 | 0 | break; |
4794 | 0 | } |
4795 | 0 | range_flight.first++; |
4796 | 0 | } |
4797 | |
|
4798 | 0 | if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better Branch (4798:13): [True: 0, False: 0]
|
4799 | 0 | pindex->nTx != 0) { // We had this block at some point, but pruned it Branch (4799:17): [True: 0, False: 0]
|
4800 | 0 | if (requested_block_from_this_peer) { Branch (4800:17): [True: 0, False: 0]
|
4801 | | // We requested this block for some reason, but our mempool will probably be useless |
4802 | | // so we just grab the block via normal getdata |
4803 | 0 | std::vector<CInv> vInv(1); |
4804 | 0 | vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); |
4805 | 0 | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); |
4806 | 0 | } |
4807 | 0 | return; |
4808 | 0 | } |
4809 | | |
4810 | | // If we're not close to tip yet, give up and let parallel block fetch work its magic |
4811 | 0 | if (!already_in_flight && !CanDirectFetch()) { Branch (4811:13): [True: 0, False: 0]
Branch (4811:35): [True: 0, False: 0]
|
4812 | 0 | return; |
4813 | 0 | } |
4814 | | |
4815 | | // We want to be a bit conservative just to be extra careful about DoS |
4816 | | // possibilities in compact block processing... |
4817 | 0 | if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) { Branch (4817:13): [True: 0, False: 0]
|
4818 | 0 | if ((already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK && nodestate->vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || Branch (4818:18): [True: 0, False: 0]
Branch (4818:76): [True: 0, False: 0]
|
4819 | 0 | requested_block_from_this_peer) { Branch (4819:18): [True: 0, False: 0]
|
4820 | 0 | std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr; |
4821 | 0 | if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) { Branch (4821:21): [True: 0, False: 0]
|
4822 | 0 | if (!(*queuedBlockIt)->partialBlock) Branch (4822:25): [True: 0, False: 0]
|
4823 | 0 | (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool)); |
4824 | 0 | else { |
4825 | | // The block was already in flight using compact blocks from the same peer |
4826 | 0 | LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n"); |
4827 | 0 | return; |
4828 | 0 | } |
4829 | 0 | } |
4830 | | |
4831 | 0 | PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock; |
4832 | 0 | ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact); |
4833 | 0 | if (status == READ_STATUS_INVALID) { Branch (4833:21): [True: 0, False: 0]
|
4834 | 0 | RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect |
4835 | 0 | Misbehaving(*peer, "invalid compact block"); |
4836 | 0 | return; |
4837 | 0 | } else if (status == READ_STATUS_FAILED) { Branch (4837:28): [True: 0, False: 0]
|
4838 | 0 | if (first_in_flight) { Branch (4838:25): [True: 0, False: 0]
|
4839 | | // Duplicate txindexes, the block is now in-flight, so just request it |
4840 | 0 | std::vector<CInv> vInv(1); |
4841 | 0 | vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); |
4842 | 0 | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); |
4843 | 0 | } else { |
4844 | | // Give up for this peer and wait for other peer(s) |
4845 | 0 | RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); |
4846 | 0 | } |
4847 | 0 | return; |
4848 | 0 | } |
4849 | | |
4850 | 0 | BlockTransactionsRequest req; |
4851 | 0 | for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) { Branch (4851:36): [True: 0, False: 0]
|
4852 | 0 | if (!partialBlock.IsTxAvailable(i)) Branch (4852:25): [True: 0, False: 0]
|
4853 | 0 | req.indexes.push_back(i); |
4854 | 0 | } |
4855 | 0 | if (req.indexes.empty()) { Branch (4855:21): [True: 0, False: 0]
|
4856 | 0 | fProcessBLOCKTXN = true; |
4857 | 0 | } else if (first_in_flight) { Branch (4857:28): [True: 0, False: 0]
|
4858 | | // We will try to round-trip any compact blocks we get on failure, |
4859 | | // as long as it's first... |
4860 | 0 | req.blockhash = pindex->GetBlockHash(); |
4861 | 0 | MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req); |
4862 | 0 | } else if (pfrom.m_bip152_highbandwidth_to && Branch (4862:28): [True: 0, False: 0]
|
4863 | 0 | (!pfrom.IsInboundConn() || Branch (4863:22): [True: 0, False: 0]
|
4864 | 0 | IsBlockRequestedFromOutbound(blockhash) || Branch (4864:21): [True: 0, False: 0]
|
4865 | 0 | already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK - 1)) { Branch (4865:21): [True: 0, False: 0]
|
4866 | | // ... or it's a hb relay peer and: |
4867 | | // - peer is outbound, or |
4868 | | // - we already have an outbound attempt in flight(so we'll take what we can get), or |
4869 | | // - it's not the final parallel download slot (which we may reserve for first outbound) |
4870 | 0 | req.blockhash = pindex->GetBlockHash(); |
4871 | 0 | MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req); |
4872 | 0 | } else { |
4873 | | // Give up for this peer and wait for other peer(s) |
4874 | 0 | RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); |
4875 | 0 | } |
4876 | 0 | } else { |
4877 | | // This block is either already in flight from a different |
4878 | | // peer, or this peer has too many blocks outstanding to |
4879 | | // download from. |
4880 | | // Optimistically try to reconstruct anyway since we might be |
4881 | | // able to without any round trips. |
4882 | 0 | PartiallyDownloadedBlock tempBlock(&m_mempool); |
4883 | 0 | ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact); |
4884 | 0 | if (status != READ_STATUS_OK) { Branch (4884:21): [True: 0, False: 0]
|
4885 | | // TODO: don't ignore failures |
4886 | 0 | return; |
4887 | 0 | } |
4888 | 0 | std::vector<CTransactionRef> dummy; |
4889 | 0 | status = tempBlock.FillBlock(*pblock, dummy); |
4890 | 0 | if (status == READ_STATUS_OK) { Branch (4890:21): [True: 0, False: 0]
|
4891 | 0 | fBlockReconstructed = true; |
4892 | 0 | } |
4893 | 0 | } |
4894 | 0 | } else { |
4895 | 0 | if (requested_block_from_this_peer) { Branch (4895:17): [True: 0, False: 0]
|
4896 | | // We requested this block, but its far into the future, so our |
4897 | | // mempool will probably be useless - request the block normally |
4898 | 0 | std::vector<CInv> vInv(1); |
4899 | 0 | vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); |
4900 | 0 | MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); |
4901 | 0 | return; |
4902 | 0 | } else { |
4903 | | // If this was an announce-cmpctblock, we want the same treatment as a header message |
4904 | 0 | fRevertToHeaderProcessing = true; |
4905 | 0 | } |
4906 | 0 | } |
4907 | 0 | } // cs_main |
4908 | | |
4909 | 0 | if (fProcessBLOCKTXN) { Branch (4909:13): [True: 0, False: 0]
|
4910 | 0 | BlockTransactions txn; |
4911 | 0 | txn.blockhash = blockhash; |
4912 | 0 | return ProcessCompactBlockTxns(pfrom, *peer, txn); |
4913 | 0 | } |
4914 | | |
4915 | 0 | if (fRevertToHeaderProcessing) { Branch (4915:13): [True: 0, False: 0]
|
4916 | | // Headers received from HB compact block peers are permitted to be |
4917 | | // relayed before full validation (see BIP 152), so we don't want to disconnect |
4918 | | // the peer if the header turns out to be for an invalid block. |
4919 | | // Note that if a peer tries to build on an invalid chain, that |
4920 | | // will be detected and the peer will be disconnected/discouraged. |
4921 | 0 | return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true); |
4922 | 0 | } |
4923 | | |
4924 | 0 | if (fBlockReconstructed) { Branch (4924:13): [True: 0, False: 0]
|
4925 | | // If we got here, we were able to optimistically reconstruct a |
4926 | | // block that is in flight from some other peer. |
4927 | 0 | { |
4928 | 0 | LOCK(cs_main); |
4929 | 0 | mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false)); |
4930 | 0 | } |
4931 | | // Setting force_processing to true means that we bypass some of |
4932 | | // our anti-DoS protections in AcceptBlock, which filters |
4933 | | // unrequested blocks that might be trying to waste our resources |
4934 | | // (eg disk space). Because we only try to reconstruct blocks when |
4935 | | // we're close to caught up (via the CanDirectFetch() requirement |
4936 | | // above, combined with the behavior of not requesting blocks until |
4937 | | // we have a chain with at least the minimum chain work), and we ignore |
4938 | | // compact blocks with less work than our tip, it is safe to treat |
4939 | | // reconstructed compact blocks as having been requested. |
4940 | 0 | ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true); |
4941 | 0 | LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid() |
4942 | 0 | if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) { Branch (4942:17): [True: 0, False: 0]
|
4943 | | // Clear download state for this block, which is in |
4944 | | // process from some other peer. We do this after calling |
4945 | | // ProcessNewBlock so that a malleated cmpctblock announcement |
4946 | | // can't be used to interfere with block relay. |
4947 | 0 | RemoveBlockRequest(pblock->GetHash(), std::nullopt); |
4948 | 0 | } |
4949 | 0 | } |
4950 | 0 | return; |
4951 | 0 | } |
4952 | | |
4953 | 0 | if (msg_type == NetMsgType::BLOCKTXN) Branch (4953:9): [True: 0, False: 0]
|
4954 | 0 | { |
4955 | | // Ignore blocktxn received while importing |
4956 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) { Branch (4956:13): [True: 0, False: 0]
|
4957 | 0 | LogPrint(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId()); |
4958 | 0 | return; |
4959 | 0 | } |
4960 | | |
4961 | 0 | BlockTransactions resp; |
4962 | 0 | vRecv >> resp; |
4963 | |
|
4964 | 0 | return ProcessCompactBlockTxns(pfrom, *peer, resp); |
4965 | 0 | } |
4966 | | |
4967 | 0 | if (msg_type == NetMsgType::HEADERS) Branch (4967:9): [True: 0, False: 0]
|
4968 | 0 | { |
4969 | | // Ignore headers received while importing |
4970 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) { Branch (4970:13): [True: 0, False: 0]
|
4971 | 0 | LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId()); |
4972 | 0 | return; |
4973 | 0 | } |
4974 | | |
4975 | 0 | std::vector<CBlockHeader> headers; |
4976 | | |
4977 | | // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. |
4978 | 0 | unsigned int nCount = ReadCompactSize(vRecv); |
4979 | 0 | if (nCount > MAX_HEADERS_RESULTS) { Branch (4979:13): [True: 0, False: 0]
|
4980 | 0 | Misbehaving(*peer, strprintf("headers message size = %u", nCount)); |
4981 | 0 | return; |
4982 | 0 | } |
4983 | 0 | headers.resize(nCount); |
4984 | 0 | for (unsigned int n = 0; n < nCount; n++) { Branch (4984:34): [True: 0, False: 0]
|
4985 | 0 | vRecv >> headers[n]; |
4986 | 0 | ReadCompactSize(vRecv); // ignore tx count; assume it is 0. |
4987 | 0 | } |
4988 | |
|
4989 | 0 | ProcessHeadersMessage(pfrom, *peer, std::move(headers), /*via_compact_block=*/false); |
4990 | | |
4991 | | // Check if the headers presync progress needs to be reported to validation. |
4992 | | // This needs to be done without holding the m_headers_presync_mutex lock. |
4993 | 0 | if (m_headers_presync_should_signal.exchange(false)) { Branch (4993:13): [True: 0, False: 0]
|
4994 | 0 | HeadersPresyncStats stats; |
4995 | 0 | { |
4996 | 0 | LOCK(m_headers_presync_mutex); |
4997 | 0 | auto it = m_headers_presync_stats.find(m_headers_presync_bestpeer); |
4998 | 0 | if (it != m_headers_presync_stats.end()) stats = it->second; Branch (4998:21): [True: 0, False: 0]
|
4999 | 0 | } |
5000 | 0 | if (stats.second) { Branch (5000:17): [True: 0, False: 0]
|
5001 | 0 | m_chainman.ReportHeadersPresync(stats.first, stats.second->first, stats.second->second); |
5002 | 0 | } |
5003 | 0 | } |
5004 | |
|
5005 | 0 | return; |
5006 | 0 | } |
5007 | | |
5008 | 0 | if (msg_type == NetMsgType::BLOCK) Branch (5008:9): [True: 0, False: 0]
|
5009 | 0 | { |
5010 | | // Ignore block received while importing |
5011 | 0 | if (m_chainman.m_blockman.LoadingBlocks()) { Branch (5011:13): [True: 0, False: 0]
|
5012 | 0 | LogPrint(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId()); |
5013 | 0 | return; |
5014 | 0 | } |
5015 | | |
5016 | 0 | std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); |
5017 | 0 | vRecv >> TX_WITH_WITNESS(*pblock); |
5018 | |
|
5019 | 0 | LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId()); |
5020 | |
|
5021 | 0 | const CBlockIndex* prev_block{WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock))}; |
5022 | | |
5023 | | // Check for possible mutation if it connects to something we know so we can check for DEPLOYMENT_SEGWIT being active |
5024 | 0 | if (prev_block && IsBlockMutated(/*block=*/*pblock, Branch (5024:13): [True: 0, False: 0]
Branch (5024:27): [True: 0, False: 0]
|
5025 | 0 | /*check_witness_root=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT))) { |
5026 | 0 | LogDebug(BCLog::NET, "Received mutated block from peer=%d\n", peer->m_id); |
5027 | 0 | Misbehaving(*peer, "mutated block"); |
5028 | 0 | WITH_LOCK(cs_main, RemoveBlockRequest(pblock->GetHash(), peer->m_id)); |
5029 | 0 | return; |
5030 | 0 | } |
5031 | | |
5032 | 0 | bool forceProcessing = false; |
5033 | 0 | const uint256 hash(pblock->GetHash()); |
5034 | 0 | bool min_pow_checked = false; |
5035 | 0 | { |
5036 | 0 | LOCK(cs_main); |
5037 | | // Always process the block if we requested it, since we may |
5038 | | // need it even when it's not a candidate for a new best tip. |
5039 | 0 | forceProcessing = IsBlockRequested(hash); |
5040 | 0 | RemoveBlockRequest(hash, pfrom.GetId()); |
5041 | | // mapBlockSource is only used for punishing peers and setting |
5042 | | // which peers send us compact blocks, so the race between here and |
5043 | | // cs_main in ProcessNewBlock is fine. |
5044 | 0 | mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true)); |
5045 | | |
5046 | | // Check claimed work on this block against our anti-dos thresholds. |
5047 | 0 | if (prev_block && prev_block->nChainWork + CalculateClaimedHeadersWork({pblock->GetBlockHeader()}) >= GetAntiDoSWorkThreshold()) { Branch (5047:17): [True: 0, False: 0]
Branch (5047:17): [True: 0, False: 0]
Branch (5047:31): [True: 0, False: 0]
|
5048 | 0 | min_pow_checked = true; |
5049 | 0 | } |
5050 | 0 | } |
5051 | 0 | ProcessBlock(pfrom, pblock, forceProcessing, min_pow_checked); |
5052 | 0 | return; |
5053 | 0 | } |
5054 | | |
5055 | 0 | if (msg_type == NetMsgType::GETADDR) { Branch (5055:9): [True: 0, False: 0]
|
5056 | | // This asymmetric behavior for inbound and outbound connections was introduced |
5057 | | // to prevent a fingerprinting attack: an attacker can send specific fake addresses |
5058 | | // to users' AddrMan and later request them by sending getaddr messages. |
5059 | | // Making nodes which are behind NAT and can only make outgoing connections ignore |
5060 | | // the getaddr message mitigates the attack. |
5061 | 0 | if (!pfrom.IsInboundConn()) { Branch (5061:13): [True: 0, False: 0]
|
5062 | 0 | LogPrint(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId()); |
5063 | 0 | return; |
5064 | 0 | } |
5065 | | |
5066 | | // Since this must be an inbound connection, SetupAddressRelay will |
5067 | | // never fail. |
5068 | 0 | Assume(SetupAddressRelay(pfrom, *peer)); |
5069 | | |
5070 | | // Only send one GetAddr response per connection to reduce resource waste |
5071 | | // and discourage addr stamping of INV announcements. |
5072 | 0 | if (peer->m_getaddr_recvd) { Branch (5072:13): [True: 0, False: 0]
|
5073 | 0 | LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId()); |
5074 | 0 | return; |
5075 | 0 | } |
5076 | 0 | peer->m_getaddr_recvd = true; |
5077 | |
|
5078 | 0 | peer->m_addrs_to_send.clear(); |
5079 | 0 | std::vector<CAddress> vAddr; |
5080 | 0 | if (pfrom.HasPermission(NetPermissionFlags::Addr)) { Branch (5080:13): [True: 0, False: 0]
|
5081 | 0 | vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /*network=*/std::nullopt); |
5082 | 0 | } else { |
5083 | 0 | vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND); |
5084 | 0 | } |
5085 | 0 | for (const CAddress &addr : vAddr) { Branch (5085:35): [True: 0, False: 0]
|
5086 | 0 | PushAddress(*peer, addr); |
5087 | 0 | } |
5088 | 0 | return; |
5089 | 0 | } |
5090 | | |
5091 | 0 | if (msg_type == NetMsgType::MEMPOOL) { Branch (5091:9): [True: 0, False: 0]
|
5092 | | // Only process received mempool messages if we advertise NODE_BLOOM |
5093 | | // or if the peer has mempool permissions. |
5094 | 0 | if (!(peer->m_our_services & NODE_BLOOM) && !pfrom.HasPermission(NetPermissionFlags::Mempool)) Branch (5094:13): [True: 0, False: 0]
Branch (5094:53): [True: 0, False: 0]
|
5095 | 0 | { |
5096 | 0 | if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) Branch (5096:17): [True: 0, False: 0]
|
5097 | 0 | { |
5098 | 0 | LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom.GetId()); |
5099 | 0 | pfrom.fDisconnect = true; |
5100 | 0 | } |
5101 | 0 | return; |
5102 | 0 | } |
5103 | | |
5104 | 0 | if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool)) Branch (5104:13): [True: 0, False: 0]
Branch (5104:55): [True: 0, False: 0]
|
5105 | 0 | { |
5106 | 0 | if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) Branch (5106:17): [True: 0, False: 0]
|
5107 | 0 | { |
5108 | 0 | LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom.GetId()); |
5109 | 0 | pfrom.fDisconnect = true; |
5110 | 0 | } |
5111 | 0 | return; |
5112 | 0 | } |
5113 | | |
5114 | 0 | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { Branch (5114:49): [True: 0, False: 0]
|
5115 | 0 | LOCK(tx_relay->m_tx_inventory_mutex); |
5116 | 0 | tx_relay->m_send_mempool = true; |
5117 | 0 | } |
5118 | 0 | return; |
5119 | 0 | } |
5120 | | |
5121 | 0 | if (msg_type == NetMsgType::PING) { Branch (5121:9): [True: 0, False: 0]
|
5122 | 0 | if (pfrom.GetCommonVersion() > BIP0031_VERSION) { Branch (5122:13): [True: 0, False: 0]
|
5123 | 0 | uint64_t nonce = 0; |
5124 | 0 | vRecv >> nonce; |
5125 | | // Echo the message back with the nonce. This allows for two useful features: |
5126 | | // |
5127 | | // 1) A remote node can quickly check if the connection is operational |
5128 | | // 2) Remote nodes can measure the latency of the network thread. If this node |
5129 | | // is overloaded it won't respond to pings quickly and the remote node can |
5130 | | // avoid sending us more work, like chain download requests. |
5131 | | // |
5132 | | // The nonce stops the remote getting confused between different pings: without |
5133 | | // it, if the remote node sends a ping once per second and this node takes 5 |
5134 | | // seconds to respond to each, the 5th ping the remote sends would appear to |
5135 | | // return very quickly. |
5136 | 0 | MakeAndPushMessage(pfrom, NetMsgType::PONG, nonce); |
5137 | 0 | } |
5138 | 0 | return; |
5139 | 0 | } |
5140 | | |
5141 | 0 | if (msg_type == NetMsgType::PONG) { Branch (5141:9): [True: 0, False: 0]
|
5142 | 0 | const auto ping_end = time_received; |
5143 | 0 | uint64_t nonce = 0; |
5144 | 0 | size_t nAvail = vRecv.in_avail(); |
5145 | 0 | bool bPingFinished = false; |
5146 | 0 | std::string sProblem; |
5147 | |
|
5148 | 0 | if (nAvail >= sizeof(nonce)) { Branch (5148:13): [True: 0, False: 0]
|
5149 | 0 | vRecv >> nonce; |
5150 | | |
5151 | | // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) |
5152 | 0 | if (peer->m_ping_nonce_sent != 0) { Branch (5152:17): [True: 0, False: 0]
|
5153 | 0 | if (nonce == peer->m_ping_nonce_sent) { Branch (5153:21): [True: 0, False: 0]
|
5154 | | // Matching pong received, this ping is no longer outstanding |
5155 | 0 | bPingFinished = true; |
5156 | 0 | const auto ping_time = ping_end - peer->m_ping_start.load(); |
5157 | 0 | if (ping_time.count() >= 0) { Branch (5157:25): [True: 0, False: 0]
|
5158 | | // Let connman know about this successful ping-pong |
5159 | 0 | pfrom.PongReceived(ping_time); |
5160 | 0 | } else { |
5161 | | // This should never happen |
5162 | 0 | sProblem = "Timing mishap"; |
5163 | 0 | } |
5164 | 0 | } else { |
5165 | | // Nonce mismatches are normal when pings are overlapping |
5166 | 0 | sProblem = "Nonce mismatch"; |
5167 | 0 | if (nonce == 0) { Branch (5167:25): [True: 0, False: 0]
|
5168 | | // This is most likely a bug in another implementation somewhere; cancel this ping |
5169 | 0 | bPingFinished = true; |
5170 | 0 | sProblem = "Nonce zero"; |
5171 | 0 | } |
5172 | 0 | } |
5173 | 0 | } else { |
5174 | 0 | sProblem = "Unsolicited pong without ping"; |
5175 | 0 | } |
5176 | 0 | } else { |
5177 | | // This is most likely a bug in another implementation somewhere; cancel this ping |
5178 | 0 | bPingFinished = true; |
5179 | 0 | sProblem = "Short payload"; |
5180 | 0 | } |
5181 | |
|
5182 | 0 | if (!(sProblem.empty())) { Branch (5182:13): [True: 0, False: 0]
|
5183 | 0 | LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n", |
5184 | 0 | pfrom.GetId(), |
5185 | 0 | sProblem, |
5186 | 0 | peer->m_ping_nonce_sent, |
5187 | 0 | nonce, |
5188 | 0 | nAvail); |
5189 | 0 | } |
5190 | 0 | if (bPingFinished) { Branch (5190:13): [True: 0, False: 0]
|
5191 | 0 | peer->m_ping_nonce_sent = 0; |
5192 | 0 | } |
5193 | 0 | return; |
5194 | 0 | } |
5195 | | |
5196 | 0 | if (msg_type == NetMsgType::FILTERLOAD) { Branch (5196:9): [True: 0, False: 0]
|
5197 | 0 | if (!(peer->m_our_services & NODE_BLOOM)) { Branch (5197:13): [True: 0, False: 0]
|
5198 | 0 | LogPrint(BCLog::NET, "filterload received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId()); |
5199 | 0 | pfrom.fDisconnect = true; |
5200 | 0 | return; |
5201 | 0 | } |
5202 | 0 | CBloomFilter filter; |
5203 | 0 | vRecv >> filter; |
5204 | |
|
5205 | 0 | if (!filter.IsWithinSizeConstraints()) Branch (5205:13): [True: 0, False: 0]
|
5206 | 0 | { |
5207 | | // There is no excuse for sending a too-large filter |
5208 | 0 | Misbehaving(*peer, "too-large bloom filter"); |
5209 | 0 | } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { Branch (5209:56): [True: 0, False: 0]
|
5210 | 0 | { |
5211 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); |
5212 | 0 | tx_relay->m_bloom_filter.reset(new CBloomFilter(filter)); |
5213 | 0 | tx_relay->m_relay_txs = true; |
5214 | 0 | } |
5215 | 0 | pfrom.m_bloom_filter_loaded = true; |
5216 | 0 | pfrom.m_relays_txs = true; |
5217 | 0 | } |
5218 | 0 | return; |
5219 | 0 | } |
5220 | | |
5221 | 0 | if (msg_type == NetMsgType::FILTERADD) { Branch (5221:9): [True: 0, False: 0]
|
5222 | 0 | if (!(peer->m_our_services & NODE_BLOOM)) { Branch (5222:13): [True: 0, False: 0]
|
5223 | 0 | LogPrint(BCLog::NET, "filteradd received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId()); |
5224 | 0 | pfrom.fDisconnect = true; |
5225 | 0 | return; |
5226 | 0 | } |
5227 | 0 | std::vector<unsigned char> vData; |
5228 | 0 | vRecv >> vData; |
5229 | | |
5230 | | // Nodes must NEVER send a data item > MAX_SCRIPT_ELEMENT_SIZE bytes (the max size for a script data object, |
5231 | | // and thus, the maximum size any matched object can have) in a filteradd message |
5232 | 0 | bool bad = false; |
5233 | 0 | if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) { Branch (5233:13): [True: 0, False: 0]
|
5234 | 0 | bad = true; |
5235 | 0 | } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { Branch (5235:56): [True: 0, False: 0]
|
5236 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); |
5237 | 0 | if (tx_relay->m_bloom_filter) { Branch (5237:17): [True: 0, False: 0]
|
5238 | 0 | tx_relay->m_bloom_filter->insert(vData); |
5239 | 0 | } else { |
5240 | 0 | bad = true; |
5241 | 0 | } |
5242 | 0 | } |
5243 | 0 | if (bad) { Branch (5243:13): [True: 0, False: 0]
|
5244 | 0 | Misbehaving(*peer, "bad filteradd message"); |
5245 | 0 | } |
5246 | 0 | return; |
5247 | 0 | } |
5248 | | |
5249 | 0 | if (msg_type == NetMsgType::FILTERCLEAR) { Branch (5249:9): [True: 0, False: 0]
|
5250 | 0 | if (!(peer->m_our_services & NODE_BLOOM)) { Branch (5250:13): [True: 0, False: 0]
|
5251 | 0 | LogPrint(BCLog::NET, "filterclear received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId()); |
5252 | 0 | pfrom.fDisconnect = true; |
5253 | 0 | return; |
5254 | 0 | } |
5255 | 0 | auto tx_relay = peer->GetTxRelay(); |
5256 | 0 | if (!tx_relay) return; Branch (5256:13): [True: 0, False: 0]
|
5257 | | |
5258 | 0 | { |
5259 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); |
5260 | 0 | tx_relay->m_bloom_filter = nullptr; |
5261 | 0 | tx_relay->m_relay_txs = true; |
5262 | 0 | } |
5263 | 0 | pfrom.m_bloom_filter_loaded = false; |
5264 | 0 | pfrom.m_relays_txs = true; |
5265 | 0 | return; |
5266 | 0 | } |
5267 | | |
5268 | 0 | if (msg_type == NetMsgType::FEEFILTER) { Branch (5268:9): [True: 0, False: 0]
|
5269 | 0 | CAmount newFeeFilter = 0; |
5270 | 0 | vRecv >> newFeeFilter; |
5271 | 0 | if (MoneyRange(newFeeFilter)) { Branch (5271:13): [True: 0, False: 0]
|
5272 | 0 | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { Branch (5272:53): [True: 0, False: 0]
|
5273 | 0 | tx_relay->m_fee_filter_received = newFeeFilter; |
5274 | 0 | } |
5275 | 0 | LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId()); |
5276 | 0 | } |
5277 | 0 | return; |
5278 | 0 | } |
5279 | | |
5280 | 0 | if (msg_type == NetMsgType::GETCFILTERS) { Branch (5280:9): [True: 0, False: 0]
|
5281 | 0 | ProcessGetCFilters(pfrom, *peer, vRecv); |
5282 | 0 | return; |
5283 | 0 | } |
5284 | | |
5285 | 0 | if (msg_type == NetMsgType::GETCFHEADERS) { Branch (5285:9): [True: 0, False: 0]
|
5286 | 0 | ProcessGetCFHeaders(pfrom, *peer, vRecv); |
5287 | 0 | return; |
5288 | 0 | } |
5289 | | |
5290 | 0 | if (msg_type == NetMsgType::GETCFCHECKPT) { Branch (5290:9): [True: 0, False: 0]
|
5291 | 0 | ProcessGetCFCheckPt(pfrom, *peer, vRecv); |
5292 | 0 | return; |
5293 | 0 | } |
5294 | | |
5295 | 0 | if (msg_type == NetMsgType::NOTFOUND) { Branch (5295:9): [True: 0, False: 0]
|
5296 | 0 | std::vector<CInv> vInv; |
5297 | 0 | vRecv >> vInv; |
5298 | 0 | if (vInv.size() <= MAX_PEER_TX_ANNOUNCEMENTS + MAX_BLOCKS_IN_TRANSIT_PER_PEER) { Branch (5298:13): [True: 0, False: 0]
|
5299 | 0 | LOCK(::cs_main); |
5300 | 0 | for (CInv &inv : vInv) { Branch (5300:28): [True: 0, False: 0]
|
5301 | 0 | if (inv.IsGenTxMsg()) { Branch (5301:21): [True: 0, False: 0]
|
5302 | | // If we receive a NOTFOUND message for a tx we requested, mark the announcement for it as |
5303 | | // completed in TxRequestTracker. |
5304 | 0 | m_txrequest.ReceivedResponse(pfrom.GetId(), inv.hash); |
5305 | 0 | } |
5306 | 0 | } |
5307 | 0 | } |
5308 | 0 | return; |
5309 | 0 | } |
5310 | | |
5311 | | // Ignore unknown commands for extensibility |
5312 | 0 | LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); |
5313 | 0 | return; |
5314 | 0 | } |
5315 | | |
5316 | | bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer) |
5317 | 5.64k | { |
5318 | 5.64k | { |
5319 | 5.64k | LOCK(peer.m_misbehavior_mutex); |
5320 | | |
5321 | | // There's nothing to do if the m_should_discourage flag isn't set |
5322 | 5.64k | if (!peer.m_should_discourage) return false; Branch (5322:13): [True: 5.64k, False: 0]
|
5323 | | |
5324 | 0 | peer.m_should_discourage = false; |
5325 | 0 | } // peer.m_misbehavior_mutex |
5326 | | |
5327 | 0 | if (pnode.HasPermission(NetPermissionFlags::NoBan)) { Branch (5327:9): [True: 0, False: 0]
|
5328 | | // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission |
5329 | 0 | LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id); |
5330 | 0 | return false; |
5331 | 0 | } |
5332 | | |
5333 | 0 | if (pnode.IsManualConn()) { Branch (5333:9): [True: 0, False: 0]
|
5334 | | // We never disconnect or discourage manual peers for bad behavior |
5335 | 0 | LogPrintf("Warning: not punishing manually connected peer %d!\n", peer.m_id); |
5336 | 0 | return false; |
5337 | 0 | } |
5338 | | |
5339 | 0 | if (pnode.addr.IsLocal()) { Branch (5339:9): [True: 0, False: 0]
|
5340 | | // We disconnect local peers for bad behavior but don't discourage (since that would discourage |
5341 | | // all peers on the same local address) |
5342 | 0 | LogPrint(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n", |
5343 | 0 | pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id); |
5344 | 0 | pnode.fDisconnect = true; |
5345 | 0 | return true; |
5346 | 0 | } |
5347 | | |
5348 | | // Normal case: Disconnect the peer and discourage all nodes sharing the address |
5349 | 0 | LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id); |
5350 | 0 | if (m_banman) m_banman->Discourage(pnode.addr); Branch (5350:9): [True: 0, False: 0]
|
5351 | 0 | m_connman.DisconnectNode(pnode.addr); |
5352 | 0 | return true; |
5353 | 0 | } |
5354 | | |
5355 | | bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc) |
5356 | 5.64k | { |
5357 | 5.64k | AssertLockHeld(g_msgproc_mutex); |
5358 | | |
5359 | 5.64k | PeerRef peer = GetPeerRef(pfrom->GetId()); |
5360 | 5.64k | if (peer == nullptr) return false; Branch (5360:9): [True: 0, False: 5.64k]
|
5361 | | |
5362 | 5.64k | { |
5363 | 5.64k | LOCK(peer->m_getdata_requests_mutex); |
5364 | 5.64k | if (!peer->m_getdata_requests.empty()) { Branch (5364:13): [True: 0, False: 5.64k]
|
5365 | 0 | ProcessGetData(*pfrom, *peer, interruptMsgProc); |
5366 | 0 | } |
5367 | 5.64k | } |
5368 | | |
5369 | 5.64k | const bool processed_orphan = ProcessOrphanTx(*peer); |
5370 | | |
5371 | 5.64k | if (pfrom->fDisconnect) Branch (5371:9): [True: 0, False: 5.64k]
|
5372 | 0 | return false; |
5373 | | |
5374 | 5.64k | if (processed_orphan) return true; Branch (5374:9): [True: 0, False: 5.64k]
|
5375 | | |
5376 | | // this maintains the order of responses |
5377 | | // and prevents m_getdata_requests to grow unbounded |
5378 | 5.64k | { |
5379 | 5.64k | LOCK(peer->m_getdata_requests_mutex); |
5380 | 5.64k | if (!peer->m_getdata_requests.empty()) return true; Branch (5380:13): [True: 0, False: 5.64k]
|
5381 | 5.64k | } |
5382 | | |
5383 | | // Don't bother if send buffer is too full to respond anyway |
5384 | 5.64k | if (pfrom->fPauseSend) return false; Branch (5384:9): [True: 0, False: 5.64k]
|
5385 | | |
5386 | 5.64k | auto poll_result{pfrom->PollMessage()}; |
5387 | 5.64k | if (!poll_result) { Branch (5387:9): [True: 0, False: 5.64k]
|
5388 | | // No message to process |
5389 | 0 | return false; |
5390 | 0 | } |
5391 | | |
5392 | 5.64k | CNetMessage& msg{poll_result->first}; |
5393 | 5.64k | bool fMoreWork = poll_result->second; |
5394 | | |
5395 | 5.64k | TRACE6(net, inbound_message, |
5396 | 5.64k | pfrom->GetId(), |
5397 | 5.64k | pfrom->m_addr_name.c_str(), |
5398 | 5.64k | pfrom->ConnectionTypeAsString().c_str(), |
5399 | 5.64k | msg.m_type.c_str(), |
5400 | 5.64k | msg.m_recv.size(), |
5401 | 5.64k | msg.m_recv.data() |
5402 | 5.64k | ); |
5403 | | |
5404 | 5.64k | if (m_opts.capture_messages) { Branch (5404:9): [True: 0, False: 5.64k]
|
5405 | 0 | CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true); |
5406 | 0 | } |
5407 | | |
5408 | 5.64k | try { |
5409 | 5.64k | ProcessMessage(*pfrom, msg.m_type, msg.m_recv, msg.m_time, interruptMsgProc); |
5410 | 5.64k | if (interruptMsgProc) return false; Branch (5410:13): [True: 0, False: 5.64k]
|
5411 | 5.64k | { |
5412 | 5.64k | LOCK(peer->m_getdata_requests_mutex); |
5413 | 5.64k | if (!peer->m_getdata_requests.empty()) fMoreWork = true; Branch (5413:17): [True: 0, False: 5.64k]
|
5414 | 5.64k | } |
5415 | | // Does this peer has an orphan ready to reconsider? |
5416 | | // (Note: we may have provided a parent for an orphan provided |
5417 | | // by another peer that was already processed; in that case, |
5418 | | // the extra work may not be noticed, possibly resulting in an |
5419 | | // unnecessary 100ms delay) |
5420 | 5.64k | if (m_orphanage.HaveTxToReconsider(peer->m_id)) fMoreWork = true; Branch (5420:13): [True: 0, False: 5.64k]
|
5421 | 5.64k | } catch (const std::exception& e) { |
5422 | 2.01k | LogPrint(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()); |
5423 | 2.01k | } catch (...) { |
5424 | 0 | LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size); |
5425 | 0 | } |
5426 | | |
5427 | 5.64k | return fMoreWork; |
5428 | 5.64k | } |
5429 | | |
5430 | | void PeerManagerImpl::ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) |
5431 | 141 | { |
5432 | 141 | AssertLockHeld(cs_main); |
5433 | | |
5434 | 141 | CNodeState &state = *State(pto.GetId()); |
5435 | | |
5436 | 141 | if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) { Branch (5436:9): [True: 141, False: 0]
Branch (5436:42): [True: 36, False: 105]
Branch (5436:78): [True: 21, False: 15]
|
5437 | | // This is an outbound peer subject to disconnection if they don't |
5438 | | // announce a block with as much work as the current tip within |
5439 | | // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if |
5440 | | // their chain has more work than ours, we should sync to it, |
5441 | | // unless it's invalid, in which case we should find that out and |
5442 | | // disconnect from them elsewhere). |
5443 | 21 | if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) { Branch (5443:13): [True: 0, False: 21]
Branch (5443:54): [True: 0, False: 0]
|
5444 | | // 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 |
5445 | 0 | if (state.m_chain_sync.m_timeout != 0s) { Branch (5445:17): [True: 0, False: 0]
|
5446 | 0 | state.m_chain_sync.m_timeout = 0s; |
5447 | 0 | state.m_chain_sync.m_work_header = nullptr; |
5448 | 0 | state.m_chain_sync.m_sent_getheaders = false; |
5449 | 0 | } |
5450 | 21 | } else if (state.m_chain_sync.m_timeout == 0s || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) { Branch (5450:20): [True: 21, False: 0]
Branch (5450:20): [True: 21, False: 0]
Branch (5450:59): [True: 0, False: 0]
Branch (5450:106): [True: 0, False: 0]
Branch (5450:147): [True: 0, False: 0]
|
5451 | | // 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 |
5452 | | // AND |
5453 | | // we are noticing this for the first time (m_timeout is 0) |
5454 | | // OR we noticed this at some point within the last CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds and set a timeout |
5455 | | // 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). |
5456 | | // Either way, set a new timeout based on our current tip. |
5457 | 21 | state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT; |
5458 | 21 | state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip(); |
5459 | 21 | state.m_chain_sync.m_sent_getheaders = false; |
5460 | 21 | } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) { Branch (5460:20): [True: 0, False: 0]
Branch (5460:20): [True: 0, False: 0]
Branch (5460:57): [True: 0, False: 0]
|
5461 | | // No evidence yet that our peer has synced to a chain with work equal to that |
5462 | | // of our tip, when we first detected it was behind. Send a single getheaders |
5463 | | // message to give the peer a chance to update us. |
5464 | 0 | if (state.m_chain_sync.m_sent_getheaders) { Branch (5464:17): [True: 0, False: 0]
|
5465 | | // They've run out of time to catch up! |
5466 | 0 | LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>"); |
5467 | 0 | pto.fDisconnect = true; |
5468 | 0 | } else { |
5469 | 0 | assert(state.m_chain_sync.m_work_header); |
5470 | | // Here, we assume that the getheaders message goes out, |
5471 | | // because it'll either go out or be skipped because of a |
5472 | | // getheaders in-flight already, in which case the peer should |
5473 | | // still respond to us with a sufficiently high work chain tip. |
5474 | 0 | MaybeSendGetHeaders(pto, |
5475 | 0 | GetLocator(state.m_chain_sync.m_work_header->pprev), |
5476 | 0 | peer); |
5477 | 0 | LogPrint(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()); |
5478 | 0 | state.m_chain_sync.m_sent_getheaders = true; |
5479 | | // Bump the timeout to allow a response, which could clear the timeout |
5480 | | // (if the response shows the peer has synced), reset the timeout (if |
5481 | | // the peer syncs to the required work but not to our tip), or result |
5482 | | // in disconnect (if we advance to the timeout and pindexBestKnownBlock |
5483 | | // has not sufficiently progressed) |
5484 | 0 | state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME; |
5485 | 0 | } |
5486 | 0 | } |
5487 | 21 | } |
5488 | 141 | } |
5489 | | |
5490 | | void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) |
5491 | 0 | { |
5492 | | // If we have any extra block-relay-only peers, disconnect the youngest unless |
5493 | | // it's given us a block -- in which case, compare with the second-youngest, and |
5494 | | // out of those two, disconnect the peer who least recently gave us a block. |
5495 | | // The youngest block-relay-only peer would be the extra peer we connected |
5496 | | // to temporarily in order to sync our tip; see net.cpp. |
5497 | | // Note that we use higher nodeid as a measure for most recent connection. |
5498 | 0 | if (m_connman.GetExtraBlockRelayCount() > 0) { Branch (5498:9): [True: 0, False: 0]
|
5499 | 0 | std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0}; |
5500 | |
|
5501 | 0 | m_connman.ForEachNode([&](CNode* pnode) { |
5502 | 0 | if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return; Branch (5502:17): [True: 0, False: 0]
Branch (5502:46): [True: 0, False: 0]
|
5503 | 0 | if (pnode->GetId() > youngest_peer.first) { Branch (5503:17): [True: 0, False: 0]
|
5504 | 0 | next_youngest_peer = youngest_peer; |
5505 | 0 | youngest_peer.first = pnode->GetId(); |
5506 | 0 | youngest_peer.second = pnode->m_last_block_time; |
5507 | 0 | } |
5508 | 0 | }); |
5509 | 0 | NodeId to_disconnect = youngest_peer.first; |
5510 | 0 | if (youngest_peer.second > next_youngest_peer.second) { Branch (5510:13): [True: 0, False: 0]
|
5511 | | // Our newest block-relay-only peer gave us a block more recently; |
5512 | | // disconnect our second youngest. |
5513 | 0 | to_disconnect = next_youngest_peer.first; |
5514 | 0 | } |
5515 | 0 | m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
5516 | 0 | AssertLockHeld(::cs_main); |
5517 | | // Make sure we're not getting a block right now, and that |
5518 | | // we've been connected long enough for this eviction to happen |
5519 | | // at all. |
5520 | | // Note that we only request blocks from a peer if we learn of a |
5521 | | // valid headers chain with at least as much work as our tip. |
5522 | 0 | CNodeState *node_state = State(pnode->GetId()); |
5523 | 0 | if (node_state == nullptr || Branch (5523:17): [True: 0, False: 0]
Branch (5523:17): [True: 0, False: 0]
|
5524 | 0 | (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->vBlocksInFlight.empty())) { Branch (5524:18): [True: 0, False: 0]
Branch (5524:70): [True: 0, False: 0]
|
5525 | 0 | pnode->fDisconnect = true; |
5526 | 0 | LogPrint(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n", |
5527 | 0 | pnode->GetId(), count_seconds(pnode->m_last_block_time)); |
5528 | 0 | return true; |
5529 | 0 | } else { |
5530 | 0 | LogPrint(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", |
5531 | 0 | pnode->GetId(), count_seconds(pnode->m_connected), node_state->vBlocksInFlight.size()); |
5532 | 0 | } |
5533 | 0 | return false; |
5534 | 0 | }); |
5535 | 0 | } |
5536 | | |
5537 | | // Check whether we have too many outbound-full-relay peers |
5538 | 0 | if (m_connman.GetExtraFullOutboundCount() > 0) { Branch (5538:9): [True: 0, False: 0]
|
5539 | | // If we have more outbound-full-relay peers than we target, disconnect one. |
5540 | | // Pick the outbound-full-relay peer that least recently announced |
5541 | | // us a new block, with ties broken by choosing the more recent |
5542 | | // connection (higher node id) |
5543 | | // Protect peers from eviction if we don't have another connection |
5544 | | // to their network, counting both outbound-full-relay and manual peers. |
5545 | 0 | NodeId worst_peer = -1; |
5546 | 0 | int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max(); |
5547 | |
|
5548 | 0 | m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_connman.GetNodesMutex()) { |
5549 | 0 | AssertLockHeld(::cs_main); |
5550 | | |
5551 | | // Only consider outbound-full-relay peers that are not already |
5552 | | // marked for disconnection |
5553 | 0 | if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return; Branch (5553:17): [True: 0, False: 0]
Branch (5553:49): [True: 0, False: 0]
|
5554 | 0 | CNodeState *state = State(pnode->GetId()); |
5555 | 0 | if (state == nullptr) return; // shouldn't be possible, but just in case Branch (5555:17): [True: 0, False: 0]
|
5556 | | // Don't evict our protected peers |
5557 | 0 | if (state->m_chain_sync.m_protect) return; Branch (5557:17): [True: 0, False: 0]
|
5558 | | // If this is the only connection on a particular network that is |
5559 | | // OUTBOUND_FULL_RELAY or MANUAL, protect it. |
5560 | 0 | if (!m_connman.MultipleManualOrFullOutboundConns(pnode->addr.GetNetwork())) return; Branch (5560:17): [True: 0, False: 0]
|
5561 | 0 | if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) { Branch (5561:17): [True: 0, False: 0]
Branch (5561:82): [True: 0, False: 0]
Branch (5561:147): [True: 0, False: 0]
|
5562 | 0 | worst_peer = pnode->GetId(); |
5563 | 0 | oldest_block_announcement = state->m_last_block_announcement; |
5564 | 0 | } |
5565 | 0 | }); |
5566 | 0 | if (worst_peer != -1) { Branch (5566:13): [True: 0, False: 0]
|
5567 | 0 | bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { |
5568 | 0 | AssertLockHeld(::cs_main); |
5569 | | |
5570 | | // Only disconnect a peer that has been connected to us for |
5571 | | // some reasonable fraction of our check-frequency, to give |
5572 | | // it time for new information to have arrived. |
5573 | | // Also don't disconnect any peer we're trying to download a |
5574 | | // block from. |
5575 | 0 | CNodeState &state = *State(pnode->GetId()); |
5576 | 0 | if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.vBlocksInFlight.empty()) { Branch (5576:21): [True: 0, False: 0]
Branch (5576:21): [True: 0, False: 0]
Branch (5576:72): [True: 0, False: 0]
|
5577 | 0 | LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement); |
5578 | 0 | pnode->fDisconnect = true; |
5579 | 0 | return true; |
5580 | 0 | } else { |
5581 | 0 | LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", |
5582 | 0 | pnode->GetId(), count_seconds(pnode->m_connected), state.vBlocksInFlight.size()); |
5583 | 0 | return false; |
5584 | 0 | } |
5585 | 0 | }); |
5586 | 0 | if (disconnected) { Branch (5586:17): [True: 0, False: 0]
|
5587 | | // If we disconnected an extra peer, that means we successfully |
5588 | | // connected to at least one peer after the last time we |
5589 | | // detected a stale tip. Don't try any more extra peers until |
5590 | | // we next detect a stale tip, to limit the load we put on the |
5591 | | // network from these extra connections. |
5592 | 0 | m_connman.SetTryNewOutboundPeer(false); |
5593 | 0 | } |
5594 | 0 | } |
5595 | 0 | } |
5596 | 0 | } |
5597 | | |
5598 | | void PeerManagerImpl::CheckForStaleTipAndEvictPeers() |
5599 | 0 | { |
5600 | 0 | LOCK(cs_main); |
5601 | |
|
5602 | 0 | auto now{GetTime<std::chrono::seconds>()}; |
5603 | |
|
5604 | 0 | EvictExtraOutboundPeers(now); |
5605 | |
|
5606 | 0 | if (now > m_stale_tip_check_time) { Branch (5606:9): [True: 0, False: 0]
|
5607 | | // Check whether our tip is stale, and if so, allow using an extra |
5608 | | // outbound peer |
5609 | 0 | if (!m_chainman.m_blockman.LoadingBlocks() && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) { Branch (5609:13): [True: 0, False: 0]
Branch (5609:55): [True: 0, False: 0]
Branch (5609:87): [True: 0, False: 0]
Branch (5609:124): [True: 0, False: 0]
|
5610 | 0 | LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", |
5611 | 0 | count_seconds(now - m_last_tip_update.load())); |
5612 | 0 | m_connman.SetTryNewOutboundPeer(true); |
5613 | 0 | } else if (m_connman.GetTryNewOutboundPeer()) { Branch (5613:20): [True: 0, False: 0]
|
5614 | 0 | m_connman.SetTryNewOutboundPeer(false); |
5615 | 0 | } |
5616 | 0 | m_stale_tip_check_time = now + STALE_CHECK_INTERVAL; |
5617 | 0 | } |
5618 | |
|
5619 | 0 | if (!m_initial_sync_finished && CanDirectFetch()) { Branch (5619:9): [True: 0, False: 0]
Branch (5619:37): [True: 0, False: 0]
|
5620 | 0 | m_connman.StartExtraBlockRelayPeers(); |
5621 | 0 | m_initial_sync_finished = true; |
5622 | 0 | } |
5623 | 0 | } |
5624 | | |
5625 | | void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now) |
5626 | 145 | { |
5627 | 145 | if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) && Branch (5627:9): [True: 144, False: 1]
Branch (5627:9): [True: 0, False: 145]
|
5628 | 145 | peer.m_ping_nonce_sent && Branch (5628:9): [True: 0, False: 144]
|
5629 | 145 | now > peer.m_ping_start.load() + TIMEOUT_INTERVAL) Branch (5629:9): [True: 0, False: 0]
|
5630 | 0 | { |
5631 | | // The ping timeout is using mocktime. To disable the check during |
5632 | | // testing, increase -peertimeout. |
5633 | 0 | LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), peer.m_id); |
5634 | 0 | node_to.fDisconnect = true; |
5635 | 0 | return; |
5636 | 0 | } |
5637 | | |
5638 | 145 | bool pingSend = false; |
5639 | | |
5640 | 145 | if (peer.m_ping_queued) { Branch (5640:9): [True: 0, False: 145]
|
5641 | | // RPC ping request by user |
5642 | 0 | pingSend = true; |
5643 | 0 | } |
5644 | | |
5645 | 145 | if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) { Branch (5645:9): [True: 145, False: 0]
Branch (5645:9): [True: 145, False: 0]
Branch (5645:40): [True: 145, False: 0]
|
5646 | | // Ping automatically sent as a latency probe & keepalive. |
5647 | 145 | pingSend = true; |
5648 | 145 | } |
5649 | | |
5650 | 145 | if (pingSend) { Branch (5650:9): [True: 145, False: 0]
|
5651 | 145 | uint64_t nonce; |
5652 | 145 | do { |
5653 | 145 | nonce = FastRandomContext().rand64(); |
5654 | 145 | } while (nonce == 0); Branch (5654:18): [True: 0, False: 145]
|
5655 | 145 | peer.m_ping_queued = false; |
5656 | 145 | peer.m_ping_start = now; |
5657 | 145 | if (node_to.GetCommonVersion() > BIP0031_VERSION) { Branch (5657:13): [True: 139, False: 6]
|
5658 | 139 | peer.m_ping_nonce_sent = nonce; |
5659 | 139 | MakeAndPushMessage(node_to, NetMsgType::PING, nonce); |
5660 | 139 | } else { |
5661 | | // Peer is too old to support ping command with nonce, pong will never arrive. |
5662 | 6 | peer.m_ping_nonce_sent = 0; |
5663 | 6 | MakeAndPushMessage(node_to, NetMsgType::PING); |
5664 | 6 | } |
5665 | 145 | } |
5666 | 145 | } |
5667 | | |
5668 | | void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) |
5669 | 141 | { |
5670 | | // Nothing to do for non-address-relay peers |
5671 | 141 | if (!peer.m_addr_relay_enabled) return; Branch (5671:9): [True: 50, False: 91]
|
5672 | | |
5673 | 91 | LOCK(peer.m_addr_send_times_mutex); |
5674 | | // Periodically advertise our local address to the peer. |
5675 | 91 | if (fListen && !m_chainman.IsInitialBlockDownload() && Branch (5675:9): [True: 91, False: 0]
Branch (5675:20): [True: 0, False: 91]
|
5676 | 91 | peer.m_next_local_addr_send < current_time) { Branch (5676:9): [True: 0, False: 0]
|
5677 | | // If we've sent before, clear the bloom filter for the peer, so that our |
5678 | | // self-announcement will actually go out. |
5679 | | // This might be unnecessary if the bloom filter has already rolled |
5680 | | // over since our last self-announcement, but there is only a small |
5681 | | // bandwidth cost that we can incur by doing this (which happens |
5682 | | // once a day on average). |
5683 | 0 | if (peer.m_next_local_addr_send != 0us) { Branch (5683:13): [True: 0, False: 0]
|
5684 | 0 | peer.m_addr_known->reset(); |
5685 | 0 | } |
5686 | 0 | if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) { Branch (5686:37): [True: 0, False: 0]
|
5687 | 0 | CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()}; |
5688 | 0 | PushAddress(peer, local_addr); |
5689 | 0 | } |
5690 | 0 | peer.m_next_local_addr_send = current_time + m_rng.rand_exp_duration(AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL); |
5691 | 0 | } |
5692 | | |
5693 | | // We sent an `addr` message to this peer recently. Nothing more to do. |
5694 | 91 | if (current_time <= peer.m_next_addr_send) return; Branch (5694:9): [True: 0, False: 91]
|
5695 | | |
5696 | 91 | peer.m_next_addr_send = current_time + m_rng.rand_exp_duration(AVG_ADDRESS_BROADCAST_INTERVAL); |
5697 | | |
5698 | 91 | if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) { Branch (5698:9): [True: 0, False: 91]
|
5699 | | // Should be impossible since we always check size before adding to |
5700 | | // m_addrs_to_send. Recover by trimming the vector. |
5701 | 0 | peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND); |
5702 | 0 | } |
5703 | | |
5704 | | // Remove addr records that the peer already knows about, and add new |
5705 | | // addrs to the m_addr_known filter on the same pass. |
5706 | 91 | auto addr_already_known = [&peer](const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) { |
5707 | 0 | bool ret = peer.m_addr_known->contains(addr.GetKey()); |
5708 | 0 | if (!ret) peer.m_addr_known->insert(addr.GetKey()); Branch (5708:13): [True: 0, False: 0]
|
5709 | 0 | return ret; |
5710 | 0 | }; |
5711 | 91 | peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known), |
5712 | 91 | peer.m_addrs_to_send.end()); |
5713 | | |
5714 | | // No addr messages to send |
5715 | 91 | if (peer.m_addrs_to_send.empty()) return; Branch (5715:9): [True: 91, False: 0]
|
5716 | | |
5717 | 0 | if (peer.m_wants_addrv2) { Branch (5717:9): [True: 0, False: 0]
|
5718 | 0 | MakeAndPushMessage(node, NetMsgType::ADDRV2, CAddress::V2_NETWORK(peer.m_addrs_to_send)); |
5719 | 0 | } else { |
5720 | 0 | MakeAndPushMessage(node, NetMsgType::ADDR, CAddress::V1_NETWORK(peer.m_addrs_to_send)); |
5721 | 0 | } |
5722 | 0 | peer.m_addrs_to_send.clear(); |
5723 | | |
5724 | | // we only send the big addr message once |
5725 | 0 | if (peer.m_addrs_to_send.capacity() > 40) { Branch (5725:9): [True: 0, False: 0]
|
5726 | 0 | peer.m_addrs_to_send.shrink_to_fit(); |
5727 | 0 | } |
5728 | 0 | } |
5729 | | |
5730 | | void PeerManagerImpl::MaybeSendSendHeaders(CNode& node, Peer& peer) |
5731 | 141 | { |
5732 | | // Delay sending SENDHEADERS (BIP 130) until we're done with an |
5733 | | // initial-headers-sync with this peer. Receiving headers announcements for |
5734 | | // new blocks while trying to sync their headers chain is problematic, |
5735 | | // because of the state tracking done. |
5736 | 141 | if (!peer.m_sent_sendheaders && node.GetCommonVersion() >= SENDHEADERS_VERSION) { Branch (5736:9): [True: 141, False: 0]
Branch (5736:37): [True: 137, False: 4]
|
5737 | 137 | LOCK(cs_main); |
5738 | 137 | CNodeState &state = *State(node.GetId()); |
5739 | 137 | if (state.pindexBestKnownBlock != nullptr && Branch (5739:13): [True: 0, False: 137]
|
5740 | 137 | state.pindexBestKnownBlock->nChainWork > m_chainman.MinimumChainWork()) { Branch (5740:17): [True: 0, False: 0]
|
5741 | | // Tell our peer we prefer to receive headers rather than inv's |
5742 | | // We send this to non-NODE NETWORK peers as well, because even |
5743 | | // non-NODE NETWORK peers can announce blocks (such as pruning |
5744 | | // nodes) |
5745 | 0 | MakeAndPushMessage(node, NetMsgType::SENDHEADERS); |
5746 | 0 | peer.m_sent_sendheaders = true; |
5747 | 0 | } |
5748 | 137 | } |
5749 | 141 | } |
5750 | | |
5751 | | void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time) |
5752 | 141 | { |
5753 | 141 | if (m_opts.ignore_incoming_txs) return; Branch (5753:9): [True: 0, False: 141]
|
5754 | 141 | if (pto.GetCommonVersion() < FEEFILTER_VERSION) return; Branch (5754:9): [True: 4, False: 137]
|
5755 | | // peers with the forcerelay permission should not filter txs to us |
5756 | 137 | if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return; Branch (5756:9): [True: 15, False: 122]
|
5757 | | // Don't send feefilter messages to outbound block-relay-only peers since they should never announce |
5758 | | // transactions to us, regardless of feefilter state. |
5759 | 122 | if (pto.IsBlockOnlyConn()) return; Branch (5759:9): [True: 14, False: 108]
|
5760 | | |
5761 | 108 | CAmount currentFilter = m_mempool.GetMinFee().GetFeePerK(); |
5762 | | |
5763 | 108 | if (m_chainman.IsInitialBlockDownload()) { Branch (5763:9): [True: 108, False: 0]
|
5764 | | // Received tx-inv messages are discarded when the active |
5765 | | // chainstate is in IBD, so tell the peer to not send them. |
5766 | 108 | currentFilter = MAX_MONEY; |
5767 | 108 | } else { |
5768 | 0 | static const CAmount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)}; |
5769 | 0 | if (peer.m_fee_filter_sent == MAX_FILTER) { Branch (5769:13): [True: 0, False: 0]
|
5770 | | // Send the current filter if we sent MAX_FILTER previously |
5771 | | // and made it out of IBD. |
5772 | 0 | peer.m_next_send_feefilter = 0us; |
5773 | 0 | } |
5774 | 0 | } |
5775 | 108 | if (current_time > peer.m_next_send_feefilter) { Branch (5775:9): [True: 108, False: 0]
|
5776 | 108 | CAmount filterToSend = m_fee_filter_rounder.round(currentFilter); |
5777 | | // We always have a fee filter of at least the min relay fee |
5778 | 108 | filterToSend = std::max(filterToSend, m_mempool.m_opts.min_relay_feerate.GetFeePerK()); |
5779 | 108 | if (filterToSend != peer.m_fee_filter_sent) { Branch (5779:13): [True: 108, False: 0]
|
5780 | 108 | MakeAndPushMessage(pto, NetMsgType::FEEFILTER, filterToSend); |
5781 | 108 | peer.m_fee_filter_sent = filterToSend; |
5782 | 108 | } |
5783 | 108 | peer.m_next_send_feefilter = current_time + m_rng.rand_exp_duration(AVG_FEEFILTER_BROADCAST_INTERVAL); |
5784 | 108 | } |
5785 | | // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY |
5786 | | // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY. |
5787 | 0 | else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter && Branch (5787:14): [True: 0, False: 0]
Branch (5787:14): [True: 0, False: 0]
|
5788 | 0 | (currentFilter < 3 * peer.m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_fee_filter_sent / 3)) { Branch (5788:18): [True: 0, False: 0]
Branch (5788:68): [True: 0, False: 0]
|
5789 | 0 | peer.m_next_send_feefilter = current_time + m_rng.randrange<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY); |
5790 | 0 | } |
5791 | 108 | } |
5792 | | |
5793 | | namespace { |
5794 | | class CompareInvMempoolOrder |
5795 | | { |
5796 | | CTxMemPool* mp; |
5797 | | bool m_wtxid_relay; |
5798 | | public: |
5799 | | explicit CompareInvMempoolOrder(CTxMemPool *_mempool, bool use_wtxid) |
5800 | 114 | { |
5801 | 114 | mp = _mempool; |
5802 | 114 | m_wtxid_relay = use_wtxid; |
5803 | 114 | } |
5804 | | |
5805 | | bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b) |
5806 | 0 | { |
5807 | | /* As std::make_heap produces a max-heap, we want the entries with the |
5808 | | * fewest ancestors/highest fee to sort later. */ |
5809 | 0 | return mp->CompareDepthAndScore(*b, *a, m_wtxid_relay); |
5810 | 0 | } |
5811 | | }; |
5812 | | } // namespace |
5813 | | |
5814 | | bool PeerManagerImpl::RejectIncomingTxs(const CNode& peer) const |
5815 | 1.07k | { |
5816 | | // block-relay-only peers may never send txs to us |
5817 | 1.07k | if (peer.IsBlockOnlyConn()) return true; Branch (5817:9): [True: 83, False: 994]
|
5818 | 994 | if (peer.IsFeelerConn()) return true; Branch (5818:9): [True: 128, False: 866]
|
5819 | | // In -blocksonly mode, peers need the 'relay' permission to send txs to us |
5820 | 866 | if (m_opts.ignore_incoming_txs && !peer.HasPermission(NetPermissionFlags::Relay)) return true; Branch (5820:9): [True: 0, False: 866]
Branch (5820:39): [True: 0, False: 0]
|
5821 | 866 | return false; |
5822 | 866 | } |
5823 | | |
5824 | | bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer) |
5825 | 287 | { |
5826 | | // We don't participate in addr relay with outbound block-relay-only |
5827 | | // connections to prevent providing adversaries with the additional |
5828 | | // information of addr traffic to infer the link. |
5829 | 287 | if (node.IsBlockOnlyConn()) return false; Branch (5829:9): [True: 24, False: 263]
|
5830 | | |
5831 | 263 | if (!peer.m_addr_relay_enabled.exchange(true)) { Branch (5831:9): [True: 263, False: 0]
|
5832 | | // During version message processing (non-block-relay-only outbound peers) |
5833 | | // or on first addr-related message we have received (inbound peers), initialize |
5834 | | // m_addr_known. |
5835 | 263 | peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001); |
5836 | 263 | } |
5837 | | |
5838 | 263 | return true; |
5839 | 287 | } |
5840 | | |
5841 | | bool PeerManagerImpl::SendMessages(CNode* pto) |
5842 | 5.64k | { |
5843 | 5.64k | AssertLockHeld(g_msgproc_mutex); |
5844 | | |
5845 | 5.64k | PeerRef peer = GetPeerRef(pto->GetId()); |
5846 | 5.64k | if (!peer) return false; Branch (5846:9): [True: 0, False: 5.64k]
|
5847 | 5.64k | const Consensus::Params& consensusParams = m_chainparams.GetConsensus(); |
5848 | | |
5849 | | // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll |
5850 | | // disconnect misbehaving peers even before the version handshake is complete. |
5851 | 5.64k | if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true; Branch (5851:9): [True: 0, False: 5.64k]
|
5852 | | |
5853 | | // Don't send anything until the version handshake is complete |
5854 | 5.64k | if (!pto->fSuccessfullyConnected || pto->fDisconnect) Branch (5854:9): [True: 5.48k, False: 163]
Branch (5854:41): [True: 14, False: 149]
|
5855 | 5.49k | return true; |
5856 | | |
5857 | 149 | const auto current_time{GetTime<std::chrono::microseconds>()}; |
5858 | | |
5859 | 149 | if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) { Branch (5859:9): [True: 5, False: 144]
Branch (5859:9): [True: 4, False: 145]
Branch (5859:35): [True: 4, False: 1]
|
5860 | 4 | LogPrint(BCLog::NET, "addrfetch connection timeout; disconnecting peer=%d\n", pto->GetId()); |
5861 | 4 | pto->fDisconnect = true; |
5862 | 4 | return true; |
5863 | 4 | } |
5864 | | |
5865 | 145 | MaybeSendPing(*pto, *peer, current_time); |
5866 | | |
5867 | | // MaybeSendPing may have marked peer for disconnection |
5868 | 145 | if (pto->fDisconnect) return true; Branch (5868:9): [True: 4, False: 141]
|
5869 | | |
5870 | 141 | MaybeSendAddr(*pto, *peer, current_time); |
5871 | | |
5872 | 141 | MaybeSendSendHeaders(*pto, *peer); |
5873 | | |
5874 | 141 | { |
5875 | 141 | LOCK(cs_main); |
5876 | | |
5877 | 141 | CNodeState &state = *State(pto->GetId()); |
5878 | | |
5879 | | // Start block sync |
5880 | 141 | if (m_chainman.m_best_header == nullptr) { Branch (5880:13): [True: 0, False: 141]
|
5881 | 0 | m_chainman.m_best_header = m_chainman.ActiveChain().Tip(); |
5882 | 0 | } |
5883 | | |
5884 | | // Determine whether we might try initial headers sync or parallel |
5885 | | // block download from this peer -- this mostly affects behavior while |
5886 | | // in IBD (once out of IBD, we sync from all peers). |
5887 | 141 | bool sync_blocks_and_headers_from_peer = false; |
5888 | 141 | if (state.fPreferredDownload) { Branch (5888:13): [True: 106, False: 35]
|
5889 | 106 | sync_blocks_and_headers_from_peer = true; |
5890 | 106 | } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) { Branch (5890:20): [True: 20, False: 15]
Branch (5890:45): [True: 19, False: 1]
|
5891 | | // Typically this is an inbound peer. If we don't have any outbound |
5892 | | // peers, or if we aren't downloading any blocks from such peers, |
5893 | | // then allow block downloads from this peer, too. |
5894 | | // We prefer downloading blocks from outbound peers to avoid |
5895 | | // putting undue load on (say) some home user who is just making |
5896 | | // outbound connections to the network, but if our only source of |
5897 | | // the latest blocks is from an inbound peer, we have to be sure to |
5898 | | // eventually download it (and not just wait indefinitely for an |
5899 | | // outbound peer to have it). |
5900 | 19 | if (m_num_preferred_download_peers == 0 || mapBlocksInFlight.empty()) { Branch (5900:17): [True: 8, False: 11]
Branch (5900:56): [True: 11, False: 0]
|
5901 | 19 | sync_blocks_and_headers_from_peer = true; |
5902 | 19 | } |
5903 | 19 | } |
5904 | | |
5905 | 141 | if (!state.fSyncStarted && CanServeBlocks(*peer) && !m_chainman.m_blockman.LoadingBlocks()) { Branch (5905:13): [True: 141, False: 0]
Branch (5905:36): [True: 126, False: 15]
Branch (5905:61): [True: 126, False: 0]
|
5906 | | // Only actively request headers from a single peer, unless we're close to today. |
5907 | 126 | if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->Time() > NodeClock::now() - 24h) { Branch (5907:17): [True: 85, False: 41]
Branch (5907:18): [True: 86, False: 40]
Branch (5907:39): [True: 85, False: 1]
Branch (5907:77): [True: 0, False: 41]
|
5908 | 85 | const CBlockIndex* pindexStart = m_chainman.m_best_header; |
5909 | | /* If possible, start at the block preceding the currently |
5910 | | best known header. This ensures that we always get a |
5911 | | non-empty list of headers back as long as the peer |
5912 | | is up-to-date. With a non-empty response, we can initialise |
5913 | | the peer's known best block. This wouldn't be possible |
5914 | | if we requested starting at m_chainman.m_best_header and |
5915 | | got back an empty response. */ |
5916 | 85 | if (pindexStart->pprev) Branch (5916:21): [True: 0, False: 85]
|
5917 | 0 | pindexStart = pindexStart->pprev; |
5918 | 85 | if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) { Branch (5918:21): [True: 85, False: 0]
|
5919 | 85 | LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height); |
5920 | | |
5921 | 85 | state.fSyncStarted = true; |
5922 | 85 | peer->m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE + |
5923 | 85 | ( |
5924 | | // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling |
5925 | | // to maintain precision |
5926 | 85 | std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} * |
5927 | 85 | Ticks<std::chrono::seconds>(NodeClock::now() - m_chainman.m_best_header->Time()) / consensusParams.nPowTargetSpacing |
5928 | 85 | ); |
5929 | 85 | nSyncStarted++; |
5930 | 85 | } |
5931 | 85 | } |
5932 | 126 | } |
5933 | | |
5934 | | // |
5935 | | // Try sending block announcements via headers |
5936 | | // |
5937 | 141 | { |
5938 | | // If we have no more than MAX_BLOCKS_TO_ANNOUNCE in our |
5939 | | // list of block hashes we're relaying, and our peer wants |
5940 | | // headers announcements, then find the first header |
5941 | | // not yet known to our peer but would connect, and send. |
5942 | | // If no header would connect, or if we have too many |
5943 | | // blocks, or if the peer doesn't want headers, just |
5944 | | // add all to the inv queue. |
5945 | 141 | LOCK(peer->m_block_inv_mutex); |
5946 | 141 | std::vector<CBlock> vHeaders; |
5947 | 141 | bool fRevertToInv = ((!peer->m_prefers_headers && Branch (5947:35): [True: 138, False: 3]
|
5948 | 141 | (!state.m_requested_hb_cmpctblocks || peer->m_blocks_for_headers_relay.size() > 1)) || Branch (5948:35): [True: 137, False: 1]
Branch (5948:72): [True: 0, False: 1]
|
5949 | 141 | peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE); Branch (5949:34): [True: 0, False: 4]
|
5950 | 141 | const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery |
5951 | 141 | ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date |
5952 | | |
5953 | 141 | if (!fRevertToInv) { Branch (5953:17): [True: 4, False: 137]
|
5954 | 4 | bool fFoundStartingHeader = false; |
5955 | | // Try to find first header that our peer doesn't have, and |
5956 | | // then send all headers past that one. If we come across any |
5957 | | // headers that aren't on m_chainman.ActiveChain(), give up. |
5958 | 4 | for (const uint256& hash : peer->m_blocks_for_headers_relay) { Branch (5958:42): [True: 0, False: 4]
|
5959 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash); |
5960 | 0 | assert(pindex); |
5961 | 0 | if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) { Branch (5961:25): [True: 0, False: 0]
|
5962 | | // Bail out if we reorged away from this block |
5963 | 0 | fRevertToInv = true; |
5964 | 0 | break; |
5965 | 0 | } |
5966 | 0 | if (pBestIndex != nullptr && pindex->pprev != pBestIndex) { Branch (5966:25): [True: 0, False: 0]
Branch (5966:50): [True: 0, False: 0]
|
5967 | | // This means that the list of blocks to announce don't |
5968 | | // connect to each other. |
5969 | | // This shouldn't really be possible to hit during |
5970 | | // regular operation (because reorgs should take us to |
5971 | | // a chain that has some block not on the prior chain, |
5972 | | // which should be caught by the prior check), but one |
5973 | | // way this could happen is by using invalidateblock / |
5974 | | // reconsiderblock repeatedly on the tip, causing it to |
5975 | | // be added multiple times to m_blocks_for_headers_relay. |
5976 | | // Robustly deal with this rare situation by reverting |
5977 | | // to an inv. |
5978 | 0 | fRevertToInv = true; |
5979 | 0 | break; |
5980 | 0 | } |
5981 | 0 | pBestIndex = pindex; |
5982 | 0 | if (fFoundStartingHeader) { Branch (5982:25): [True: 0, False: 0]
|
5983 | | // add this to the headers message |
5984 | 0 | vHeaders.emplace_back(pindex->GetBlockHeader()); |
5985 | 0 | } else if (PeerHasHeader(&state, pindex)) { Branch (5985:32): [True: 0, False: 0]
|
5986 | 0 | continue; // keep looking for the first new block |
5987 | 0 | } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) { Branch (5987:32): [True: 0, False: 0]
Branch (5987:60): [True: 0, False: 0]
|
5988 | | // Peer doesn't have this header but they do have the prior one. |
5989 | | // Start sending headers. |
5990 | 0 | fFoundStartingHeader = true; |
5991 | 0 | vHeaders.emplace_back(pindex->GetBlockHeader()); |
5992 | 0 | } else { |
5993 | | // Peer doesn't have this header or the prior one -- nothing will |
5994 | | // connect, so bail out. |
5995 | 0 | fRevertToInv = true; |
5996 | 0 | break; |
5997 | 0 | } |
5998 | 0 | } |
5999 | 4 | } |
6000 | 141 | if (!fRevertToInv && !vHeaders.empty()) { Branch (6000:17): [True: 4, False: 137]
Branch (6000:34): [True: 0, False: 4]
|
6001 | 0 | if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) { Branch (6001:21): [True: 0, False: 0]
Branch (6001:45): [True: 0, False: 0]
|
6002 | | // We only send up to 1 block as header-and-ids, as otherwise |
6003 | | // probably means we're doing an initial-ish-sync or they're slow |
6004 | 0 | LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__, |
6005 | 0 | vHeaders.front().GetHash().ToString(), pto->GetId()); |
6006 | |
|
6007 | 0 | std::optional<CSerializedNetMsg> cached_cmpctblock_msg; |
6008 | 0 | { |
6009 | 0 | LOCK(m_most_recent_block_mutex); |
6010 | 0 | if (m_most_recent_block_hash == pBestIndex->GetBlockHash()) { Branch (6010:29): [True: 0, False: 0]
|
6011 | 0 | cached_cmpctblock_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, *m_most_recent_compact_block); |
6012 | 0 | } |
6013 | 0 | } |
6014 | 0 | if (cached_cmpctblock_msg.has_value()) { Branch (6014:25): [True: 0, False: 0]
|
6015 | 0 | PushMessage(*pto, std::move(cached_cmpctblock_msg.value())); |
6016 | 0 | } else { |
6017 | 0 | CBlock block; |
6018 | 0 | const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(block, *pBestIndex)}; |
6019 | 0 | assert(ret); |
6020 | 0 | CBlockHeaderAndShortTxIDs cmpctblock{block, m_rng.rand64()}; |
6021 | 0 | MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK, cmpctblock); |
6022 | 0 | } |
6023 | 0 | state.pindexBestHeaderSent = pBestIndex; |
6024 | 0 | } else if (peer->m_prefers_headers) { Branch (6024:28): [True: 0, False: 0]
|
6025 | 0 | if (vHeaders.size() > 1) { Branch (6025:25): [True: 0, False: 0]
|
6026 | 0 | LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__, |
6027 | 0 | vHeaders.size(), |
6028 | 0 | vHeaders.front().GetHash().ToString(), |
6029 | 0 | vHeaders.back().GetHash().ToString(), pto->GetId()); |
6030 | 0 | } else { |
6031 | 0 | LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__, |
6032 | 0 | vHeaders.front().GetHash().ToString(), pto->GetId()); |
6033 | 0 | } |
6034 | 0 | MakeAndPushMessage(*pto, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders)); |
6035 | 0 | state.pindexBestHeaderSent = pBestIndex; |
6036 | 0 | } else |
6037 | 0 | fRevertToInv = true; |
6038 | 0 | } |
6039 | 141 | if (fRevertToInv) { Branch (6039:17): [True: 137, False: 4]
|
6040 | | // If falling back to using an inv, just try to inv the tip. |
6041 | | // The last entry in m_blocks_for_headers_relay was our tip at some point |
6042 | | // in the past. |
6043 | 137 | if (!peer->m_blocks_for_headers_relay.empty()) { Branch (6043:21): [True: 0, False: 137]
|
6044 | 0 | const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back(); |
6045 | 0 | const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce); |
6046 | 0 | assert(pindex); |
6047 | | |
6048 | | // Warn if we're announcing a block that is not on the main chain. |
6049 | | // This should be very rare and could be optimized out. |
6050 | | // Just log for now. |
6051 | 0 | if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) { Branch (6051:25): [True: 0, False: 0]
|
6052 | 0 | LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n", |
6053 | 0 | hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString()); |
6054 | 0 | } |
6055 | | |
6056 | | // If the peer's chain has this block, don't inv it back. |
6057 | 0 | if (!PeerHasHeader(&state, pindex)) { Branch (6057:25): [True: 0, False: 0]
|
6058 | 0 | peer->m_blocks_for_inv_relay.push_back(hashToAnnounce); |
6059 | 0 | LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__, |
6060 | 0 | pto->GetId(), hashToAnnounce.ToString()); |
6061 | 0 | } |
6062 | 0 | } |
6063 | 137 | } |
6064 | 141 | peer->m_blocks_for_headers_relay.clear(); |
6065 | 141 | } |
6066 | | |
6067 | | // |
6068 | | // Message: inventory |
6069 | | // |
6070 | 0 | std::vector<CInv> vInv; |
6071 | 141 | { |
6072 | 141 | LOCK(peer->m_block_inv_mutex); |
6073 | 141 | vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_TARGET)); |
6074 | | |
6075 | | // Add blocks |
6076 | 141 | for (const uint256& hash : peer->m_blocks_for_inv_relay) { Branch (6076:38): [True: 0, False: 141]
|
6077 | 0 | vInv.emplace_back(MSG_BLOCK, hash); |
6078 | 0 | if (vInv.size() == MAX_INV_SZ) { Branch (6078:21): [True: 0, False: 0]
|
6079 | 0 | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
6080 | 0 | vInv.clear(); |
6081 | 0 | } |
6082 | 0 | } |
6083 | 141 | peer->m_blocks_for_inv_relay.clear(); |
6084 | 141 | } |
6085 | | |
6086 | 141 | if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { Branch (6086:49): [True: 114, False: 27]
|
6087 | 114 | LOCK(tx_relay->m_tx_inventory_mutex); |
6088 | | // Check whether periodic sends should happen |
6089 | 114 | bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan); |
6090 | 114 | if (tx_relay->m_next_inv_send_time < current_time) { Branch (6090:21): [True: 114, False: 0]
|
6091 | 114 | fSendTrickle = true; |
6092 | 114 | if (pto->IsInboundConn()) { Branch (6092:25): [True: 29, False: 85]
|
6093 | 29 | tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL); |
6094 | 85 | } else { |
6095 | 85 | tx_relay->m_next_inv_send_time = current_time + m_rng.rand_exp_duration(OUTBOUND_INVENTORY_BROADCAST_INTERVAL); |
6096 | 85 | } |
6097 | 114 | } |
6098 | | |
6099 | | // Time to send but the peer has requested we not relay transactions. |
6100 | 114 | if (fSendTrickle) { Branch (6100:21): [True: 114, False: 0]
|
6101 | 114 | LOCK(tx_relay->m_bloom_filter_mutex); |
6102 | 114 | if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear(); Branch (6102:25): [True: 4, False: 110]
|
6103 | 114 | } |
6104 | | |
6105 | | // Respond to BIP35 mempool requests |
6106 | 114 | if (fSendTrickle && tx_relay->m_send_mempool) { Branch (6106:21): [True: 114, False: 0]
Branch (6106:37): [True: 0, False: 114]
|
6107 | 0 | auto vtxinfo = m_mempool.infoAll(); |
6108 | 0 | tx_relay->m_send_mempool = false; |
6109 | 0 | const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()}; |
6110 | |
|
6111 | 0 | LOCK(tx_relay->m_bloom_filter_mutex); |
6112 | |
|
6113 | 0 | for (const auto& txinfo : vtxinfo) { Branch (6113:45): [True: 0, False: 0]
|
6114 | 0 | CInv inv{ |
6115 | 0 | peer->m_wtxid_relay ? MSG_WTX : MSG_TX, Branch (6115:29): [True: 0, False: 0]
|
6116 | 0 | peer->m_wtxid_relay ? Branch (6116:29): [True: 0, False: 0]
|
6117 | 0 | txinfo.tx->GetWitnessHash().ToUint256() : |
6118 | 0 | txinfo.tx->GetHash().ToUint256(), |
6119 | 0 | }; |
6120 | 0 | tx_relay->m_tx_inventory_to_send.erase(inv.hash); |
6121 | | |
6122 | | // Don't send transactions that peers will not put into their mempool |
6123 | 0 | if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) { Branch (6123:29): [True: 0, False: 0]
|
6124 | 0 | continue; |
6125 | 0 | } |
6126 | 0 | if (tx_relay->m_bloom_filter) { Branch (6126:29): [True: 0, False: 0]
|
6127 | 0 | if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue; Branch (6127:33): [True: 0, False: 0]
|
6128 | 0 | } |
6129 | 0 | tx_relay->m_tx_inventory_known_filter.insert(inv.hash); |
6130 | 0 | vInv.push_back(inv); |
6131 | 0 | if (vInv.size() == MAX_INV_SZ) { Branch (6131:29): [True: 0, False: 0]
|
6132 | 0 | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
6133 | 0 | vInv.clear(); |
6134 | 0 | } |
6135 | 0 | } |
6136 | 0 | } |
6137 | | |
6138 | | // Determine transactions to relay |
6139 | 114 | if (fSendTrickle) { Branch (6139:21): [True: 114, False: 0]
|
6140 | | // Produce a vector with all candidates for sending |
6141 | 114 | std::vector<std::set<uint256>::iterator> vInvTx; |
6142 | 114 | vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size()); |
6143 | 114 | for (std::set<uint256>::iterator it = tx_relay->m_tx_inventory_to_send.begin(); it != tx_relay->m_tx_inventory_to_send.end(); it++) { Branch (6143:101): [True: 0, False: 114]
|
6144 | 0 | vInvTx.push_back(it); |
6145 | 0 | } |
6146 | 114 | const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()}; |
6147 | | // Topologically and fee-rate sort the inventory we send for privacy and priority reasons. |
6148 | | // A heap is used so that not all items need sorting if only a few are being sent. |
6149 | 114 | CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, peer->m_wtxid_relay); |
6150 | 114 | std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); |
6151 | | // No reason to drain out at many times the network's capacity, |
6152 | | // especially since we have many peers and some will draw much shorter delays. |
6153 | 114 | unsigned int nRelayedTransactions = 0; |
6154 | 114 | LOCK(tx_relay->m_bloom_filter_mutex); |
6155 | 114 | size_t broadcast_max{INVENTORY_BROADCAST_TARGET + (tx_relay->m_tx_inventory_to_send.size()/1000)*5}; |
6156 | 114 | broadcast_max = std::min<size_t>(INVENTORY_BROADCAST_MAX, broadcast_max); |
6157 | 114 | while (!vInvTx.empty() && nRelayedTransactions < broadcast_max) { Branch (6157:28): [True: 0, False: 114]
Branch (6157:47): [True: 0, False: 0]
|
6158 | | // Fetch the top element from the heap |
6159 | 0 | std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); |
6160 | 0 | std::set<uint256>::iterator it = vInvTx.back(); |
6161 | 0 | vInvTx.pop_back(); |
6162 | 0 | uint256 hash = *it; |
6163 | 0 | CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash); Branch (6163:34): [True: 0, False: 0]
|
6164 | | // Remove it from the to-be-sent set |
6165 | 0 | tx_relay->m_tx_inventory_to_send.erase(it); |
6166 | | // Check if not in the filter already |
6167 | 0 | if (tx_relay->m_tx_inventory_known_filter.contains(hash)) { Branch (6167:29): [True: 0, False: 0]
|
6168 | 0 | continue; |
6169 | 0 | } |
6170 | | // Not in the mempool anymore? don't bother sending it. |
6171 | 0 | auto txinfo = m_mempool.info(ToGenTxid(inv)); |
6172 | 0 | if (!txinfo.tx) { Branch (6172:29): [True: 0, False: 0]
|
6173 | 0 | continue; |
6174 | 0 | } |
6175 | | // Peer told you to not send transactions at that feerate? Don't bother sending it. |
6176 | 0 | if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) { Branch (6176:29): [True: 0, False: 0]
|
6177 | 0 | continue; |
6178 | 0 | } |
6179 | 0 | if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue; Branch (6179:29): [True: 0, False: 0]
Branch (6179:57): [True: 0, False: 0]
|
6180 | | // Send |
6181 | 0 | vInv.push_back(inv); |
6182 | 0 | nRelayedTransactions++; |
6183 | 0 | if (vInv.size() == MAX_INV_SZ) { Branch (6183:29): [True: 0, False: 0]
|
6184 | 0 | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
6185 | 0 | vInv.clear(); |
6186 | 0 | } |
6187 | 0 | tx_relay->m_tx_inventory_known_filter.insert(hash); |
6188 | 0 | } |
6189 | | |
6190 | | // Ensure we'll respond to GETDATA requests for anything we've just announced |
6191 | 114 | LOCK(m_mempool.cs); |
6192 | 114 | tx_relay->m_last_inv_sequence = m_mempool.GetSequence(); |
6193 | 114 | } |
6194 | 114 | } |
6195 | 141 | if (!vInv.empty()) Branch (6195:13): [True: 0, False: 141]
|
6196 | 0 | MakeAndPushMessage(*pto, NetMsgType::INV, vInv); |
6197 | | |
6198 | | // Detect whether we're stalling |
6199 | 141 | auto stalling_timeout = m_block_stalling_timeout.load(); |
6200 | 141 | if (state.m_stalling_since.count() && state.m_stalling_since < current_time - stalling_timeout) { Branch (6200:13): [True: 0, False: 141]
Branch (6200:13): [True: 0, False: 141]
Branch (6200:47): [True: 0, False: 0]
|
6201 | | // Stalling only triggers when the block download window cannot move. During normal steady state, |
6202 | | // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection |
6203 | | // should only happen during initial block download. |
6204 | 0 | LogPrintf("Peer=%d%s is stalling block download, disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); |
6205 | 0 | pto->fDisconnect = true; |
6206 | | // Increase timeout for the next peer so that we don't disconnect multiple peers if our own |
6207 | | // bandwidth is insufficient. |
6208 | 0 | const auto new_timeout = std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX); |
6209 | 0 | if (stalling_timeout != new_timeout && m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { Branch (6209:17): [True: 0, False: 0]
Branch (6209:52): [True: 0, False: 0]
|
6210 | 0 | LogPrint(BCLog::NET, "Increased stalling timeout temporarily to %d seconds\n", count_seconds(new_timeout)); |
6211 | 0 | } |
6212 | 0 | return true; |
6213 | 0 | } |
6214 | | // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N) |
6215 | | // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout. |
6216 | | // We compensate for other peers to prevent killing off peers due to our own downstream link |
6217 | | // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes |
6218 | | // to unreasonably increase our timeout. |
6219 | 141 | if (state.vBlocksInFlight.size() > 0) { Branch (6219:13): [True: 0, False: 141]
|
6220 | 0 | QueuedBlock &queuedBlock = state.vBlocksInFlight.front(); |
6221 | 0 | int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1; |
6222 | 0 | if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { Branch (6222:17): [True: 0, False: 0]
|
6223 | 0 | LogPrintf("Timeout downloading block %s from peer=%d%s, disconnecting\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); |
6224 | 0 | pto->fDisconnect = true; |
6225 | 0 | return true; |
6226 | 0 | } |
6227 | 0 | } |
6228 | | // Check for headers sync timeouts |
6229 | 141 | if (state.fSyncStarted && peer->m_headers_sync_timeout < std::chrono::microseconds::max()) { Branch (6229:13): [True: 85, False: 56]
Branch (6229:13): [True: 85, False: 56]
Branch (6229:35): [True: 85, False: 0]
|
6230 | | // Detect whether this is a stalling initial-headers-sync peer |
6231 | 85 | if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) { Branch (6231:17): [True: 85, False: 0]
|
6232 | 85 | if (current_time > peer->m_headers_sync_timeout && nSyncStarted == 1 && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)) { Branch (6232:21): [True: 0, False: 85]
Branch (6232:68): [True: 0, False: 0]
Branch (6232:89): [True: 0, False: 0]
|
6233 | | // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer, |
6234 | | // and we have others we could be using instead. |
6235 | | // Note: If all our peers are inbound, then we won't |
6236 | | // disconnect our sync peer for stalling; we have bigger |
6237 | | // problems if we can't get any outbound peers. |
6238 | 0 | if (!pto->HasPermission(NetPermissionFlags::NoBan)) { Branch (6238:25): [True: 0, False: 0]
|
6239 | 0 | LogPrintf("Timeout downloading headers from peer=%d%s, disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); |
6240 | 0 | pto->fDisconnect = true; |
6241 | 0 | return true; |
6242 | 0 | } else { |
6243 | 0 | LogPrintf("Timeout downloading headers from noban peer=%d%s, not disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); |
6244 | | // Reset the headers sync state so that we have a |
6245 | | // chance to try downloading from a different peer. |
6246 | | // Note: this will also result in at least one more |
6247 | | // getheaders message to be sent to |
6248 | | // this peer (eventually). |
6249 | 0 | state.fSyncStarted = false; |
6250 | 0 | nSyncStarted--; |
6251 | 0 | peer->m_headers_sync_timeout = 0us; |
6252 | 0 | } |
6253 | 0 | } |
6254 | 85 | } else { |
6255 | | // After we've caught up once, reset the timeout so we can't trigger |
6256 | | // disconnect later. |
6257 | 0 | peer->m_headers_sync_timeout = std::chrono::microseconds::max(); |
6258 | 0 | } |
6259 | 85 | } |
6260 | | |
6261 | | // Check that outbound peers have reasonable chains |
6262 | | // GetTime() is used by this anti-DoS logic so we can test this using mocktime |
6263 | 141 | ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>()); |
6264 | | |
6265 | | // |
6266 | | // Message: getdata (blocks) |
6267 | | // |
6268 | 141 | std::vector<CInv> vGetData; |
6269 | 141 | if (CanServeBlocks(*peer) && ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) || !m_chainman.IsInitialBlockDownload()) && state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { Branch (6269:13): [True: 126, False: 15]
Branch (6269:40): [True: 125, False: 1]
Branch (6269:77): [True: 106, False: 19]
Branch (6269:103): [True: 0, False: 20]
Branch (6269:144): [True: 106, False: 0]
|
6270 | 106 | std::vector<const CBlockIndex*> vToDownload; |
6271 | 106 | NodeId staller = -1; |
6272 | 106 | auto get_inflight_budget = [&state]() { |
6273 | 106 | return std::max(0, MAX_BLOCKS_IN_TRANSIT_PER_PEER - static_cast<int>(state.vBlocksInFlight.size())); |
6274 | 106 | }; |
6275 | | |
6276 | | // If a snapshot chainstate is in use, we want to find its next blocks |
6277 | | // before the background chainstate to prioritize getting to network tip. |
6278 | 106 | FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload, staller); |
6279 | 106 | if (m_chainman.BackgroundSyncInProgress() && !IsLimitedPeer(*peer)) { Branch (6279:17): [True: 0, False: 106]
Branch (6279:58): [True: 0, False: 0]
|
6280 | 0 | TryDownloadingHistoricalBlocks( |
6281 | 0 | *peer, |
6282 | 0 | get_inflight_budget(), |
6283 | 0 | vToDownload, m_chainman.GetBackgroundSyncTip(), |
6284 | 0 | Assert(m_chainman.GetSnapshotBaseBlock())); |
6285 | 0 | } |
6286 | 106 | for (const CBlockIndex *pindex : vToDownload) { Branch (6286:44): [True: 0, False: 106]
|
6287 | 0 | uint32_t nFetchFlags = GetFetchFlags(*peer); |
6288 | 0 | vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()); |
6289 | 0 | BlockRequested(pto->GetId(), *pindex); |
6290 | 0 | LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), |
6291 | 0 | pindex->nHeight, pto->GetId()); |
6292 | 0 | } |
6293 | 106 | if (state.vBlocksInFlight.empty() && staller != -1) { Branch (6293:17): [True: 106, False: 0]
Branch (6293:50): [True: 0, False: 106]
|
6294 | 0 | if (State(staller)->m_stalling_since == 0us) { Branch (6294:21): [True: 0, False: 0]
|
6295 | 0 | State(staller)->m_stalling_since = current_time; |
6296 | 0 | LogPrint(BCLog::NET, "Stall started peer=%d\n", staller); |
6297 | 0 | } |
6298 | 0 | } |
6299 | 106 | } |
6300 | | |
6301 | | // |
6302 | | // Message: getdata (transactions) |
6303 | | // |
6304 | 141 | std::vector<std::pair<NodeId, GenTxid>> expired; |
6305 | 141 | auto requestable = m_txrequest.GetRequestable(pto->GetId(), current_time, &expired); |
6306 | 141 | for (const auto& entry : expired) { Branch (6306:32): [True: 0, False: 141]
|
6307 | 0 | LogPrint(BCLog::NET, "timeout of inflight %s %s from peer=%d\n", entry.second.IsWtxid() ? "wtx" : "tx", |
6308 | 0 | entry.second.GetHash().ToString(), entry.first); |
6309 | 0 | } |
6310 | 141 | for (const GenTxid& gtxid : requestable) { Branch (6310:35): [True: 0, False: 141]
|
6311 | | // Exclude m_recent_rejects_reconsiderable: we may be requesting a missing parent |
6312 | | // that was previously rejected for being too low feerate. |
6313 | 0 | if (!AlreadyHaveTx(gtxid, /*include_reconsiderable=*/false)) { Branch (6313:17): [True: 0, False: 0]
|
6314 | 0 | LogPrint(BCLog::NET, "Requesting %s %s peer=%d\n", gtxid.IsWtxid() ? "wtx" : "tx", |
6315 | 0 | gtxid.GetHash().ToString(), pto->GetId()); |
6316 | 0 | vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*peer)), gtxid.GetHash()); Branch (6316:39): [True: 0, False: 0]
|
6317 | 0 | if (vGetData.size() >= MAX_GETDATA_SZ) { Branch (6317:21): [True: 0, False: 0]
|
6318 | 0 | MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData); |
6319 | 0 | vGetData.clear(); |
6320 | 0 | } |
6321 | 0 | m_txrequest.RequestedTx(pto->GetId(), gtxid.GetHash(), current_time + GETDATA_TX_INTERVAL); |
6322 | 0 | } else { |
6323 | | // We have already seen this transaction, no need to download. This is just a belt-and-suspenders, as |
6324 | | // this should already be called whenever a transaction becomes AlreadyHaveTx(). |
6325 | 0 | m_txrequest.ForgetTxHash(gtxid.GetHash()); |
6326 | 0 | } |
6327 | 0 | } |
6328 | | |
6329 | | |
6330 | 141 | if (!vGetData.empty()) Branch (6330:13): [True: 0, False: 141]
|
6331 | 0 | MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData); |
6332 | 141 | } // release cs_main |
6333 | 0 | MaybeSendFeefilter(*pto, *peer, current_time); |
6334 | 141 | return true; |
6335 | 141 | } |