Branch data Line data Source code
# 1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
# 2 : : // Copyright (c) 2009-2021 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 <merkleblock.h>
# 20 : : #include <netbase.h>
# 21 : : #include <netmessagemaker.h>
# 22 : : #include <node/blockstorage.h>
# 23 : : #include <policy/fees.h>
# 24 : : #include <policy/policy.h>
# 25 : : #include <policy/settings.h>
# 26 : : #include <primitives/block.h>
# 27 : : #include <primitives/transaction.h>
# 28 : : #include <random.h>
# 29 : : #include <reverse_iterator.h>
# 30 : : #include <scheduler.h>
# 31 : : #include <streams.h>
# 32 : : #include <sync.h>
# 33 : : #include <timedata.h>
# 34 : : #include <tinyformat.h>
# 35 : : #include <txmempool.h>
# 36 : : #include <txorphanage.h>
# 37 : : #include <txrequest.h>
# 38 : : #include <util/check.h> // For NDEBUG compile time check
# 39 : : #include <util/strencodings.h>
# 40 : : #include <util/system.h>
# 41 : : #include <util/trace.h>
# 42 : : #include <validation.h>
# 43 : :
# 44 : : #include <algorithm>
# 45 : : #include <atomic>
# 46 : : #include <chrono>
# 47 : : #include <future>
# 48 : : #include <memory>
# 49 : : #include <optional>
# 50 : : #include <typeinfo>
# 51 : :
# 52 : : using node::ReadBlockFromDisk;
# 53 : : using node::ReadRawBlockFromDisk;
# 54 : : using node::fImporting;
# 55 : : using node::fPruneMode;
# 56 : : using node::fReindex;
# 57 : :
# 58 : : /** How long to cache transactions in mapRelay for normal relay */
# 59 : : static constexpr auto RELAY_TX_CACHE_TIME = 15min;
# 60 : : /** How long a transaction has to be in the mempool before it can unconditionally be relayed (even when not in mapRelay). */
# 61 : : static constexpr auto UNCONDITIONAL_RELAY_DELAY = 2min;
# 62 : : /** Headers download timeout.
# 63 : : * Timeout = base + per_header * (expected number of headers) */
# 64 : : static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min;
# 65 : : static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;
# 66 : : /** How long to wait for a peer to respond to a getheaders request */
# 67 : : static constexpr auto HEADERS_RESPONSE_TIME{2min};
# 68 : : /** Protect at least this many outbound peers from disconnection due to slow/
# 69 : : * behind headers chain.
# 70 : : */
# 71 : : static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
# 72 : : /** Timeout for (unprotected) outbound peers to sync to our chainwork */
# 73 : : static constexpr auto CHAIN_SYNC_TIMEOUT{20min};
# 74 : : /** How frequently to check for stale tips */
# 75 : : static constexpr auto STALE_CHECK_INTERVAL{10min};
# 76 : : /** How frequently to check for extra outbound peers and disconnect */
# 77 : : static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};
# 78 : : /** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */
# 79 : : static constexpr auto MINIMUM_CONNECT_TIME{30s};
# 80 : : /** SHA256("main address relay")[0:8] */
# 81 : : static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
# 82 : : /// Age after which a stale block will no longer be served if requested as
# 83 : : /// protection against fingerprinting. Set to one month, denominated in seconds.
# 84 : : static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
# 85 : : /// Age after which a block is considered historical for purposes of rate
# 86 : : /// limiting block relay. Set to one week, denominated in seconds.
# 87 : : static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
# 88 : : /** Time between pings automatically sent out for latency probing and keepalive */
# 89 : : static constexpr auto PING_INTERVAL{2min};
# 90 : : /** The maximum number of entries in a locator */
# 91 : : static const unsigned int MAX_LOCATOR_SZ = 101;
# 92 : : /** The maximum number of entries in an 'inv' protocol message */
# 93 : : static const unsigned int MAX_INV_SZ = 50000;
# 94 : : /** Maximum number of in-flight transaction requests from a peer. It is not a hard limit, but the threshold at which
# 95 : : * point the OVERLOADED_PEER_TX_DELAY kicks in. */
# 96 : : static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT = 100;
# 97 : : /** Maximum number of transactions to consider for requesting, per peer. It provides a reasonable DoS limit to
# 98 : : * per-peer memory usage spent on announcements, while covering peers continuously sending INVs at the maximum
# 99 : : * rate (by our own policy, see INVENTORY_BROADCAST_PER_SECOND) for several minutes, while not receiving
# 100 : : * the actual transaction (from any peer) in response to requests for them. */
# 101 : : static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 5000;
# 102 : : /** How long to delay requesting transactions via txids, if we have wtxid-relaying peers */
# 103 : : static constexpr auto TXID_RELAY_DELAY{2s};
# 104 : : /** How long to delay requesting transactions from non-preferred peers */
# 105 : : static constexpr auto NONPREF_PEER_TX_DELAY{2s};
# 106 : : /** How long to delay requesting transactions from overloaded peers (see MAX_PEER_TX_REQUEST_IN_FLIGHT). */
# 107 : : static constexpr auto OVERLOADED_PEER_TX_DELAY{2s};
# 108 : : /** How long to wait before downloading a transaction from an additional peer */
# 109 : : static constexpr auto GETDATA_TX_INTERVAL{60s};
# 110 : : /** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */
# 111 : : static const unsigned int MAX_GETDATA_SZ = 1000;
# 112 : : /** Number of blocks that can be requested at any given time from a single peer. */
# 113 : : static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
# 114 : : /** Time during which a peer must stall block download progress before being disconnected. */
# 115 : : static constexpr auto BLOCK_STALLING_TIMEOUT{2s};
# 116 : : /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
# 117 : : * less than this number, we reached its tip. Changing this value is a protocol upgrade. */
# 118 : : static const unsigned int MAX_HEADERS_RESULTS = 2000;
# 119 : : /** Maximum depth of blocks we're willing to serve as compact blocks to peers
# 120 : : * when requested. For older blocks, a regular BLOCK response will be sent. */
# 121 : : static const int MAX_CMPCTBLOCK_DEPTH = 5;
# 122 : : /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */
# 123 : : static const int MAX_BLOCKTXN_DEPTH = 10;
# 124 : : /** Size of the "block download window": how far ahead of our current height do we fetch?
# 125 : : * Larger windows tolerate larger download speed differences between peer, but increase the potential
# 126 : : * degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably
# 127 : : * want to make this a per-peer adaptive value at some point. */
# 128 : : static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
# 129 : : /** Block download timeout base, expressed in multiples of the block interval (i.e. 10 min) */
# 130 : : static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1;
# 131 : : /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */
# 132 : : static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5;
# 133 : : /** Maximum number of headers to announce when relaying blocks with headers message.*/
# 134 : : static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
# 135 : : /** Maximum number of unconnecting headers announcements before DoS score */
# 136 : : static const int MAX_UNCONNECTING_HEADERS = 10;
# 137 : : /** Minimum blocks required to signal NODE_NETWORK_LIMITED */
# 138 : : static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
# 139 : : /** Average delay between local address broadcasts */
# 140 : : static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h};
# 141 : : /** Average delay between peer address broadcasts */
# 142 : : static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s};
# 143 : : /** Delay between rotating the peers we relay a particular address to */
# 144 : : static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h};
# 145 : : /** Average delay between trickled inventory transmissions for inbound peers.
# 146 : : * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */
# 147 : : static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s};
# 148 : : /** Average delay between trickled inventory transmissions for outbound peers.
# 149 : : * Use a smaller delay as there is less privacy concern for them.
# 150 : : * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */
# 151 : : static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s};
# 152 : : /** Maximum rate of inventory items to send per second.
# 153 : : * Limits the impact of low-fee transaction floods. */
# 154 : : static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7;
# 155 : : /** Maximum number of inventory items to send per transmission. */
# 156 : : static constexpr unsigned int INVENTORY_BROADCAST_MAX = INVENTORY_BROADCAST_PER_SECOND * count_seconds(INBOUND_INVENTORY_BROADCAST_INTERVAL);
# 157 : : /** The number of most recently announced transactions a peer can request. */
# 158 : : static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY = 3500;
# 159 : : /** Verify that INVENTORY_MAX_RECENT_RELAY is enough to cache everything typically
# 160 : : * relayed before unconditional relay from the mempool kicks in. This is only a
# 161 : : * lower bound, and it should be larger to account for higher inv rate to outbound
# 162 : : * peers, and random variations in the broadcast mechanism. */
# 163 : : static_assert(INVENTORY_MAX_RECENT_RELAY >= INVENTORY_BROADCAST_PER_SECOND * UNCONDITIONAL_RELAY_DELAY / std::chrono::seconds{1}, "INVENTORY_RELAY_MAX too low");
# 164 : : /** Average delay between feefilter broadcasts in seconds. */
# 165 : : static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min};
# 166 : : /** Maximum feefilter broadcast delay after significant change. */
# 167 : : static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min};
# 168 : : /** Maximum number of compact filters that may be requested with one getcfilters. See BIP 157. */
# 169 : : static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
# 170 : : /** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */
# 171 : : static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;
# 172 : : /** the maximum percentage of addresses from our addrman to return in response to a getaddr message. */
# 173 : : static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
# 174 : : /** The maximum number of address records permitted in an ADDR message. */
# 175 : : static constexpr size_t MAX_ADDR_TO_SEND{1000};
# 176 : : /** The maximum rate of address records we're willing to process on average. Can be bypassed using
# 177 : : * the NetPermissionFlags::Addr permission. */
# 178 : : static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
# 179 : : /** The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND
# 180 : : * based increments won't go above this, but the MAX_ADDR_TO_SEND increment following GETADDR
# 181 : : * is exempt from this limit). */
# 182 : : static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND};
# 183 : : /** The compactblocks version we support. See BIP 152. */
# 184 : : static constexpr uint64_t CMPCTBLOCKS_VERSION{2};
# 185 : :
# 186 : : // Internal stuff
# 187 : : namespace {
# 188 : : /** Blocks that are in flight, and that are in the queue to be downloaded. */
# 189 : : struct QueuedBlock {
# 190 : : /** BlockIndex. We must have this since we only request blocks when we've already validated the header. */
# 191 : : const CBlockIndex* pindex;
# 192 : : /** Optional, used for CMPCTBLOCK downloads */
# 193 : : std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
# 194 : : };
# 195 : :
# 196 : : /**
# 197 : : * Data structure for an individual peer. This struct is not protected by
# 198 : : * cs_main since it does not contain validation-critical data.
# 199 : : *
# 200 : : * Memory is owned by shared pointers and this object is destructed when
# 201 : : * the refcount drops to zero.
# 202 : : *
# 203 : : * Mutexes inside this struct must not be held when locking m_peer_mutex.
# 204 : : *
# 205 : : * TODO: move most members from CNodeState to this structure.
# 206 : : * TODO: move remaining application-layer data members from CNode to this structure.
# 207 : : */
# 208 : : struct Peer {
# 209 : : /** Same id as the CNode object for this peer */
# 210 : : const NodeId m_id{0};
# 211 : :
# 212 : : /** Services we offered to this peer.
# 213 : : *
# 214 : : * This is supplied by CConnman during peer initialization. It's const
# 215 : : * because there is no protocol defined for renegotiating services
# 216 : : * initially offered to a peer. The set of local services we offer should
# 217 : : * not change after initialization.
# 218 : : *
# 219 : : * An interesting example of this is NODE_NETWORK and initial block
# 220 : : * download: a node which starts up from scratch doesn't have any blocks
# 221 : : * to serve, but still advertises NODE_NETWORK because it will eventually
# 222 : : * fulfill this role after IBD completes. P2P code is written in such a
# 223 : : * way that it can gracefully handle peers who don't make good on their
# 224 : : * service advertisements. */
# 225 : : const ServiceFlags m_our_services;
# 226 : : /** Services this peer offered to us. */
# 227 : : std::atomic<ServiceFlags> m_their_services{NODE_NONE};
# 228 : :
# 229 : : /** Protects misbehavior data members */
# 230 : : Mutex m_misbehavior_mutex;
# 231 : : /** Accumulated misbehavior score for this peer */
# 232 : : int m_misbehavior_score GUARDED_BY(m_misbehavior_mutex){0};
# 233 : : /** Whether this peer should be disconnected and marked as discouraged (unless it has NetPermissionFlags::NoBan permission). */
# 234 : : bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false};
# 235 : :
# 236 : : /** Protects block inventory data members */
# 237 : : Mutex m_block_inv_mutex;
# 238 : : /** List of blocks that we'll announce via an `inv` message.
# 239 : : * There is no final sorting before sending, as they are always sent
# 240 : : * immediately and in the order requested. */
# 241 : : std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex);
# 242 : : /** Unfiltered list of blocks that we'd like to announce via a `headers`
# 243 : : * message. If we can't announce via a `headers` message, we'll fall back to
# 244 : : * announcing via `inv`. */
# 245 : : std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex);
# 246 : : /** The final block hash that we sent in an `inv` message to this peer.
# 247 : : * When the peer requests this block, we send an `inv` message to trigger
# 248 : : * the peer to request the next sequence of block hashes.
# 249 : : * Most peers use headers-first syncing, which doesn't use this mechanism */
# 250 : : uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {};
# 251 : :
# 252 : : /** This peer's reported block height when we connected */
# 253 : : std::atomic<int> m_starting_height{-1};
# 254 : :
# 255 : : /** The pong reply we're expecting, or 0 if no pong expected. */
# 256 : : std::atomic<uint64_t> m_ping_nonce_sent{0};
# 257 : : /** When the last ping was sent, or 0 if no ping was ever sent */
# 258 : : std::atomic<std::chrono::microseconds> m_ping_start{0us};
# 259 : : /** Whether a ping has been requested by the user */
# 260 : : std::atomic<bool> m_ping_queued{false};
# 261 : :
# 262 : : /** Whether this peer relays txs via wtxid */
# 263 : : std::atomic<bool> m_wtxid_relay{false};
# 264 : : /** The feerate in the most recent BIP133 `feefilter` message sent to the peer.
# 265 : : * It is *not* a p2p protocol violation for the peer to send us
# 266 : : * transactions with a lower fee rate than this. See BIP133. */
# 267 : : CAmount m_fee_filter_sent{0};
# 268 : : /** Timestamp after which we will send the next BIP133 `feefilter` message
# 269 : : * to the peer. */
# 270 : : std::chrono::microseconds m_next_send_feefilter{0};
# 271 : :
# 272 : : struct TxRelay {
# 273 : : mutable RecursiveMutex m_bloom_filter_mutex;
# 274 : : /** Whether the peer wishes to receive transaction announcements.
# 275 : : *
# 276 : : * This is initially set based on the fRelay flag in the received
# 277 : : * `version` message. If initially set to false, it can only be flipped
# 278 : : * to true if we have offered the peer NODE_BLOOM services and it sends
# 279 : : * us a `filterload` or `filterclear` message. See BIP37. */
# 280 : : bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false};
# 281 : : /** A bloom filter for which transactions to announce to the peer. See BIP37. */
# 282 : : std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr};
# 283 : :
# 284 : : mutable RecursiveMutex m_tx_inventory_mutex;
# 285 : : /** A filter of all the txids and wtxids that the peer has announced to
# 286 : : * us or we have announced to the peer. We use this to avoid announcing
# 287 : : * the same txid/wtxid to a peer that already has the transaction. */
# 288 : : CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
# 289 : : /** Set of transaction ids we still have to announce (txid for
# 290 : : * non-wtxid-relay peers, wtxid for wtxid-relay peers). We use the
# 291 : : * mempool to sort transactions in dependency order before relay, so
# 292 : : * this does not have to be sorted. */
# 293 : : std::set<uint256> m_tx_inventory_to_send;
# 294 : : /** Whether the peer has requested us to send our complete mempool. Only
# 295 : : * permitted if the peer has NetPermissionFlags::Mempool. See BIP35. */
# 296 : : bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};
# 297 : : /** The last time a BIP35 `mempool` request was serviced. */
# 298 : : std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
# 299 : : /** The next time after which we will send an `inv` message containing
# 300 : : * transaction announcements to this peer. */
# 301 : : std::chrono::microseconds m_next_inv_send_time{0};
# 302 : :
# 303 : : /** Minimum fee rate with which to filter transaction announcements to this node. See BIP133. */
# 304 : : std::atomic<CAmount> m_fee_filter_received{0};
# 305 : : };
# 306 : :
# 307 : : /* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */
# 308 : : TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
# 309 : 1142 : {
# 310 : 1142 : LOCK(m_tx_relay_mutex);
# 311 : 1142 : Assume(!m_tx_relay);
# 312 : 1142 : m_tx_relay = std::make_unique<Peer::TxRelay>();
# 313 : 1142 : return m_tx_relay.get();
# 314 : 1142 : };
# 315 : :
# 316 : : TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
# 317 : 482494 : {
# 318 : 482494 : return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get());
# 319 : 482494 : };
# 320 : :
# 321 : : /** A vector of addresses to send to the peer, limited to MAX_ADDR_TO_SEND. */
# 322 : : std::vector<CAddress> m_addrs_to_send;
# 323 : : /** Probabilistic filter to track recent addr messages relayed with this
# 324 : : * peer. Used to avoid relaying redundant addresses to this peer.
# 325 : : *
# 326 : : * We initialize this filter 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 : : * Presence of this filter must correlate with m_addr_relay_enabled.
# 331 : : **/
# 332 : : std::unique_ptr<CRollingBloomFilter> m_addr_known;
# 333 : : /** Whether we are participating in address relay with this connection.
# 334 : : *
# 335 : : * We set this bool to true for outbound peers (other than
# 336 : : * block-relay-only connections), or when an inbound peer sends us an
# 337 : : * address related message (ADDR, ADDRV2, GETADDR).
# 338 : : *
# 339 : : * We use this bool to decide whether a peer is eligible for gossiping
# 340 : : * addr messages. This avoids relaying to peers that are unlikely to
# 341 : : * forward them, effectively blackholing self announcements. Reasons
# 342 : : * peers might support addr relay on the link include that they connected
# 343 : : * to us as a block-relay-only peer or they are a light client.
# 344 : : *
# 345 : : * This field must correlate with whether m_addr_known has been
# 346 : : * initialized.*/
# 347 : : std::atomic_bool m_addr_relay_enabled{false};
# 348 : : /** Whether a getaddr request to this peer is outstanding. */
# 349 : : bool m_getaddr_sent{false};
# 350 : : /** Guards address sending timers. */
# 351 : : mutable Mutex m_addr_send_times_mutex;
# 352 : : /** Time point to send the next ADDR message to this peer. */
# 353 : : std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
# 354 : : /** Time point to possibly re-announce our local address to this peer. */
# 355 : : std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
# 356 : : /** Whether the peer has signaled support for receiving ADDRv2 (BIP155)
# 357 : : * messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */
# 358 : : std::atomic_bool m_wants_addrv2{false};
# 359 : : /** Whether this peer has already sent us a getaddr message. */
# 360 : : bool m_getaddr_recvd{false};
# 361 : : /** Number of addresses that can be processed from this peer. Start at 1 to
# 362 : : * permit self-announcement. */
# 363 : : double m_addr_token_bucket{1.0};
# 364 : : /** When m_addr_token_bucket was last updated */
# 365 : : std::chrono::microseconds m_addr_token_timestamp{GetTime<std::chrono::microseconds>()};
# 366 : : /** Total number of addresses that were dropped due to rate limiting. */
# 367 : : std::atomic<uint64_t> m_addr_rate_limited{0};
# 368 : : /** Total number of addresses that were processed (excludes rate-limited ones). */
# 369 : : std::atomic<uint64_t> m_addr_processed{0};
# 370 : :
# 371 : : /** Set of txids to reconsider once their parent transactions have been accepted **/
# 372 : : std::set<uint256> m_orphan_work_set GUARDED_BY(g_cs_orphans);
# 373 : :
# 374 : : /** Whether we've sent this peer a getheaders in response to an inv prior to initial-headers-sync completing */
# 375 : : bool m_inv_triggered_getheaders_before_sync{false};
# 376 : :
# 377 : : /** Protects m_getdata_requests **/
# 378 : : Mutex m_getdata_requests_mutex;
# 379 : : /** Work queue of items requested by this peer **/
# 380 : : std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);
# 381 : :
# 382 : : /** Time of the last getheaders message to this peer */
# 383 : : NodeClock::time_point m_last_getheaders_timestamp{};
# 384 : :
# 385 : : /** Protects m_headers_sync **/
# 386 : : Mutex m_headers_sync_mutex;
# 387 : : /** Headers-sync state for this peer (eg for initial sync, or syncing large
# 388 : : * reorgs) **/
# 389 : : std::unique_ptr<HeadersSyncState> m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex) GUARDED_BY(m_headers_sync_mutex) {};
# 390 : :
# 391 : : /** Whether we've sent our peer a sendheaders message. **/
# 392 : : std::atomic<bool> m_sent_sendheaders{false};
# 393 : :
# 394 : : explicit Peer(NodeId id, ServiceFlags our_services)
# 395 : : : m_id{id}
# 396 : : , m_our_services{our_services}
# 397 : 1218 : {}
# 398 : :
# 399 : : private:
# 400 : : Mutex m_tx_relay_mutex;
# 401 : :
# 402 : : /** Transaction relay data. Will be a nullptr if we're not relaying
# 403 : : * transactions with this peer (e.g. if it's a block-relay-only peer or
# 404 : : * the peer has sent us fRelay=false with bloom filters disabled). */
# 405 : : std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex);
# 406 : : };
# 407 : :
# 408 : : using PeerRef = std::shared_ptr<Peer>;
# 409 : :
# 410 : : /**
# 411 : : * Maintain validation-specific state about nodes, protected by cs_main, instead
# 412 : : * by CNode's own locks. This simplifies asynchronous operation, where
# 413 : : * processing of incoming data is done after the ProcessMessage call returns,
# 414 : : * and we're no longer holding the node's locks.
# 415 : : */
# 416 : : struct CNodeState {
# 417 : : //! The best known block we know this peer has announced.
# 418 : : const CBlockIndex* pindexBestKnownBlock{nullptr};
# 419 : : //! The hash of the last unknown block this peer has announced.
# 420 : : uint256 hashLastUnknownBlock{};
# 421 : : //! The last full block we both have.
# 422 : : const CBlockIndex* pindexLastCommonBlock{nullptr};
# 423 : : //! The best header we have sent our peer.
# 424 : : const CBlockIndex* pindexBestHeaderSent{nullptr};
# 425 : : //! Length of current-streak of unconnecting headers announcements
# 426 : : int nUnconnectingHeaders{0};
# 427 : : //! Whether we've started headers synchronization with this peer.
# 428 : : bool fSyncStarted{false};
# 429 : : //! When to potentially disconnect peer for stalling headers download
# 430 : : std::chrono::microseconds m_headers_sync_timeout{0us};
# 431 : : //! Since when we're stalling block download progress (in microseconds), or 0.
# 432 : : std::chrono::microseconds m_stalling_since{0us};
# 433 : : std::list<QueuedBlock> vBlocksInFlight;
# 434 : : //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
# 435 : : std::chrono::microseconds m_downloading_since{0us};
# 436 : : int nBlocksInFlight{0};
# 437 : : //! Whether we consider this a preferred download peer.
# 438 : : bool fPreferredDownload{false};
# 439 : : //! Whether this peer wants invs or headers (when possible) for block announcements.
# 440 : : bool fPreferHeaders{false};
# 441 : : /** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */
# 442 : : bool m_requested_hb_cmpctblocks{false};
# 443 : : /** Whether this peer will send us cmpctblocks if we request them. */
# 444 : : bool m_provides_cmpctblocks{false};
# 445 : :
# 446 : : /** State used to enforce CHAIN_SYNC_TIMEOUT and EXTRA_PEER_CHECK_INTERVAL logic.
# 447 : : *
# 448 : : * Both are only in effect for outbound, non-manual, non-protected connections.
# 449 : : * Any peer protected (m_protect = true) is not chosen for eviction. A peer is
# 450 : : * marked as protected if all of these are true:
# 451 : : * - its connection type is IsBlockOnlyConn() == false
# 452 : : * - it gave us a valid connecting header
# 453 : : * - we haven't reached MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT yet
# 454 : : * - its chain tip has at least as much work as ours
# 455 : : *
# 456 : : * CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip,
# 457 : : * set a timeout CHAIN_SYNC_TIMEOUT in the future:
# 458 : : * - If at timeout their best known block now has more work than our tip
# 459 : : * when the timeout was set, then either reset the timeout or clear it
# 460 : : * (after comparing against our current tip's work)
# 461 : : * - If at timeout their best known block still has less work than our
# 462 : : * tip did when the timeout was set, then send a getheaders message,
# 463 : : * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
# 464 : : * If their best known block is still behind when that new timeout is
# 465 : : * reached, disconnect.
# 466 : : *
# 467 : : * EXTRA_PEER_CHECK_INTERVAL: after each interval, if we have too many outbound peers,
# 468 : : * drop the outbound one that least recently announced us a new block.
# 469 : : */
# 470 : : struct ChainSyncTimeoutState {
# 471 : : //! A timeout used for checking whether our peer has sufficiently synced
# 472 : : std::chrono::seconds m_timeout{0s};
# 473 : : //! A header with the work we require on our peer's chain
# 474 : : const CBlockIndex* m_work_header{nullptr};
# 475 : : //! After timeout is reached, set to true after sending getheaders
# 476 : : bool m_sent_getheaders{false};
# 477 : : //! Whether this peer is protected from disconnection due to a bad/slow chain
# 478 : : bool m_protect{false};
# 479 : : };
# 480 : :
# 481 : : ChainSyncTimeoutState m_chain_sync;
# 482 : :
# 483 : : //! Time of last new block announcement
# 484 : : int64_t m_last_block_announcement{0};
# 485 : :
# 486 : : //! Whether this peer is an inbound connection
# 487 : : const bool m_is_inbound;
# 488 : :
# 489 : : //! A rolling bloom filter of all announced tx CInvs to this peer.
# 490 : : CRollingBloomFilter m_recently_announced_invs = CRollingBloomFilter{INVENTORY_MAX_RECENT_RELAY, 0.000001};
# 491 : :
# 492 : 1218 : CNodeState(bool is_inbound) : m_is_inbound(is_inbound) {}
# 493 : : };
# 494 : :
# 495 : : class PeerManagerImpl final : public PeerManager
# 496 : : {
# 497 : : public:
# 498 : : PeerManagerImpl(CConnman& connman, AddrMan& addrman,
# 499 : : BanMan* banman, ChainstateManager& chainman,
# 500 : : CTxMemPool& pool, bool ignore_incoming_txs);
# 501 : :
# 502 : : /** Overridden from CValidationInterface. */
# 503 : : void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override
# 504 : : EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex);
# 505 : : void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override
# 506 : : EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex);
# 507 : : void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
# 508 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 509 : : void BlockChecked(const CBlock& block, const BlockValidationState& state) override
# 510 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 511 : : void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override
# 512 : : EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);
# 513 : :
# 514 : : /** Implement NetEventsInterface */
# 515 : : void InitializeNode(CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 516 : : void FinalizeNode(const CNode& node) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex);
# 517 : : bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override
# 518 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex);
# 519 : : bool SendMessages(CNode* pto) override EXCLUSIVE_LOCKS_REQUIRED(pto->cs_sendProcessing)
# 520 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex);
# 521 : :
# 522 : : /** Implement PeerManager */
# 523 : : void StartScheduledTasks(CScheduler& scheduler) override;
# 524 : : void CheckForStaleTipAndEvictPeers() override;
# 525 : : std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) override
# 526 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 527 : : bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 528 : 79 : bool IgnoresIncomingTxs() override { return m_ignore_incoming_txs; }
# 529 : : void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 530 : : void RelayTransaction(const uint256& txid, const uint256& wtxid) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 531 : 67022 : void SetBestHeight(int height) override { m_best_height = height; };
# 532 : 10 : void UnitTestMisbehaving(NodeId peer_id, int howmuch) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), howmuch, ""); };
# 533 : : void ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
# 534 : : const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override
# 535 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex);
# 536 : : void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override;
# 537 : :
# 538 : : private:
# 539 : : /** Consider evicting an outbound peer based on the amount of time they've been behind our tip */
# 540 : : void ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 541 : :
# 542 : : /** If we have extra outbound peers, try to disconnect the one with the oldest block announcement */
# 543 : : void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 544 : :
# 545 : : /** Retrieve unbroadcast transactions from the mempool and reattempt sending to peers */
# 546 : : void ReattemptInitialBroadcast(CScheduler& scheduler) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 547 : :
# 548 : : /** Get a shared pointer to the Peer object.
# 549 : : * May return an empty shared_ptr if the Peer object can't be found. */
# 550 : : PeerRef GetPeerRef(NodeId id) const EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 551 : :
# 552 : : /** Get a shared pointer to the Peer object and remove it from m_peer_map.
# 553 : : * May return an empty shared_ptr if the Peer object can't be found. */
# 554 : : PeerRef RemovePeer(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 555 : :
# 556 : : /**
# 557 : : * Increment peer's misbehavior score. If the new value >= DISCOURAGEMENT_THRESHOLD, mark the node
# 558 : : * to be discouraged, meaning the peer might be disconnected and added to the discouragement filter.
# 559 : : */
# 560 : : void Misbehaving(Peer& peer, int howmuch, const std::string& message);
# 561 : :
# 562 : : /**
# 563 : : * Potentially mark a node discouraged based on the contents of a BlockValidationState object
# 564 : : *
# 565 : : * @param[in] via_compact_block this bool is passed in because net_processing should
# 566 : : * punish peers differently depending on whether the data was provided in a compact
# 567 : : * block message or not. If the compact block had a valid header, but contained invalid
# 568 : : * txs, the peer should not be punished. See BIP 152.
# 569 : : *
# 570 : : * @return Returns true if the peer was punished (probably disconnected)
# 571 : : */
# 572 : : bool MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
# 573 : : bool via_compact_block, const std::string& message = "")
# 574 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 575 : :
# 576 : : /**
# 577 : : * Potentially disconnect and discourage a node based on the contents of a TxValidationState object
# 578 : : *
# 579 : : * @return Returns true if the peer was punished (probably disconnected)
# 580 : : */
# 581 : : bool MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state, const std::string& message = "")
# 582 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 583 : :
# 584 : : /** Maybe disconnect a peer and discourage future connections from its address.
# 585 : : *
# 586 : : * @param[in] pnode The node to check.
# 587 : : * @param[in] peer The peer object to check.
# 588 : : * @return True if the peer was marked for disconnection in this function
# 589 : : */
# 590 : : bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer);
# 591 : :
# 592 : : void ProcessOrphanTx(std::set<uint256>& orphan_work_set) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_cs_orphans)
# 593 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 594 : : /** Process a single headers message from a peer.
# 595 : : *
# 596 : : * @param[in] pfrom CNode of the peer
# 597 : : * @param[in] peer The peer sending us the headers
# 598 : : * @param[in] headers The headers received. Note that this may be modified within ProcessHeadersMessage.
# 599 : : * @param[in] via_compact_block Whether this header came in via compact block handling.
# 600 : : */
# 601 : : void ProcessHeadersMessage(CNode& pfrom, Peer& peer,
# 602 : : std::vector<CBlockHeader>&& headers,
# 603 : : bool via_compact_block)
# 604 : : EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex);
# 605 : : /** Various helpers for headers processing, invoked by ProcessHeadersMessage() */
# 606 : : /** Return true if headers are continuous and have valid proof-of-work (DoS points assigned on failure) */
# 607 : : bool CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer);
# 608 : : /** Calculate an anti-DoS work threshold for headers chains */
# 609 : : arith_uint256 GetAntiDoSWorkThreshold();
# 610 : : /** Deal with state tracking and headers sync for peers that send the
# 611 : : * occasional non-connecting header (this can happen due to BIP 130 headers
# 612 : : * announcements for blocks interacting with the 2hr (MAX_FUTURE_BLOCK_TIME) rule). */
# 613 : : void HandleFewUnconnectingHeaders(CNode& pfrom, Peer& peer, const std::vector<CBlockHeader>& headers);
# 614 : : /** Return true if the headers connect to each other, false otherwise */
# 615 : : bool CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const;
# 616 : : /** Try to continue a low-work headers sync that has already begun.
# 617 : : * Assumes the caller has already verified the headers connect, and has
# 618 : : * checked that each header satisfies the proof-of-work target included in
# 619 : : * the header.
# 620 : : * @param[in] peer The peer we're syncing with.
# 621 : : * @param[in] pfrom CNode of the peer
# 622 : : * @param[in,out] headers The headers to be processed.
# 623 : : * @return True if the passed in headers were successfully processed
# 624 : : * as the continuation of a low-work headers sync in progress;
# 625 : : * false otherwise.
# 626 : : * If false, the passed in headers will be returned back to
# 627 : : * the caller.
# 628 : : * If true, the returned headers may be empty, indicating
# 629 : : * there is no more work for the caller to do; or the headers
# 630 : : * may be populated with entries that have passed anti-DoS
# 631 : : * checks (and therefore may be validated for block index
# 632 : : * acceptance by the caller).
# 633 : : */
# 634 : : bool IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom,
# 635 : : std::vector<CBlockHeader>& headers)
# 636 : : EXCLUSIVE_LOCKS_REQUIRED(peer.m_headers_sync_mutex, !m_headers_presync_mutex);
# 637 : : /** Check work on a headers chain to be processed, and if insufficient,
# 638 : : * initiate our anti-DoS headers sync mechanism.
# 639 : : *
# 640 : : * @param[in] peer The peer whose headers we're processing.
# 641 : : * @param[in] pfrom CNode of the peer
# 642 : : * @param[in] chain_start_header Where these headers connect in our index.
# 643 : : * @param[in,out] headers The headers to be processed.
# 644 : : *
# 645 : : * @return True if chain was low work and a headers sync was
# 646 : : * initiated (and headers will be empty after calling); false
# 647 : : * otherwise.
# 648 : : */
# 649 : : bool TryLowWorkHeadersSync(Peer& peer, CNode& pfrom,
# 650 : : const CBlockIndex* chain_start_header,
# 651 : : std::vector<CBlockHeader>& headers)
# 652 : : EXCLUSIVE_LOCKS_REQUIRED(!peer.m_headers_sync_mutex, !m_peer_mutex, !m_headers_presync_mutex);
# 653 : :
# 654 : : /** Return true if the given header is an ancestor of
# 655 : : * m_chainman.m_best_header or our current tip */
# 656 : : bool IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 657 : :
# 658 : : /** Request further headers from this peer with a given locator.
# 659 : : * We don't issue a getheaders message if we have a recent one outstanding.
# 660 : : * This returns true if a getheaders is actually sent, and false otherwise.
# 661 : : */
# 662 : : bool MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer);
# 663 : : /** Potentially fetch blocks from this peer upon receipt of a new headers tip */
# 664 : : void HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex* pindexLast);
# 665 : : /** Update peer state based on received headers message */
# 666 : : void UpdatePeerStateForReceivedHeaders(CNode& pfrom, const CBlockIndex *pindexLast, bool received_new_header, bool may_have_more_headers);
# 667 : :
# 668 : : void SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req);
# 669 : :
# 670 : : /** Register with TxRequestTracker that an INV has been received from a
# 671 : : * peer. The announcement parameters are decided in PeerManager and then
# 672 : : * passed to TxRequestTracker. */
# 673 : : void AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
# 674 : : EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
# 675 : :
# 676 : : /** Send a version message to a peer */
# 677 : : void PushNodeVersion(CNode& pnode, const Peer& peer);
# 678 : :
# 679 : : /** Send a ping message every PING_INTERVAL or if requested via RPC. May
# 680 : : * mark the peer to be disconnected if a ping has timed out.
# 681 : : * We use mockable time for ping timeouts, so setmocktime may cause pings
# 682 : : * to time out. */
# 683 : : void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now);
# 684 : :
# 685 : : /** Send `addr` messages on a regular schedule. */
# 686 : : void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time);
# 687 : :
# 688 : : /** Send a single `sendheaders` message, after we have completed headers sync with a peer. */
# 689 : : void MaybeSendSendHeaders(CNode& node, Peer& peer);
# 690 : :
# 691 : : /** Relay (gossip) an address to a few randomly chosen nodes.
# 692 : : *
# 693 : : * @param[in] originator The id of the peer that sent us the address. We don't want to relay it back.
# 694 : : * @param[in] addr Address to relay.
# 695 : : * @param[in] fReachable Whether the address' network is reachable. We relay unreachable
# 696 : : * addresses less.
# 697 : : */
# 698 : : void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
# 699 : :
# 700 : : /** Send `feefilter` message. */
# 701 : : void MaybeSendFeefilter(CNode& node, Peer& peer, std::chrono::microseconds current_time);
# 702 : :
# 703 : : const CChainParams& m_chainparams;
# 704 : : CConnman& m_connman;
# 705 : : AddrMan& m_addrman;
# 706 : : /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
# 707 : : BanMan* const m_banman;
# 708 : : ChainstateManager& m_chainman;
# 709 : : CTxMemPool& m_mempool;
# 710 : : TxRequestTracker m_txrequest GUARDED_BY(::cs_main);
# 711 : :
# 712 : : /** The height of the best chain */
# 713 : : std::atomic<int> m_best_height{-1};
# 714 : :
# 715 : : /** Next time to check for stale tip */
# 716 : : std::chrono::seconds m_stale_tip_check_time{0s};
# 717 : :
# 718 : : /** Whether this node is running in -blocksonly mode */
# 719 : : const bool m_ignore_incoming_txs;
# 720 : :
# 721 : : bool RejectIncomingTxs(const CNode& peer) const;
# 722 : :
# 723 : : /** Whether we've completed initial sync yet, for determining when to turn
# 724 : : * on extra block-relay-only peers. */
# 725 : : bool m_initial_sync_finished{false};
# 726 : :
# 727 : : /** Protects m_peer_map. This mutex must not be locked while holding a lock
# 728 : : * on any of the mutexes inside a Peer object. */
# 729 : : mutable Mutex m_peer_mutex;
# 730 : : /**
# 731 : : * Map of all Peer objects, keyed by peer id. This map is protected
# 732 : : * by the m_peer_mutex. Once a shared pointer reference is
# 733 : : * taken, the lock may be released. Individual fields are protected by
# 734 : : * their own locks.
# 735 : : */
# 736 : : std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex);
# 737 : :
# 738 : : /** Map maintaining per-node state. */
# 739 : : std::map<NodeId, CNodeState> m_node_states GUARDED_BY(cs_main);
# 740 : :
# 741 : : /** Get a pointer to a const CNodeState, used when not mutating the CNodeState object. */
# 742 : : const CNodeState* State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 743 : : /** Get a pointer to a mutable CNodeState. */
# 744 : : CNodeState* State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 745 : :
# 746 : : uint32_t GetFetchFlags(const Peer& peer) const;
# 747 : :
# 748 : : std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us};
# 749 : :
# 750 : : /** Number of nodes with fSyncStarted. */
# 751 : : int nSyncStarted GUARDED_BY(cs_main) = 0;
# 752 : :
# 753 : : /** Hash of the last block we received via INV */
# 754 : : uint256 m_last_block_inv_triggering_headers_sync{};
# 755 : :
# 756 : : /**
# 757 : : * Sources of received blocks, saved to be able punish them when processing
# 758 : : * happens afterwards.
# 759 : : * Set mapBlockSource[hash].second to false if the node should not be
# 760 : : * punished if the block is invalid.
# 761 : : */
# 762 : : std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main);
# 763 : :
# 764 : : /** Number of peers with wtxid relay. */
# 765 : : std::atomic<int> m_wtxid_relay_peers{0};
# 766 : :
# 767 : : /** Number of outbound peers with m_chain_sync.m_protect. */
# 768 : : int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
# 769 : :
# 770 : : /** Number of preferable block download peers. */
# 771 : : int m_num_preferred_download_peers GUARDED_BY(cs_main){0};
# 772 : :
# 773 : : bool AlreadyHaveTx(const GenTxid& gtxid)
# 774 : : EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_recent_confirmed_transactions_mutex);
# 775 : :
# 776 : : /**
# 777 : : * Filter for transactions that were recently rejected by the mempool.
# 778 : : * These are not rerequested until the chain tip changes, at which point
# 779 : : * the entire filter is reset.
# 780 : : *
# 781 : : * Without this filter we'd be re-requesting txs from each of our peers,
# 782 : : * increasing bandwidth consumption considerably. For instance, with 100
# 783 : : * peers, half of which relay a tx we don't accept, that might be a 50x
# 784 : : * bandwidth increase. A flooding attacker attempting to roll-over the
# 785 : : * filter using minimum-sized, 60byte, transactions might manage to send
# 786 : : * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
# 787 : : * two minute window to send invs to us.
# 788 : : *
# 789 : : * Decreasing the false positive rate is fairly cheap, so we pick one in a
# 790 : : * million to make it highly unlikely for users to have issues with this
# 791 : : * filter.
# 792 : : *
# 793 : : * We typically only add wtxids to this filter. For non-segwit
# 794 : : * transactions, the txid == wtxid, so this only prevents us from
# 795 : : * re-downloading non-segwit transactions when communicating with
# 796 : : * non-wtxidrelay peers -- which is important for avoiding malleation
# 797 : : * attacks that could otherwise interfere with transaction relay from
# 798 : : * non-wtxidrelay peers. For communicating with wtxidrelay peers, having
# 799 : : * the reject filter store wtxids is exactly what we want to avoid
# 800 : : * redownload of a rejected transaction.
# 801 : : *
# 802 : : * In cases where we can tell that a segwit transaction will fail
# 803 : : * validation no matter the witness, we may add the txid of such
# 804 : : * transaction to the filter as well. This can be helpful when
# 805 : : * communicating with txid-relay peers or if we were to otherwise fetch a
# 806 : : * transaction via txid (eg in our orphan handling).
# 807 : : *
# 808 : : * Memory used: 1.3 MB
# 809 : : */
# 810 : : CRollingBloomFilter m_recent_rejects GUARDED_BY(::cs_main){120'000, 0.000'001};
# 811 : : uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main);
# 812 : :
# 813 : : /*
# 814 : : * Filter for transactions that have been recently confirmed.
# 815 : : * We use this to avoid requesting transactions that have already been
# 816 : : * confirnmed.
# 817 : : *
# 818 : : * Blocks don't typically have more than 4000 transactions, so this should
# 819 : : * be at least six blocks (~1 hr) worth of transactions that we can store,
# 820 : : * inserting both a txid and wtxid for every observed transaction.
# 821 : : * If the number of transactions appearing in a block goes up, or if we are
# 822 : : * seeing getdata requests more than an hour after initial announcement, we
# 823 : : * can increase this number.
# 824 : : * The false positive rate of 1/1M should come out to less than 1
# 825 : : * transaction per day that would be inadvertently ignored (which is the
# 826 : : * same probability that we have in the reject filter).
# 827 : : */
# 828 : : Mutex m_recent_confirmed_transactions_mutex;
# 829 : : CRollingBloomFilter m_recent_confirmed_transactions GUARDED_BY(m_recent_confirmed_transactions_mutex){48'000, 0.000'001};
# 830 : :
# 831 : : /**
# 832 : : * For sending `inv`s to inbound peers, we use a single (exponentially
# 833 : : * distributed) timer for all peers. If we used a separate timer for each
# 834 : : * peer, a spy node could make multiple inbound connections to us to
# 835 : : * accurately determine when we received the transaction (and potentially
# 836 : : * determine the transaction's origin). */
# 837 : : std::chrono::microseconds NextInvToInbounds(std::chrono::microseconds now,
# 838 : : std::chrono::seconds average_interval);
# 839 : :
# 840 : :
# 841 : : // All of the following cache a recent block, and are protected by m_most_recent_block_mutex
# 842 : : Mutex m_most_recent_block_mutex;
# 843 : : std::shared_ptr<const CBlock> m_most_recent_block GUARDED_BY(m_most_recent_block_mutex);
# 844 : : std::shared_ptr<const CBlockHeaderAndShortTxIDs> m_most_recent_compact_block GUARDED_BY(m_most_recent_block_mutex);
# 845 : : uint256 m_most_recent_block_hash GUARDED_BY(m_most_recent_block_mutex);
# 846 : :
# 847 : : // Data about the low-work headers synchronization, aggregated from all peers' HeadersSyncStates.
# 848 : : /** Mutex guarding the other m_headers_presync_* variables. */
# 849 : : Mutex m_headers_presync_mutex;
# 850 : : /** A type to represent statistics about a peer's low-work headers sync.
# 851 : : *
# 852 : : * - The first field is the total verified amount of work in that synchronization.
# 853 : : * - The second is:
# 854 : : * - nullopt: the sync is in REDOWNLOAD phase (phase 2).
# 855 : : * - {height, timestamp}: the sync has the specified tip height and block timestamp (phase 1).
# 856 : : */
# 857 : : using HeadersPresyncStats = std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>;
# 858 : : /** Statistics for all peers in low-work headers sync. */
# 859 : : std::map<NodeId, HeadersPresyncStats> m_headers_presync_stats GUARDED_BY(m_headers_presync_mutex) {};
# 860 : : /** The peer with the most-work entry in m_headers_presync_stats. */
# 861 : : NodeId m_headers_presync_bestpeer GUARDED_BY(m_headers_presync_mutex) {-1};
# 862 : : /** The m_headers_presync_stats improved, and needs signalling. */
# 863 : : std::atomic_bool m_headers_presync_should_signal{false};
# 864 : :
# 865 : : /** Height of the highest block announced using BIP 152 high-bandwidth mode. */
# 866 : : int m_highest_fast_announce{0};
# 867 : :
# 868 : : /** Have we requested this block from a peer */
# 869 : : bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 870 : :
# 871 : : /** Remove this block from our tracked requested blocks. Called if:
# 872 : : * - the block has been received from a peer
# 873 : : * - the request for the block has timed out
# 874 : : */
# 875 : : void RemoveBlockRequest(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 876 : :
# 877 : : /* Mark a block as in flight
# 878 : : * Returns false, still setting pit, if the block was already in flight from the same peer
# 879 : : * pit will only be valid as long as the same cs_main lock is being held
# 880 : : */
# 881 : : bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 882 : :
# 883 : : bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 884 : :
# 885 : : /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
# 886 : : * at most count entries.
# 887 : : */
# 888 : : void FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 889 : :
# 890 : : std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight GUARDED_BY(cs_main);
# 891 : :
# 892 : : /** When our tip was last updated. */
# 893 : : std::atomic<std::chrono::seconds> m_last_tip_update{0s};
# 894 : :
# 895 : : /** Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). */
# 896 : : CTransactionRef FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now) LOCKS_EXCLUDED(cs_main);
# 897 : :
# 898 : : void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
# 899 : : EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex) LOCKS_EXCLUDED(::cs_main);
# 900 : :
# 901 : : /** Process a new block. Perform any post-processing housekeeping */
# 902 : : void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked);
# 903 : :
# 904 : : /** Relay map (txid or wtxid -> CTransactionRef) */
# 905 : : typedef std::map<uint256, CTransactionRef> MapRelay;
# 906 : : MapRelay mapRelay GUARDED_BY(cs_main);
# 907 : : /** Expiration-time ordered list of (expire time, relay map entry) pairs. */
# 908 : : std::deque<std::pair<std::chrono::microseconds, MapRelay::iterator>> g_relay_expiration GUARDED_BY(cs_main);
# 909 : :
# 910 : : /**
# 911 : : * When a peer sends us a valid block, instruct it to announce blocks to us
# 912 : : * using CMPCTBLOCK if possible by adding its nodeid to the end of
# 913 : : * lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by
# 914 : : * removing the first element if necessary.
# 915 : : */
# 916 : : void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 917 : :
# 918 : : /** Stack of nodes which we have set to announce using compact blocks */
# 919 : : std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
# 920 : :
# 921 : : /** Number of peers from which we're downloading blocks. */
# 922 : : int m_peers_downloading_from GUARDED_BY(cs_main) = 0;
# 923 : :
# 924 : : /** Storage for orphan information */
# 925 : : TxOrphanage m_orphanage;
# 926 : :
# 927 : : void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans);
# 928 : :
# 929 : : /** Orphan/conflicted/etc transactions that are kept for compact block reconstruction.
# 930 : : * The last -blockreconstructionextratxn/DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN of
# 931 : : * these are kept in a ring buffer */
# 932 : : std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_cs_orphans);
# 933 : : /** Offset into vExtraTxnForCompact to insert the next tx */
# 934 : : size_t vExtraTxnForCompactIt GUARDED_BY(g_cs_orphans) = 0;
# 935 : :
# 936 : : /** Check whether the last unknown block a peer advertised is not yet known. */
# 937 : : void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 938 : : /** Update tracking information about which blocks a peer is assumed to have. */
# 939 : : void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 940 : : bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 941 : :
# 942 : : /**
# 943 : : * To prevent fingerprinting attacks, only send blocks/headers outside of
# 944 : : * the active chain if they are no more than a month older (both in time,
# 945 : : * and in best equivalent proof of work) than the best header chain we know
# 946 : : * about and we fully-validated them at some point.
# 947 : : */
# 948 : : bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 949 : : bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 950 : : void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
# 951 : : EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);
# 952 : :
# 953 : : /**
# 954 : : * Validation logic for compact filters request handling.
# 955 : : *
# 956 : : * May disconnect from the peer in the case of a bad request.
# 957 : : *
# 958 : : * @param[in] node The node that we received the request from
# 959 : : * @param[in] peer The peer that we received the request from
# 960 : : * @param[in] filter_type The filter type the request is for. Must be basic filters.
# 961 : : * @param[in] start_height The start height for the request
# 962 : : * @param[in] stop_hash The stop_hash for the request
# 963 : : * @param[in] max_height_diff The maximum number of items permitted to request, as specified in BIP 157
# 964 : : * @param[out] stop_index The CBlockIndex for the stop_hash block, if the request can be serviced.
# 965 : : * @param[out] filter_index The filter index, if the request can be serviced.
# 966 : : * @return True if the request can be serviced.
# 967 : : */
# 968 : : bool PrepareBlockFilterRequest(CNode& node, Peer& peer,
# 969 : : BlockFilterType filter_type, uint32_t start_height,
# 970 : : const uint256& stop_hash, uint32_t max_height_diff,
# 971 : : const CBlockIndex*& stop_index,
# 972 : : BlockFilterIndex*& filter_index);
# 973 : :
# 974 : : /**
# 975 : : * Handle a cfilters request.
# 976 : : *
# 977 : : * May disconnect from the peer in the case of a bad request.
# 978 : : *
# 979 : : * @param[in] node The node that we received the request from
# 980 : : * @param[in] peer The peer that we received the request from
# 981 : : * @param[in] vRecv The raw message received
# 982 : : */
# 983 : : void ProcessGetCFilters(CNode& node, Peer& peer, CDataStream& vRecv);
# 984 : :
# 985 : : /**
# 986 : : * Handle a cfheaders request.
# 987 : : *
# 988 : : * May disconnect from the peer in the case of a bad request.
# 989 : : *
# 990 : : * @param[in] node The node that we received the request from
# 991 : : * @param[in] peer The peer that we received the request from
# 992 : : * @param[in] vRecv The raw message received
# 993 : : */
# 994 : : void ProcessGetCFHeaders(CNode& node, Peer& peer, CDataStream& vRecv);
# 995 : :
# 996 : : /**
# 997 : : * Handle a getcfcheckpt request.
# 998 : : *
# 999 : : * May disconnect from the peer in the case of a bad request.
# 1000 : : *
# 1001 : : * @param[in] node The node that we received the request from
# 1002 : : * @param[in] peer The peer that we received the request from
# 1003 : : * @param[in] vRecv The raw message received
# 1004 : : */
# 1005 : : void ProcessGetCFCheckPt(CNode& node, Peer& peer, CDataStream& vRecv);
# 1006 : :
# 1007 : : /** Checks if address relay is permitted with peer. If needed, initializes
# 1008 : : * the m_addr_known bloom filter and sets m_addr_relay_enabled to true.
# 1009 : : *
# 1010 : : * @return True if address relay is enabled with peer
# 1011 : : * False if address relay is disallowed
# 1012 : : */
# 1013 : : bool SetupAddressRelay(const CNode& node, Peer& peer);
# 1014 : : };
# 1015 : :
# 1016 : : const CNodeState* PeerManagerImpl::State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
# 1017 : 2200324 : {
# 1018 : 2200324 : std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
# 1019 [ + + ]: 2200324 : if (it == m_node_states.end())
# 1020 : 1011 : return nullptr;
# 1021 : 2199313 : return &it->second;
# 1022 : 2200324 : }
# 1023 : :
# 1024 : : CNodeState* PeerManagerImpl::State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
# 1025 : 2183963 : {
# 1026 : 2183963 : return const_cast<CNodeState*>(std::as_const(*this).State(pnode));
# 1027 : 2183963 : }
# 1028 : :
# 1029 : : /**
# 1030 : : * Whether the peer supports the address. For example, a peer that does not
# 1031 : : * implement BIP155 cannot receive Tor v3 addresses because it requires
# 1032 : : * ADDRv2 (BIP155) encoding.
# 1033 : : */
# 1034 : : static bool IsAddrCompatible(const Peer& peer, const CAddress& addr)
# 1035 : 19459 : {
# 1036 [ + + ][ + - ]: 19459 : return peer.m_wants_addrv2 || addr.IsAddrV1Compatible();
# 1037 : 19459 : }
# 1038 : :
# 1039 : : static void AddAddressKnown(Peer& peer, const CAddress& addr)
# 1040 : 1281 : {
# 1041 : 1281 : assert(peer.m_addr_known);
# 1042 : 0 : peer.m_addr_known->insert(addr.GetKey());
# 1043 : 1281 : }
# 1044 : :
# 1045 : : static void PushAddress(Peer& peer, const CAddress& addr, FastRandomContext& insecure_rand)
# 1046 : 18968 : {
# 1047 : : // Known checking here is only to save space from duplicates.
# 1048 : : // Before sending, we'll filter it again for known addresses that were
# 1049 : : // added after addresses were pushed.
# 1050 : 18968 : assert(peer.m_addr_known);
# 1051 [ + - ][ + + ]: 18968 : if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) {
# [ + + ][ + - ]
# 1052 [ - + ]: 18947 : if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) {
# 1053 : 0 : peer.m_addrs_to_send[insecure_rand.randrange(peer.m_addrs_to_send.size())] = addr;
# 1054 : 18947 : } else {
# 1055 : 18947 : peer.m_addrs_to_send.push_back(addr);
# 1056 : 18947 : }
# 1057 : 18947 : }
# 1058 : 18968 : }
# 1059 : :
# 1060 : : static void AddKnownTx(Peer& peer, const uint256& hash)
# 1061 : 47330 : {
# 1062 : 47330 : auto tx_relay = peer.GetTxRelay();
# 1063 [ - + ]: 47330 : if (!tx_relay) return;
# 1064 : :
# 1065 : 47330 : LOCK(tx_relay->m_tx_inventory_mutex);
# 1066 : 47330 : tx_relay->m_tx_inventory_known_filter.insert(hash);
# 1067 : 47330 : }
# 1068 : :
# 1069 : : /** Whether this peer can serve us blocks. */
# 1070 : : static bool CanServeBlocks(const Peer& peer)
# 1071 : 456376 : {
# 1072 : 456376 : return peer.m_their_services & (NODE_NETWORK|NODE_NETWORK_LIMITED);
# 1073 : 456376 : }
# 1074 : :
# 1075 : : /** Whether this peer can only serve limited recent blocks (e.g. because
# 1076 : : * it prunes old blocks) */
# 1077 : : static bool IsLimitedPeer(const Peer& peer)
# 1078 : 338791 : {
# 1079 [ + + ]: 338791 : return (!(peer.m_their_services & NODE_NETWORK) &&
# 1080 [ + - ]: 338791 : (peer.m_their_services & NODE_NETWORK_LIMITED));
# 1081 : 338791 : }
# 1082 : :
# 1083 : : /** Whether this peer can serve us witness data */
# 1084 : : static bool CanServeWitnesses(const Peer& peer)
# 1085 : 616563 : {
# 1086 : 616563 : return peer.m_their_services & NODE_WITNESS;
# 1087 : 616563 : }
# 1088 : :
# 1089 : : std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
# 1090 : : std::chrono::seconds average_interval)
# 1091 : 3134 : {
# 1092 [ + + ]: 3134 : if (m_next_inv_to_inbounds.load() < now) {
# 1093 : : // If this function were called from multiple threads simultaneously
# 1094 : : // it would possible that both update the next send variable, and return a different result to their caller.
# 1095 : : // This is not possible in practice as only the net processing thread invokes this function.
# 1096 : 1404 : m_next_inv_to_inbounds = GetExponentialRand(now, average_interval);
# 1097 : 1404 : }
# 1098 : 3134 : return m_next_inv_to_inbounds;
# 1099 : 3134 : }
# 1100 : :
# 1101 : : bool PeerManagerImpl::IsBlockRequested(const uint256& hash)
# 1102 : 596352 : {
# 1103 : 596352 : return mapBlocksInFlight.find(hash) != mapBlocksInFlight.end();
# 1104 : 596352 : }
# 1105 : :
# 1106 : : void PeerManagerImpl::RemoveBlockRequest(const uint256& hash)
# 1107 : 83002 : {
# 1108 : 83002 : auto it = mapBlocksInFlight.find(hash);
# 1109 [ + + ]: 83002 : if (it == mapBlocksInFlight.end()) {
# 1110 : : // Block was not requested
# 1111 : 41931 : return;
# 1112 : 41931 : }
# 1113 : :
# 1114 : 41071 : auto [node_id, list_it] = it->second;
# 1115 : 41071 : CNodeState *state = State(node_id);
# 1116 : 41071 : assert(state != nullptr);
# 1117 : :
# 1118 [ + + ]: 41071 : if (state->vBlocksInFlight.begin() == list_it) {
# 1119 : : // First block on the queue was received, update the start download time for the next one
# 1120 : 40854 : state->m_downloading_since = std::max(state->m_downloading_since, GetTime<std::chrono::microseconds>());
# 1121 : 40854 : }
# 1122 : 41071 : state->vBlocksInFlight.erase(list_it);
# 1123 : :
# 1124 : 41071 : state->nBlocksInFlight--;
# 1125 [ + + ]: 41071 : if (state->nBlocksInFlight == 0) {
# 1126 : : // Last validated block on the queue was received.
# 1127 : 12518 : m_peers_downloading_from--;
# 1128 : 12518 : }
# 1129 : 41071 : state->m_stalling_since = 0us;
# 1130 : 41071 : mapBlocksInFlight.erase(it);
# 1131 : 41071 : }
# 1132 : :
# 1133 : : bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit)
# 1134 : 41365 : {
# 1135 : 41365 : const uint256& hash{block.GetBlockHash()};
# 1136 : :
# 1137 : 41365 : CNodeState *state = State(nodeid);
# 1138 : 41365 : assert(state != nullptr);
# 1139 : :
# 1140 : : // Short-circuit most stuff in case it is from the same node
# 1141 : 0 : std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
# 1142 [ + + ][ + + ]: 41365 : if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
# [ + - ]
# 1143 [ + - ]: 230 : if (pit) {
# 1144 : 230 : *pit = &itInFlight->second.second;
# 1145 : 230 : }
# 1146 : 230 : return false;
# 1147 : 230 : }
# 1148 : :
# 1149 : : // Make sure it's not listed somewhere already.
# 1150 : 41135 : RemoveBlockRequest(hash);
# 1151 : :
# 1152 : 41135 : std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
# 1153 [ + + ]: 41135 : {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool) : nullptr)});
# 1154 : 41135 : state->nBlocksInFlight++;
# 1155 [ + + ]: 41135 : if (state->nBlocksInFlight == 1) {
# 1156 : : // We're starting a block download (batch) from this peer.
# 1157 : 12537 : state->m_downloading_since = GetTime<std::chrono::microseconds>();
# 1158 : 12537 : m_peers_downloading_from++;
# 1159 : 12537 : }
# 1160 : 41135 : itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
# 1161 [ + + ]: 41135 : if (pit) {
# 1162 : 11061 : *pit = &itInFlight->second.second;
# 1163 : 11061 : }
# 1164 : 41135 : return true;
# 1165 : 41365 : }
# 1166 : :
# 1167 : : void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid)
# 1168 : 13476 : {
# 1169 : 13476 : AssertLockHeld(cs_main);
# 1170 : :
# 1171 : : // When in -blocksonly mode, never request high-bandwidth mode from peers. Our
# 1172 : : // mempool will not contain the transactions necessary to reconstruct the
# 1173 : : // compact block.
# 1174 [ + + ]: 13476 : if (m_ignore_incoming_txs) return;
# 1175 : :
# 1176 : 13475 : CNodeState* nodestate = State(nodeid);
# 1177 [ + + ][ + + ]: 13475 : if (!nodestate || !nodestate->m_provides_cmpctblocks) {
# 1178 : : // Don't request compact blocks if the peer has not signalled support
# 1179 : 1768 : return;
# 1180 : 1768 : }
# 1181 : :
# 1182 : 11707 : int num_outbound_hb_peers = 0;
# 1183 [ + + ]: 12670 : for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
# 1184 [ + + ]: 12381 : if (*it == nodeid) {
# 1185 : 11418 : lNodesAnnouncingHeaderAndIDs.erase(it);
# 1186 : 11418 : lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
# 1187 : 11418 : return;
# 1188 : 11418 : }
# 1189 : 963 : CNodeState *state = State(*it);
# 1190 [ + + ][ + + ]: 963 : if (state != nullptr && !state->m_is_inbound) ++num_outbound_hb_peers;
# 1191 : 963 : }
# 1192 [ + + ]: 289 : if (nodestate->m_is_inbound) {
# 1193 : : // If we're adding an inbound HB peer, make sure we're not removing
# 1194 : : // our last outbound HB peer in the process.
# 1195 [ + + ][ + + ]: 132 : if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 1) {
# 1196 : 3 : CNodeState *remove_node = State(lNodesAnnouncingHeaderAndIDs.front());
# 1197 [ + - ][ + + ]: 3 : if (remove_node != nullptr && !remove_node->m_is_inbound) {
# 1198 : : // Put the HB outbound peer in the second slot, so that it
# 1199 : : // doesn't get removed.
# 1200 : 1 : std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
# 1201 : 1 : }
# 1202 : 3 : }
# 1203 : 132 : }
# 1204 : 289 : m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
# 1205 : 289 : AssertLockHeld(::cs_main);
# 1206 [ + + ]: 289 : if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
# 1207 : : // As per BIP152, we only get 3 of our peers to announce
# 1208 : : // blocks using compact encodings.
# 1209 : 18 : m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this](CNode* pnodeStop){
# 1210 : 4 : m_connman.PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetCommonVersion()).Make(NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION));
# 1211 : : // save BIP152 bandwidth state: we select peer to be low-bandwidth
# 1212 : 4 : pnodeStop->m_bip152_highbandwidth_to = false;
# 1213 : 4 : return true;
# 1214 : 4 : });
# 1215 : 18 : lNodesAnnouncingHeaderAndIDs.pop_front();
# 1216 : 18 : }
# 1217 : 289 : m_connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetCommonVersion()).Make(NetMsgType::SENDCMPCT, /*high_bandwidth=*/true, /*version=*/CMPCTBLOCKS_VERSION));
# 1218 : : // save BIP152 bandwidth state: we select peer to be high-bandwidth
# 1219 : 289 : pfrom->m_bip152_highbandwidth_to = true;
# 1220 : 289 : lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
# 1221 : 289 : return true;
# 1222 : 289 : });
# 1223 : 289 : }
# 1224 : :
# 1225 : : bool PeerManagerImpl::TipMayBeStale()
# 1226 : 6 : {
# 1227 : 6 : AssertLockHeld(cs_main);
# 1228 : 6 : const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
# 1229 [ + + ]: 6 : if (m_last_tip_update.load() == 0s) {
# 1230 : 4 : m_last_tip_update = GetTime<std::chrono::seconds>();
# 1231 : 4 : }
# 1232 [ + + ][ + - ]: 6 : return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty();
# 1233 : 6 : }
# 1234 : :
# 1235 : : bool PeerManagerImpl::CanDirectFetch()
# 1236 : 24462 : {
# 1237 : 24462 : return m_chainman.ActiveChain().Tip()->Time() > GetAdjustedTime() - m_chainparams.GetConsensus().PowTargetSpacing() * 20;
# 1238 : 24462 : }
# 1239 : :
# 1240 : : static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
# 1241 : 103405 : {
# 1242 [ + + ][ + + ]: 103405 : if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
# 1243 : 35207 : return true;
# 1244 [ + + ][ + + ]: 68198 : if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
# 1245 : 33696 : return true;
# 1246 : 34502 : return false;
# 1247 : 68198 : }
# 1248 : :
# 1249 : 773765 : void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) {
# 1250 : 773765 : CNodeState *state = State(nodeid);
# 1251 : 773765 : assert(state != nullptr);
# 1252 : :
# 1253 [ + + ]: 773765 : if (!state->hashLastUnknownBlock.IsNull()) {
# 1254 : 5121 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
# 1255 [ + + ][ + + ]: 5121 : if (pindex && pindex->nChainWork > 0) {
# [ + - ]
# 1256 [ + + ][ + - ]: 161 : if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
# 1257 : 161 : state->pindexBestKnownBlock = pindex;
# 1258 : 161 : }
# 1259 : 161 : state->hashLastUnknownBlock.SetNull();
# 1260 : 161 : }
# 1261 : 5121 : }
# 1262 : 773765 : }
# 1263 : :
# 1264 : 26538 : void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
# 1265 : 26538 : CNodeState *state = State(nodeid);
# 1266 : 26538 : assert(state != nullptr);
# 1267 : :
# 1268 : 0 : ProcessBlockAvailability(nodeid);
# 1269 : :
# 1270 : 26538 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
# 1271 [ + + ][ + + ]: 26538 : if (pindex && pindex->nChainWork > 0) {
# [ + - ]
# 1272 : : // An actually better block was announced.
# 1273 [ + + ][ + + ]: 25523 : if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
# 1274 : 25315 : state->pindexBestKnownBlock = pindex;
# 1275 : 25315 : }
# 1276 : 25523 : } else {
# 1277 : : // An unknown block was announced; just assume that the latest one is the best one.
# 1278 : 1015 : state->hashLastUnknownBlock = hash;
# 1279 : 1015 : }
# 1280 : 26538 : }
# 1281 : :
# 1282 : : void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller)
# 1283 : 338464 : {
# 1284 [ - + ]: 338464 : if (count == 0)
# 1285 : 0 : return;
# 1286 : :
# 1287 : 338464 : vBlocks.reserve(vBlocks.size() + count);
# 1288 : 338464 : CNodeState *state = State(peer.m_id);
# 1289 : 338464 : assert(state != nullptr);
# 1290 : :
# 1291 : : // Make sure pindexBestKnownBlock is up to date, we'll need it.
# 1292 : 0 : ProcessBlockAvailability(peer.m_id);
# 1293 : :
# 1294 [ + + ][ + + ]: 338464 : if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
# [ - + ]
# 1295 : : // This peer has nothing interesting.
# 1296 : 182074 : return;
# 1297 : 182074 : }
# 1298 : :
# 1299 [ + + ]: 156390 : if (state->pindexLastCommonBlock == nullptr) {
# 1300 : : // Bootstrap quickly by guessing a parent of our best tip is the forking point.
# 1301 : : // Guessing wrong in either direction is not a problem.
# 1302 : 650 : state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())];
# 1303 : 650 : }
# 1304 : :
# 1305 : : // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
# 1306 : : // of its current tip anymore. Go back enough to fix that.
# 1307 : 156390 : state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
# 1308 [ + + ]: 156390 : if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
# 1309 : 102716 : return;
# 1310 : :
# 1311 : 53674 : std::vector<const CBlockIndex*> vToFetch;
# 1312 : 53674 : const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
# 1313 : : // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
# 1314 : : // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
# 1315 : : // download that next block if the window were 1 larger.
# 1316 : 53674 : int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
# 1317 : 53674 : int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
# 1318 : 53674 : NodeId waitingfor = -1;
# 1319 [ + + ]: 81951 : while (pindexWalk->nHeight < nMaxHeight) {
# 1320 : : // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
# 1321 : : // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
# 1322 : : // as iterating over ~100 CBlockIndex* entries anyway.
# 1323 : 53684 : int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
# 1324 : 53684 : vToFetch.resize(nToFetch);
# 1325 : 53684 : pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
# 1326 : 53684 : vToFetch[nToFetch - 1] = pindexWalk;
# 1327 [ + + ]: 2927632 : for (unsigned int i = nToFetch - 1; i > 0; i--) {
# 1328 : 2873948 : vToFetch[i - 1] = vToFetch[i]->pprev;
# 1329 : 2873948 : }
# 1330 : :
# 1331 : : // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
# 1332 : : // are not yet downloaded and not in flight to vBlocks. In the meantime, update
# 1333 : : // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
# 1334 : : // already part of our chain (and therefore don't need it even if pruned).
# 1335 [ + + ]: 530686 : for (const CBlockIndex* pindex : vToFetch) {
# 1336 [ + + ]: 530686 : if (!pindex->IsValid(BLOCK_VALID_TREE)) {
# 1337 : : // We consider the chain that this peer is on invalid.
# 1338 : 235 : return;
# 1339 : 235 : }
# 1340 [ + + ][ + - ]: 530451 : if (!CanServeWitnesses(peer) && DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {
# 1341 : : // We wouldn't download this block or its descendants from this peer.
# 1342 : 220 : return;
# 1343 : 220 : }
# 1344 [ + + ][ - + ]: 530231 : if (pindex->nStatus & BLOCK_HAVE_DATA || m_chainman.ActiveChain().Contains(pindex)) {
# 1345 [ + + ]: 56821 : if (pindex->HaveTxsDownloaded())
# 1346 : 51729 : state->pindexLastCommonBlock = pindex;
# 1347 [ + + ]: 473410 : } else if (!IsBlockRequested(pindex->GetBlockHash())) {
# 1348 : : // The block is not already downloaded, and not yet in flight.
# 1349 [ - + ]: 26628 : if (pindex->nHeight > nWindowEnd) {
# 1350 : : // We reached the end of the window.
# 1351 [ # # ][ # # ]: 0 : if (vBlocks.size() == 0 && waitingfor != peer.m_id) {
# 1352 : : // We aren't able to fetch anything, but we would be if the download window was one larger.
# 1353 : 0 : nodeStaller = waitingfor;
# 1354 : 0 : }
# 1355 : 0 : return;
# 1356 : 0 : }
# 1357 : 26628 : vBlocks.push_back(pindex);
# 1358 [ + + ]: 26628 : if (vBlocks.size() == count) {
# 1359 : 24952 : return;
# 1360 : 24952 : }
# 1361 [ + + ]: 446782 : } else if (waitingfor == -1) {
# 1362 : : // This is the first already-in-flight block.
# 1363 : 39059 : waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
# 1364 : 39059 : }
# 1365 : 530231 : }
# 1366 : 53684 : }
# 1367 : 53674 : }
# 1368 : :
# 1369 : : } // namespace
# 1370 : :
# 1371 : : void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer)
# 1372 : 1208 : {
# 1373 : 1208 : uint64_t my_services{peer.m_our_services};
# 1374 : 1208 : const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())};
# 1375 : 1208 : uint64_t nonce = pnode.GetLocalNonce();
# 1376 : 1208 : const int nNodeStartingHeight{m_best_height};
# 1377 : 1208 : NodeId nodeid = pnode.GetId();
# 1378 : 1208 : CAddress addr = pnode.addr;
# 1379 : :
# 1380 [ + + ][ + - ]: 1208 : CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService();
# [ + + ]
# 1381 : 1208 : uint64_t your_services{addr.nServices};
# 1382 : :
# 1383 [ + + ][ + + ]: 1208 : const bool tx_relay = !m_ignore_incoming_txs && !pnode.IsBlockOnlyConn() && !pnode.IsFeelerConn();
# [ + + ]
# 1384 : 1208 : m_connman.PushMessage(&pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime,
# 1385 : 1208 : your_services, addr_you, // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime)
# 1386 : 1208 : my_services, CService(), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime)
# 1387 : 1208 : nonce, strSubVersion, nNodeStartingHeight, tx_relay));
# 1388 : :
# 1389 [ + + ]: 1208 : if (fLogIPs) {
# 1390 [ + - ]: 2 : LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, them=%s, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addr_you.ToString(), tx_relay, nodeid);
# 1391 : 1206 : } else {
# 1392 [ + - ]: 1206 : LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid);
# 1393 : 1206 : }
# 1394 : 1208 : }
# 1395 : :
# 1396 : : void PeerManagerImpl::AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
# 1397 : 21700 : {
# 1398 : 21700 : AssertLockHeld(::cs_main); // For m_txrequest
# 1399 : 21700 : NodeId nodeid = node.GetId();
# 1400 [ + + ][ + + ]: 21700 : if (!node.HasPermission(NetPermissionFlags::Relay) && m_txrequest.Count(nodeid) >= MAX_PEER_TX_ANNOUNCEMENTS) {
# 1401 : : // Too many queued announcements from this peer
# 1402 : 1 : return;
# 1403 : 1 : }
# 1404 : 21699 : const CNodeState* state = State(nodeid);
# 1405 : :
# 1406 : : // Decide the TxRequestTracker parameters for this announcement:
# 1407 : : // - "preferred": if fPreferredDownload is set (= outbound, or NetPermissionFlags::NoBan permission)
# 1408 : : // - "reqtime": current time plus delays for:
# 1409 : : // - NONPREF_PEER_TX_DELAY for announcements from non-preferred connections
# 1410 : : // - TXID_RELAY_DELAY for txid announcements while wtxid peers are available
# 1411 : : // - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least
# 1412 : : // MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay).
# 1413 : 21699 : auto delay{0us};
# 1414 : 21699 : const bool preferred = state->fPreferredDownload;
# 1415 [ + + ]: 21699 : if (!preferred) delay += NONPREF_PEER_TX_DELAY;
# 1416 [ + + ][ + + ]: 21699 : if (!gtxid.IsWtxid() && m_wtxid_relay_peers > 0) delay += TXID_RELAY_DELAY;
# 1417 [ + + ]: 21699 : const bool overloaded = !node.HasPermission(NetPermissionFlags::Relay) &&
# 1418 [ + + ]: 21699 : m_txrequest.CountInFlight(nodeid) >= MAX_PEER_TX_REQUEST_IN_FLIGHT;
# 1419 [ + + ]: 21699 : if (overloaded) delay += OVERLOADED_PEER_TX_DELAY;
# 1420 : 21699 : m_txrequest.ReceivedInv(nodeid, gtxid, preferred, current_time + delay);
# 1421 : 21699 : }
# 1422 : :
# 1423 : : void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
# 1424 : 2 : {
# 1425 : 2 : LOCK(cs_main);
# 1426 : 2 : CNodeState *state = State(node);
# 1427 [ + - ]: 2 : if (state) state->m_last_block_announcement = time_in_seconds;
# 1428 : 2 : }
# 1429 : :
# 1430 : : void PeerManagerImpl::InitializeNode(CNode& node, ServiceFlags our_services)
# 1431 : 1218 : {
# 1432 : 1218 : NodeId nodeid = node.GetId();
# 1433 : 1218 : {
# 1434 : 1218 : LOCK(cs_main);
# 1435 : 1218 : m_node_states.emplace_hint(m_node_states.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(node.IsInboundConn()));
# 1436 : 1218 : assert(m_txrequest.Count(nodeid) == 0);
# 1437 : 1218 : }
# 1438 : 0 : PeerRef peer = std::make_shared<Peer>(nodeid, our_services);
# 1439 : 1218 : {
# 1440 : 1218 : LOCK(m_peer_mutex);
# 1441 : 1218 : m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
# 1442 : 1218 : }
# 1443 [ + + ]: 1218 : if (!node.IsInboundConn()) {
# 1444 : 462 : PushNodeVersion(node, *peer);
# 1445 : 462 : }
# 1446 : 1218 : }
# 1447 : :
# 1448 : : void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler)
# 1449 : 3 : {
# 1450 : 3 : std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs();
# 1451 : :
# 1452 [ + + ]: 3 : for (const auto& txid : unbroadcast_txids) {
# 1453 : 3 : CTransactionRef tx = m_mempool.get(txid);
# 1454 : :
# 1455 [ + - ]: 3 : if (tx != nullptr) {
# 1456 : 3 : RelayTransaction(txid, tx->GetWitnessHash());
# 1457 : 3 : } else {
# 1458 : 0 : m_mempool.RemoveUnbroadcastTx(txid, true);
# 1459 : 0 : }
# 1460 : 3 : }
# 1461 : :
# 1462 : : // Schedule next run for 10-15 minutes in the future.
# 1463 : : // We add randomness on every cycle to avoid the possibility of P2P fingerprinting.
# 1464 : 3 : const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
# 1465 : 3 : scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
# 1466 : 3 : }
# 1467 : :
# 1468 : : void PeerManagerImpl::FinalizeNode(const CNode& node)
# 1469 : 1216 : {
# 1470 : 1216 : NodeId nodeid = node.GetId();
# 1471 : 1216 : int misbehavior{0};
# 1472 : 1216 : {
# 1473 : 1216 : LOCK(cs_main);
# 1474 : 1216 : {
# 1475 : : // We remove the PeerRef from g_peer_map here, but we don't always
# 1476 : : // destruct the Peer. Sometimes another thread is still holding a
# 1477 : : // PeerRef, so the refcount is >= 1. Be careful not to do any
# 1478 : : // processing here that assumes Peer won't be changed before it's
# 1479 : : // destructed.
# 1480 : 1216 : PeerRef peer = RemovePeer(nodeid);
# 1481 : 1216 : assert(peer != nullptr);
# 1482 : 1216 : misbehavior = WITH_LOCK(peer->m_misbehavior_mutex, return peer->m_misbehavior_score);
# 1483 : 1216 : m_wtxid_relay_peers -= peer->m_wtxid_relay;
# 1484 : 1216 : assert(m_wtxid_relay_peers >= 0);
# 1485 : 1216 : }
# 1486 : 0 : CNodeState *state = State(nodeid);
# 1487 : 1216 : assert(state != nullptr);
# 1488 : :
# 1489 [ + + ]: 1216 : if (state->fSyncStarted)
# 1490 : 1134 : nSyncStarted--;
# 1491 : :
# 1492 [ + + ]: 1216 : for (const QueuedBlock& entry : state->vBlocksInFlight) {
# 1493 : 64 : mapBlocksInFlight.erase(entry.pindex->GetBlockHash());
# 1494 : 64 : }
# 1495 : 1216 : WITH_LOCK(g_cs_orphans, m_orphanage.EraseForPeer(nodeid));
# 1496 : 1216 : m_txrequest.DisconnectedPeer(nodeid);
# 1497 : 1216 : m_num_preferred_download_peers -= state->fPreferredDownload;
# 1498 : 1216 : m_peers_downloading_from -= (state->nBlocksInFlight != 0);
# 1499 : 1216 : assert(m_peers_downloading_from >= 0);
# 1500 : 0 : m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
# 1501 : 1216 : assert(m_outbound_peers_with_protect_from_disconnect >= 0);
# 1502 : :
# 1503 : 0 : m_node_states.erase(nodeid);
# 1504 : :
# 1505 [ + + ]: 1216 : if (m_node_states.empty()) {
# 1506 : : // Do a consistency check after the last peer is removed.
# 1507 : 654 : assert(mapBlocksInFlight.empty());
# 1508 : 0 : assert(m_num_preferred_download_peers == 0);
# 1509 : 0 : assert(m_peers_downloading_from == 0);
# 1510 : 0 : assert(m_outbound_peers_with_protect_from_disconnect == 0);
# 1511 : 0 : assert(m_wtxid_relay_peers == 0);
# 1512 : 0 : assert(m_txrequest.Size() == 0);
# 1513 : 0 : assert(m_orphanage.Size() == 0);
# 1514 : 654 : }
# 1515 : 1216 : } // cs_main
# 1516 [ + + ][ + + ]: 1216 : if (node.fSuccessfullyConnected && misbehavior == 0 &&
# 1517 [ + + ][ + + ]: 1216 : !node.IsBlockOnlyConn() && !node.IsInboundConn()) {
# 1518 : : // Only change visible addrman state for full outbound peers. We don't
# 1519 : : // call Connected() for feeler connections since they don't have
# 1520 : : // fSuccessfullyConnected set.
# 1521 : 410 : m_addrman.Connected(node.addr);
# 1522 : 410 : }
# 1523 : 1216 : {
# 1524 : 1216 : LOCK(m_headers_presync_mutex);
# 1525 : 1216 : m_headers_presync_stats.erase(nodeid);
# 1526 : 1216 : }
# 1527 [ + - ]: 1216 : LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
# 1528 : 1216 : }
# 1529 : :
# 1530 : : PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const
# 1531 : 853650 : {
# 1532 : 853650 : LOCK(m_peer_mutex);
# 1533 : 853650 : auto it = m_peer_map.find(id);
# 1534 [ + + ]: 853650 : return it != m_peer_map.end() ? it->second : nullptr;
# 1535 : 853650 : }
# 1536 : :
# 1537 : : PeerRef PeerManagerImpl::RemovePeer(NodeId id)
# 1538 : 1216 : {
# 1539 : 1216 : PeerRef ret;
# 1540 : 1216 : LOCK(m_peer_mutex);
# 1541 : 1216 : auto it = m_peer_map.find(id);
# 1542 [ + - ]: 1216 : if (it != m_peer_map.end()) {
# 1543 : 1216 : ret = std::move(it->second);
# 1544 : 1216 : m_peer_map.erase(it);
# 1545 : 1216 : }
# 1546 : 1216 : return ret;
# 1547 : 1216 : }
# 1548 : :
# 1549 : : bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const
# 1550 : 16361 : {
# 1551 : 16361 : {
# 1552 : 16361 : LOCK(cs_main);
# 1553 : 16361 : const CNodeState* state = State(nodeid);
# 1554 [ - + ]: 16361 : if (state == nullptr)
# 1555 : 0 : return false;
# 1556 [ + + ]: 16361 : stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
# 1557 [ + + ]: 16361 : stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
# 1558 [ + + ]: 16361 : for (const QueuedBlock& queue : state->vBlocksInFlight) {
# 1559 [ + - ]: 2015 : if (queue.pindex)
# 1560 : 2015 : stats.vHeightInFlight.push_back(queue.pindex->nHeight);
# 1561 : 2015 : }
# 1562 : 16361 : }
# 1563 : :
# 1564 : 0 : PeerRef peer = GetPeerRef(nodeid);
# 1565 [ - + ]: 16361 : if (peer == nullptr) return false;
# 1566 : 16361 : stats.their_services = peer->m_their_services;
# 1567 : 16361 : stats.m_starting_height = peer->m_starting_height;
# 1568 : : // It is common for nodes with good ping times to suddenly become lagged,
# 1569 : : // due to a new block arriving or other large transfer.
# 1570 : : // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
# 1571 : : // since pingtime does not update until the ping is complete, which might take a while.
# 1572 : : // So, if a ping is taking an unusually long time in flight,
# 1573 : : // the caller can immediately detect that this is happening.
# 1574 : 16361 : auto ping_wait{0us};
# 1575 [ + + ][ + + ]: 16361 : if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) {
# [ + - ]
# 1576 : 40 : ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
# 1577 : 40 : }
# 1578 : :
# 1579 [ + + ]: 16361 : if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
# 1580 : 15926 : stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs);
# 1581 : 15926 : stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load();
# 1582 : 15926 : } else {
# 1583 : 435 : stats.m_relay_txs = false;
# 1584 : 435 : stats.m_fee_filter_received = 0;
# 1585 : 435 : }
# 1586 : :
# 1587 : 16361 : stats.m_ping_wait = ping_wait;
# 1588 : 16361 : stats.m_addr_processed = peer->m_addr_processed.load();
# 1589 : 16361 : stats.m_addr_rate_limited = peer->m_addr_rate_limited.load();
# 1590 : 16361 : stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load();
# 1591 : 16361 : {
# 1592 : 16361 : LOCK(peer->m_headers_sync_mutex);
# 1593 [ + + ]: 16361 : if (peer->m_headers_sync) {
# 1594 : 3 : stats.presync_height = peer->m_headers_sync->GetPresyncHeight();
# 1595 : 3 : }
# 1596 : 16361 : }
# 1597 : :
# 1598 : 16361 : return true;
# 1599 : 16361 : }
# 1600 : :
# 1601 : : void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx)
# 1602 : 734 : {
# 1603 : 734 : size_t max_extra_txn = gArgs.GetIntArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
# 1604 [ - + ]: 734 : if (max_extra_txn <= 0)
# 1605 : 0 : return;
# 1606 [ + + ]: 734 : if (!vExtraTxnForCompact.size())
# 1607 : 19 : vExtraTxnForCompact.resize(max_extra_txn);
# 1608 : 734 : vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
# 1609 : 734 : vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
# 1610 : 734 : }
# 1611 : :
# 1612 : : void PeerManagerImpl::Misbehaving(Peer& peer, int howmuch, const std::string& message)
# 1613 : 813 : {
# 1614 : 813 : assert(howmuch > 0);
# 1615 : :
# 1616 : 813 : LOCK(peer.m_misbehavior_mutex);
# 1617 : 813 : const int score_before{peer.m_misbehavior_score};
# 1618 : 813 : peer.m_misbehavior_score += howmuch;
# 1619 : 813 : const int score_now{peer.m_misbehavior_score};
# 1620 : :
# 1621 [ + + ]: 813 : const std::string message_prefixed = message.empty() ? "" : (": " + message);
# 1622 : 813 : std::string warning;
# 1623 : :
# 1624 [ + + ][ + + ]: 813 : if (score_now >= DISCOURAGEMENT_THRESHOLD && score_before < DISCOURAGEMENT_THRESHOLD) {
# 1625 : 104 : warning = " DISCOURAGE THRESHOLD EXCEEDED";
# 1626 : 104 : peer.m_should_discourage = true;
# 1627 : 104 : }
# 1628 : :
# 1629 [ + - ]: 813 : LogPrint(BCLog::NET, "Misbehaving: peer=%d (%d -> %d)%s%s\n",
# 1630 : 813 : peer.m_id, score_before, score_now, warning, message_prefixed);
# 1631 : 813 : }
# 1632 : :
# 1633 : : bool PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
# 1634 : : bool via_compact_block, const std::string& message)
# 1635 : 779 : {
# 1636 : 779 : PeerRef peer{GetPeerRef(nodeid)};
# 1637 [ - + ]: 779 : switch (state.GetResult()) {
# 1638 [ - + ]: 0 : case BlockValidationResult::BLOCK_RESULT_UNSET:
# 1639 : 0 : break;
# 1640 [ + + ]: 1 : case BlockValidationResult::BLOCK_HEADER_LOW_WORK:
# 1641 : : // We didn't try to process the block because the header chain may have
# 1642 : : // too little work.
# 1643 : 1 : break;
# 1644 : : // The node is providing invalid data:
# 1645 [ + + ]: 580 : case BlockValidationResult::BLOCK_CONSENSUS:
# 1646 [ + + ]: 748 : case BlockValidationResult::BLOCK_MUTATED:
# 1647 [ + + ]: 748 : if (!via_compact_block) {
# 1648 [ + - ]: 732 : if (peer) Misbehaving(*peer, 100, message);
# 1649 : 732 : return true;
# 1650 : 732 : }
# 1651 : 16 : break;
# 1652 [ + + ]: 17 : case BlockValidationResult::BLOCK_CACHED_INVALID:
# 1653 : 17 : {
# 1654 : 17 : LOCK(cs_main);
# 1655 : 17 : CNodeState *node_state = State(nodeid);
# 1656 [ - + ]: 17 : if (node_state == nullptr) {
# 1657 : 0 : break;
# 1658 : 0 : }
# 1659 : :
# 1660 : : // Discourage outbound (but not inbound) peers if on an invalid chain.
# 1661 : : // Exempt HB compact block peers. Manual connections are always protected from discouragement.
# 1662 [ + - ][ + - ]: 17 : if (!via_compact_block && !node_state->m_is_inbound) {
# 1663 [ + - ]: 17 : if (peer) Misbehaving(*peer, 100, message);
# 1664 : 17 : return true;
# 1665 : 17 : }
# 1666 : 0 : break;
# 1667 : 17 : }
# 1668 [ + + ]: 6 : case BlockValidationResult::BLOCK_INVALID_HEADER:
# 1669 [ + + ]: 7 : case BlockValidationResult::BLOCK_CHECKPOINT:
# 1670 [ + + ]: 10 : case BlockValidationResult::BLOCK_INVALID_PREV:
# 1671 [ + - ]: 10 : if (peer) Misbehaving(*peer, 100, message);
# 1672 : 10 : return true;
# 1673 : : // Conflicting (but not necessarily invalid) data or different policy:
# 1674 [ + + ]: 1 : case BlockValidationResult::BLOCK_MISSING_PREV:
# 1675 : : // TODO: Handle this much more gracefully (10 DoS points is super arbitrary)
# 1676 [ + - ]: 1 : if (peer) Misbehaving(*peer, 10, message);
# 1677 : 1 : return true;
# 1678 [ - + ]: 0 : case BlockValidationResult::BLOCK_RECENT_CONSENSUS_CHANGE:
# 1679 [ + + ]: 2 : case BlockValidationResult::BLOCK_TIME_FUTURE:
# 1680 : 2 : break;
# 1681 : 779 : }
# 1682 [ - + ]: 19 : if (message != "") {
# 1683 [ # # ]: 0 : LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
# 1684 : 0 : }
# 1685 : 19 : return false;
# 1686 : 779 : }
# 1687 : :
# 1688 : : bool PeerManagerImpl::MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state, const std::string& message)
# 1689 : 330 : {
# 1690 : 330 : PeerRef peer{GetPeerRef(nodeid)};
# 1691 [ - + ]: 330 : switch (state.GetResult()) {
# 1692 [ - + ]: 0 : case TxValidationResult::TX_RESULT_UNSET:
# 1693 : 0 : break;
# 1694 : : // The node is providing invalid data:
# 1695 [ + + ]: 26 : case TxValidationResult::TX_CONSENSUS:
# 1696 [ + - ]: 26 : if (peer) Misbehaving(*peer, 100, message);
# 1697 : 26 : return true;
# 1698 : : // Conflicting (but not necessarily invalid) data or different policy:
# 1699 [ - + ]: 0 : case TxValidationResult::TX_RECENT_CONSENSUS_CHANGE:
# 1700 [ + + ]: 25 : case TxValidationResult::TX_INPUTS_NOT_STANDARD:
# 1701 [ + + ]: 80 : case TxValidationResult::TX_NOT_STANDARD:
# 1702 [ + + ]: 250 : case TxValidationResult::TX_MISSING_INPUTS:
# 1703 [ - + ]: 250 : case TxValidationResult::TX_PREMATURE_SPEND:
# 1704 [ + + ]: 257 : case TxValidationResult::TX_WITNESS_MUTATED:
# 1705 [ + + ]: 258 : case TxValidationResult::TX_WITNESS_STRIPPED:
# 1706 [ - + ]: 258 : case TxValidationResult::TX_CONFLICT:
# 1707 [ + + ]: 304 : case TxValidationResult::TX_MEMPOOL_POLICY:
# 1708 [ - + ]: 304 : case TxValidationResult::TX_NO_MEMPOOL:
# 1709 : 304 : break;
# 1710 : 330 : }
# 1711 [ - + ]: 304 : if (message != "") {
# 1712 [ # # ]: 0 : LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
# 1713 : 0 : }
# 1714 : 304 : return false;
# 1715 : 330 : }
# 1716 : :
# 1717 : : bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
# 1718 : 29444 : {
# 1719 : 29444 : AssertLockHeld(cs_main);
# 1720 [ + + ]: 29444 : if (m_chainman.ActiveChain().Contains(pindex)) return true;
# 1721 [ + + ][ + - ]: 94 : return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (m_chainman.m_best_header != nullptr) &&
# 1722 [ + + ]: 94 : (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
# 1723 [ + - ]: 94 : (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
# 1724 : 29444 : }
# 1725 : :
# 1726 : : std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index)
# 1727 : 4 : {
# 1728 [ - + ]: 4 : if (fImporting) return "Importing...";
# 1729 [ - + ]: 4 : if (fReindex) return "Reindexing...";
# 1730 : :
# 1731 : : // Ensure this peer exists and hasn't been disconnected
# 1732 : 4 : PeerRef peer = GetPeerRef(peer_id);
# 1733 [ + + ]: 4 : if (peer == nullptr) return "Peer does not exist";
# 1734 : :
# 1735 : : // Ignore pre-segwit peers
# 1736 [ + + ]: 2 : if (!CanServeWitnesses(*peer)) return "Pre-SegWit peer";
# 1737 : :
# 1738 : 1 : LOCK(cs_main);
# 1739 : :
# 1740 : : // Mark block as in-flight unless it already is (for this peer).
# 1741 : : // If a block was already in-flight for a different peer, its BLOCKTXN
# 1742 : : // response will be dropped.
# 1743 [ - + ]: 1 : if (!BlockRequested(peer_id, block_index)) return "Already requested from this peer";
# 1744 : :
# 1745 : : // Construct message to request the block
# 1746 : 1 : const uint256& hash{block_index.GetBlockHash()};
# 1747 : 1 : std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)};
# 1748 : :
# 1749 : : // Send block request message to the peer
# 1750 : 1 : bool success = m_connman.ForNode(peer_id, [this, &invs](CNode* node) {
# 1751 : 1 : const CNetMsgMaker msgMaker(node->GetCommonVersion());
# 1752 : 1 : this->m_connman.PushMessage(node, msgMaker.Make(NetMsgType::GETDATA, invs));
# 1753 : 1 : return true;
# 1754 : 1 : });
# 1755 : :
# 1756 [ - + ]: 1 : if (!success) return "Peer not fully connected";
# 1757 : :
# 1758 [ + - ]: 1 : LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
# 1759 : 1 : hash.ToString(), peer_id);
# 1760 : 1 : return std::nullopt;
# 1761 : 1 : }
# 1762 : :
# 1763 : : std::unique_ptr<PeerManager> PeerManager::make(CConnman& connman, AddrMan& addrman,
# 1764 : : BanMan* banman, ChainstateManager& chainman,
# 1765 : : CTxMemPool& pool, bool ignore_incoming_txs)
# 1766 : 960 : {
# 1767 : 960 : return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman, pool, ignore_incoming_txs);
# 1768 : 960 : }
# 1769 : :
# 1770 : : PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman,
# 1771 : : BanMan* banman, ChainstateManager& chainman,
# 1772 : : CTxMemPool& pool, bool ignore_incoming_txs)
# 1773 : : : m_chainparams(chainman.GetParams()),
# 1774 : : m_connman(connman),
# 1775 : : m_addrman(addrman),
# 1776 : : m_banman(banman),
# 1777 : : m_chainman(chainman),
# 1778 : : m_mempool(pool),
# 1779 : : m_ignore_incoming_txs(ignore_incoming_txs)
# 1780 : 960 : {
# 1781 : 960 : }
# 1782 : :
# 1783 : : void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler)
# 1784 : 735 : {
# 1785 : : // Stale tip checking and peer eviction are on two different timers, but we
# 1786 : : // don't want them to get out of sync due to drift in the scheduler, so we
# 1787 : : // combine them in one function and schedule at the quicker (peer-eviction)
# 1788 : : // timer.
# 1789 : 735 : static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
# 1790 : 735 : scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL});
# 1791 : :
# 1792 : : // schedule next run for 10-15 minutes in the future
# 1793 : 735 : const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
# 1794 : 735 : scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
# 1795 : 735 : }
# 1796 : :
# 1797 : : /**
# 1798 : : * Evict orphan txn pool entries based on a newly connected
# 1799 : : * block, remember the recently confirmed transactions, and delete tracked
# 1800 : : * announcements for them. Also save the time of the last tip update.
# 1801 : : */
# 1802 : : void PeerManagerImpl::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex)
# 1803 : 74591 : {
# 1804 : 74591 : m_orphanage.EraseForBlock(*pblock);
# 1805 : 74591 : m_last_tip_update = GetTime<std::chrono::seconds>();
# 1806 : :
# 1807 : 74591 : {
# 1808 : 74591 : LOCK(m_recent_confirmed_transactions_mutex);
# 1809 [ + + ]: 118656 : for (const auto& ptx : pblock->vtx) {
# 1810 : 118656 : m_recent_confirmed_transactions.insert(ptx->GetHash());
# 1811 [ + + ]: 118656 : if (ptx->GetHash() != ptx->GetWitnessHash()) {
# 1812 : 88219 : m_recent_confirmed_transactions.insert(ptx->GetWitnessHash());
# 1813 : 88219 : }
# 1814 : 118656 : }
# 1815 : 74591 : }
# 1816 : 74591 : {
# 1817 : 74591 : LOCK(cs_main);
# 1818 [ + + ]: 118656 : for (const auto& ptx : pblock->vtx) {
# 1819 : 118656 : m_txrequest.ForgetTxHash(ptx->GetHash());
# 1820 : 118656 : m_txrequest.ForgetTxHash(ptx->GetWitnessHash());
# 1821 : 118656 : }
# 1822 : 74591 : }
# 1823 : 74591 : }
# 1824 : :
# 1825 : : void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex)
# 1826 : 9242 : {
# 1827 : : // To avoid relay problems with transactions that were previously
# 1828 : : // confirmed, clear our filter of recently confirmed transactions whenever
# 1829 : : // there's a reorg.
# 1830 : : // This means that in a 1-block reorg (where 1 block is disconnected and
# 1831 : : // then another block reconnected), our filter will drop to having only one
# 1832 : : // block's worth of transactions in it, but that should be fine, since
# 1833 : : // presumably the most common case of relaying a confirmed transaction
# 1834 : : // should be just after a new block containing it is found.
# 1835 : 9242 : LOCK(m_recent_confirmed_transactions_mutex);
# 1836 : 9242 : m_recent_confirmed_transactions.reset();
# 1837 : 9242 : }
# 1838 : :
# 1839 : : /**
# 1840 : : * Maintain state about the best-seen block and fast-announce a compact block
# 1841 : : * to compatible peers.
# 1842 : : */
# 1843 : : void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)
# 1844 : 60928 : {
# 1845 : 60928 : auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock);
# 1846 : 60928 : const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
# 1847 : :
# 1848 : 60928 : LOCK(cs_main);
# 1849 : :
# 1850 [ + + ]: 60928 : if (pindex->nHeight <= m_highest_fast_announce)
# 1851 : 2868 : return;
# 1852 : 58060 : m_highest_fast_announce = pindex->nHeight;
# 1853 : :
# 1854 [ + + ]: 58060 : if (!DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) return;
# 1855 : :
# 1856 : 56738 : uint256 hashBlock(pblock->GetHash());
# 1857 : 56738 : const std::shared_future<CSerializedNetMsg> lazy_ser{
# 1858 : 56738 : std::async(std::launch::deferred, [&] { return msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock); })};
# 1859 : :
# 1860 : 56738 : {
# 1861 : 56738 : LOCK(m_most_recent_block_mutex);
# 1862 : 56738 : m_most_recent_block_hash = hashBlock;
# 1863 : 56738 : m_most_recent_block = pblock;
# 1864 : 56738 : m_most_recent_compact_block = pcmpctblock;
# 1865 : 56738 : }
# 1866 : :
# 1867 : 63265 : m_connman.ForEachNode([this, pindex, &lazy_ser, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
# 1868 : 63265 : AssertLockHeld(::cs_main);
# 1869 : :
# 1870 [ - + ][ - + ]: 63265 : if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
# 1871 : 0 : return;
# 1872 : 63265 : ProcessBlockAvailability(pnode->GetId());
# 1873 : 63265 : CNodeState &state = *State(pnode->GetId());
# 1874 : : // If the peer has, or we announced to them the previous block already,
# 1875 : : // but we don't think they have this one, go ahead and announce it
# 1876 [ + + ][ + + ]: 63265 : if (state.m_requested_hb_cmpctblocks && !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
# [ + + ]
# 1877 : :
# 1878 [ + - ]: 13000 : LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock",
# 1879 : 13000 : hashBlock.ToString(), pnode->GetId());
# 1880 : :
# 1881 : 13000 : const CSerializedNetMsg& ser_cmpctblock{lazy_ser.get()};
# 1882 : 13000 : m_connman.PushMessage(pnode, ser_cmpctblock.Copy());
# 1883 : 13000 : state.pindexBestHeaderSent = pindex;
# 1884 : 13000 : }
# 1885 : 63265 : });
# 1886 : 56738 : }
# 1887 : :
# 1888 : : /**
# 1889 : : * Update our best height and announce any block hashes which weren't previously
# 1890 : : * in m_chainman.ActiveChain() to our peers.
# 1891 : : */
# 1892 : : void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
# 1893 : 66284 : {
# 1894 : 66284 : SetBestHeight(pindexNew->nHeight);
# 1895 : 66284 : SetServiceFlagsIBDCache(!fInitialDownload);
# 1896 : :
# 1897 : : // Don't relay inventory during initial block download.
# 1898 [ + + ]: 66284 : if (fInitialDownload) return;
# 1899 : :
# 1900 : : // Find the hashes of all blocks that weren't previously in the best chain.
# 1901 : 59439 : std::vector<uint256> vHashes;
# 1902 : 59439 : const CBlockIndex *pindexToAnnounce = pindexNew;
# 1903 [ + + ]: 119068 : while (pindexToAnnounce != pindexFork) {
# 1904 : 59641 : vHashes.push_back(pindexToAnnounce->GetBlockHash());
# 1905 : 59641 : pindexToAnnounce = pindexToAnnounce->pprev;
# 1906 [ + + ]: 59641 : if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
# 1907 : : // Limit announcements in case of a huge reorganization.
# 1908 : : // Rely on the peer's synchronization mechanism in that case.
# 1909 : 12 : break;
# 1910 : 12 : }
# 1911 : 59641 : }
# 1912 : :
# 1913 : 59439 : {
# 1914 : 59439 : LOCK(m_peer_mutex);
# 1915 [ + + ]: 67739 : for (auto& it : m_peer_map) {
# 1916 : 67739 : Peer& peer = *it.second;
# 1917 : 67739 : LOCK(peer.m_block_inv_mutex);
# 1918 [ + + ]: 68039 : for (const uint256& hash : reverse_iterate(vHashes)) {
# 1919 : 68039 : peer.m_blocks_for_headers_relay.push_back(hash);
# 1920 : 68039 : }
# 1921 : 67739 : }
# 1922 : 59439 : }
# 1923 : :
# 1924 : 59439 : m_connman.WakeMessageHandler();
# 1925 : 59439 : }
# 1926 : :
# 1927 : : /**
# 1928 : : * Handle invalid block rejection and consequent peer discouragement, maintain which
# 1929 : : * peers announce compact blocks.
# 1930 : : */
# 1931 : : void PeerManagerImpl::BlockChecked(const CBlock& block, const BlockValidationState& state)
# 1932 : 77853 : {
# 1933 : 77853 : LOCK(cs_main);
# 1934 : :
# 1935 : 77853 : const uint256 hash(block.GetHash());
# 1936 : 77853 : std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
# 1937 : :
# 1938 : : // If the block failed validation, we know where it came from and we're still connected
# 1939 : : // to that peer, maybe punish.
# 1940 [ + + ][ + + ]: 77853 : if (state.IsInvalid() &&
# 1941 [ + + ]: 77853 : it != mapBlockSource.end() &&
# 1942 [ + - ]: 77853 : State(it->second.first)) {
# 1943 : 758 : MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second);
# 1944 : 758 : }
# 1945 : : // Check that:
# 1946 : : // 1. The block is valid
# 1947 : : // 2. We're not in initial block download
# 1948 : : // 3. This is currently the best block we're aware of. We haven't updated
# 1949 : : // the tip yet so we have no way to check this directly here. Instead we
# 1950 : : // just check that there are currently no other blocks in flight.
# 1951 [ + + ]: 77095 : else if (state.IsValid() &&
# 1952 [ + + ]: 77095 : !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
# 1953 [ + + ]: 77095 : mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
# 1954 [ + + ]: 44741 : if (it != mapBlockSource.end()) {
# 1955 : 13476 : MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
# 1956 : 13476 : }
# 1957 : 44741 : }
# 1958 [ + + ]: 77853 : if (it != mapBlockSource.end())
# 1959 : 41666 : mapBlockSource.erase(it);
# 1960 : 77853 : }
# 1961 : :
# 1962 : : //////////////////////////////////////////////////////////////////////////////
# 1963 : : //
# 1964 : : // Messages
# 1965 : : //
# 1966 : :
# 1967 : :
# 1968 : : bool PeerManagerImpl::AlreadyHaveTx(const GenTxid& gtxid)
# 1969 : 58081 : {
# 1970 [ + + ]: 58081 : if (m_chainman.ActiveChain().Tip()->GetBlockHash() != hashRecentRejectsChainTip) {
# 1971 : : // If the chain tip has changed previously rejected transactions
# 1972 : : // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
# 1973 : : // or a double-spend. Reset the rejects filter and give those
# 1974 : : // txs a second chance.
# 1975 : 820 : hashRecentRejectsChainTip = m_chainman.ActiveChain().Tip()->GetBlockHash();
# 1976 : 820 : m_recent_rejects.reset();
# 1977 : 820 : }
# 1978 : :
# 1979 : 58081 : const uint256& hash = gtxid.GetHash();
# 1980 : :
# 1981 [ + + ]: 58081 : if (m_orphanage.HaveTx(gtxid)) return true;
# 1982 : :
# 1983 : 58032 : {
# 1984 : 58032 : LOCK(m_recent_confirmed_transactions_mutex);
# 1985 [ + + ]: 58032 : if (m_recent_confirmed_transactions.contains(hash)) return true;
# 1986 : 58032 : }
# 1987 : :
# 1988 [ + + ][ + + ]: 57978 : return m_recent_rejects.contains(hash) || m_mempool.exists(gtxid);
# 1989 : 58032 : }
# 1990 : :
# 1991 : : bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash)
# 1992 : 1440 : {
# 1993 : 1440 : return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
# 1994 : 1440 : }
# 1995 : :
# 1996 : : void PeerManagerImpl::SendPings()
# 1997 : 2 : {
# 1998 : 2 : LOCK(m_peer_mutex);
# 1999 [ + + ]: 3 : for(auto& it : m_peer_map) it.second->m_ping_queued = true;
# 2000 : 2 : }
# 2001 : :
# 2002 : : void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid)
# 2003 : 20768 : {
# 2004 : 20768 : LOCK(m_peer_mutex);
# 2005 [ + + ]: 36048 : for(auto& it : m_peer_map) {
# 2006 : 36048 : Peer& peer = *it.second;
# 2007 : 36048 : auto tx_relay = peer.GetTxRelay();
# 2008 [ + + ]: 36048 : if (!tx_relay) continue;
# 2009 : :
# 2010 [ + + ]: 36045 : const uint256& hash{peer.m_wtxid_relay ? wtxid : txid};
# 2011 : 36045 : LOCK(tx_relay->m_tx_inventory_mutex);
# 2012 [ + + ]: 36045 : if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) {
# 2013 : 24798 : tx_relay->m_tx_inventory_to_send.insert(hash);
# 2014 : 24798 : }
# 2015 : 36045 : };
# 2016 : 20768 : }
# 2017 : :
# 2018 : : void PeerManagerImpl::RelayAddress(NodeId originator,
# 2019 : : const CAddress& addr,
# 2020 : : bool fReachable)
# 2021 : 53 : {
# 2022 : : // We choose the same nodes within a given 24h window (if the list of connected
# 2023 : : // nodes does not change) and we don't relay to nodes that already know an
# 2024 : : // address. So within 24h we will likely relay a given address once. This is to
# 2025 : : // prevent a peer from unjustly giving their address better propagation by sending
# 2026 : : // it to us repeatedly.
# 2027 : :
# 2028 [ + + ][ - + ]: 53 : if (!fReachable && !addr.IsRelayable()) return;
# 2029 : :
# 2030 : : // Relay to a limited number of other nodes
# 2031 : : // Use deterministic randomness to send to the same nodes for 24 hours
# 2032 : : // at a time so the m_addr_knowns of the chosen nodes prevent repeats
# 2033 : 53 : const uint64_t hash_addr{CServiceHash(0, 0)(addr)};
# 2034 : 53 : const auto current_time{GetTime<std::chrono::seconds>()};
# 2035 : : // Adding address hash makes exact rotation time different per address, while preserving periodicity.
# 2036 : 53 : const uint64_t time_addr{(static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) / count_seconds(ROTATE_ADDR_RELAY_DEST_INTERVAL)};
# 2037 : 53 : const CSipHasher hasher{m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY)
# 2038 : 53 : .Write(hash_addr)
# 2039 : 53 : .Write(time_addr)};
# 2040 : 53 : FastRandomContext insecure_rand;
# 2041 : :
# 2042 : : // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers.
# 2043 [ + + ][ + - ]: 53 : unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
# 2044 : :
# 2045 : 53 : std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}};
# 2046 : 53 : assert(nRelayNodes <= best.size());
# 2047 : :
# 2048 : 53 : LOCK(m_peer_mutex);
# 2049 : :
# 2050 [ + + ]: 569 : for (auto& [id, peer] : m_peer_map) {
# 2051 [ + + ][ + + ]: 569 : if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) {
# [ + - ]
# 2052 : 512 : uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
# 2053 [ + + ]: 1264 : for (unsigned int i = 0; i < nRelayNodes; i++) {
# 2054 [ + + ]: 918 : if (hashKey > best[i].first) {
# 2055 : 166 : std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
# 2056 : 166 : best[i] = std::make_pair(hashKey, peer.get());
# 2057 : 166 : break;
# 2058 : 166 : }
# 2059 : 918 : }
# 2060 : 512 : }
# 2061 : 569 : };
# 2062 : :
# 2063 [ + + ][ + + ]: 135 : for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
# 2064 : 82 : PushAddress(*best[i].second, addr, insecure_rand);
# 2065 : 82 : }
# 2066 : 53 : }
# 2067 : :
# 2068 : : void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
# 2069 : 29429 : {
# 2070 : 29429 : std::shared_ptr<const CBlock> a_recent_block;
# 2071 : 29429 : std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
# 2072 : 29429 : {
# 2073 : 29429 : LOCK(m_most_recent_block_mutex);
# 2074 : 29429 : a_recent_block = m_most_recent_block;
# 2075 : 29429 : a_recent_compact_block = m_most_recent_compact_block;
# 2076 : 29429 : }
# 2077 : :
# 2078 : 29429 : bool need_activate_chain = false;
# 2079 : 29429 : {
# 2080 : 29429 : LOCK(cs_main);
# 2081 : 29429 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
# 2082 [ + - ]: 29429 : if (pindex) {
# 2083 [ + - ][ + + ]: 29429 : if (pindex->HaveTxsDownloaded() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
# 2084 [ - + ]: 29429 : pindex->IsValid(BLOCK_VALID_TREE)) {
# 2085 : : // If we have the block and all of its parents, but have not yet validated it,
# 2086 : : // we might be in the middle of connecting it (ie in the unlock of cs_main
# 2087 : : // before ActivateBestChain but after AcceptBlock).
# 2088 : : // In this case, we need to run ActivateBestChain prior to checking the relay
# 2089 : : // conditions below.
# 2090 : 0 : need_activate_chain = true;
# 2091 : 0 : }
# 2092 : 29429 : }
# 2093 : 29429 : } // release cs_main before calling ActivateBestChain
# 2094 [ - + ]: 29429 : if (need_activate_chain) {
# 2095 : 0 : BlockValidationState state;
# 2096 [ # # ]: 0 : if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
# 2097 [ # # ]: 0 : LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
# 2098 : 0 : }
# 2099 : 0 : }
# 2100 : :
# 2101 : 29429 : LOCK(cs_main);
# 2102 : 29429 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
# 2103 [ - + ]: 29429 : if (!pindex) {
# 2104 : 0 : return;
# 2105 : 0 : }
# 2106 [ + + ]: 29429 : if (!BlockRequestAllowed(pindex)) {
# 2107 [ + - ]: 2 : LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId());
# 2108 : 2 : return;
# 2109 : 2 : }
# 2110 : 29427 : const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
# 2111 : : // disconnect node in case we have reached the outbound limit for serving historical blocks
# 2112 [ + + ]: 29427 : if (m_connman.OutboundTargetReached(true) &&
# 2113 [ + - ][ + + ]: 29427 : (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&
# [ - + ]
# 2114 [ + + ]: 29427 : !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target
# 2115 : 29427 : ) {
# 2116 [ + - ]: 2 : LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom.GetId());
# 2117 : 2 : pfrom.fDisconnect = true;
# 2118 : 2 : return;
# 2119 : 2 : }
# 2120 : : // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
# 2121 [ + + ]: 29425 : if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && (
# 2122 [ + - ][ + + ]: 28432 : (((peer.m_our_services & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) && (m_chainman.ActiveChain().Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
# [ + + ]
# 2123 : 28432 : )) {
# 2124 [ + - ]: 1 : LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, disconnect peer=%d\n", pfrom.GetId());
# 2125 : : //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
# 2126 : 1 : pfrom.fDisconnect = true;
# 2127 : 1 : return;
# 2128 : 1 : }
# 2129 : : // Pruned nodes may have deleted the block, so check whether
# 2130 : : // it's available before trying to send.
# 2131 [ - + ]: 29424 : if (!(pindex->nStatus & BLOCK_HAVE_DATA)) {
# 2132 : 0 : return;
# 2133 : 0 : }
# 2134 : 29424 : std::shared_ptr<const CBlock> pblock;
# 2135 [ + + ][ + + ]: 29424 : if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
# [ + + ]
# 2136 : 1918 : pblock = a_recent_block;
# 2137 [ + + ]: 27506 : } else if (inv.IsMsgWitnessBlk()) {
# 2138 : : // Fast-path: in this case it is possible to serve the block directly from disk,
# 2139 : : // as the network format matches the format on disk
# 2140 : 23503 : std::vector<uint8_t> block_data;
# 2141 [ - + ]: 23503 : if (!ReadRawBlockFromDisk(block_data, pindex->GetBlockPos(), m_chainparams.MessageStart())) {
# 2142 : 0 : assert(!"cannot load block from disk");
# 2143 : 0 : }
# 2144 : 0 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCK, Span{block_data}));
# 2145 : : // Don't set pblock as we've sent the block
# 2146 : 23503 : } else {
# 2147 : : // Send block from disk
# 2148 : 4003 : std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
# 2149 [ - + ]: 4003 : if (!ReadBlockFromDisk(*pblockRead, pindex, m_chainparams.GetConsensus())) {
# 2150 : 0 : assert(!"cannot load block from disk");
# 2151 : 0 : }
# 2152 : 0 : pblock = pblockRead;
# 2153 : 4003 : }
# 2154 [ + + ]: 29424 : if (pblock) {
# 2155 [ + + ]: 5921 : if (inv.IsMsgBlk()) {
# 2156 : 5296 : m_connman.PushMessage(&pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
# 2157 [ + + ]: 5296 : } else if (inv.IsMsgWitnessBlk()) {
# 2158 : 361 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
# 2159 [ + + ]: 361 : } else if (inv.IsMsgFilteredBlk()) {
# 2160 : 7 : bool sendMerkleBlock = false;
# 2161 : 7 : CMerkleBlock merkleBlock;
# 2162 [ + - ]: 7 : if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
# 2163 : 7 : LOCK(tx_relay->m_bloom_filter_mutex);
# 2164 [ + + ]: 7 : if (tx_relay->m_bloom_filter) {
# 2165 : 4 : sendMerkleBlock = true;
# 2166 : 4 : merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
# 2167 : 4 : }
# 2168 : 7 : }
# 2169 [ + + ]: 7 : if (sendMerkleBlock) {
# 2170 : 4 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
# 2171 : : // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
# 2172 : : // This avoids hurting performance by pointlessly requiring a round-trip
# 2173 : : // Note that there is currently no way for a node to request any single transactions we didn't send here -
# 2174 : : // they must either disconnect and retry or request the full block.
# 2175 : : // Thus, the protocol spec specified allows for us to provide duplicate txn here,
# 2176 : : // however we MUST always provide at least what the remote peer needs
# 2177 : 4 : typedef std::pair<unsigned int, uint256> PairType;
# 2178 [ + + ]: 4 : for (PairType& pair : merkleBlock.vMatchedTxn)
# 2179 : 2 : m_connman.PushMessage(&pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
# 2180 : 4 : }
# 2181 : : // else
# 2182 : : // no response
# 2183 [ + - ]: 257 : } else if (inv.IsMsgCmpctBlk()) {
# 2184 : : // If a peer is asking for old blocks, we're almost guaranteed
# 2185 : : // they won't have a useful mempool to match against a compact block,
# 2186 : : // and we don't feel like constructing the object for them, so
# 2187 : : // instead we respond with the full, non-compact block.
# 2188 [ + - ][ + + ]: 257 : if (CanDirectFetch() && pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_CMPCTBLOCK_DEPTH) {
# 2189 [ + + ][ + + ]: 252 : if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
# [ + + ]
# 2190 : 162 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
# 2191 : 162 : } else {
# 2192 : 90 : CBlockHeaderAndShortTxIDs cmpctblock{*pblock};
# 2193 : 90 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::CMPCTBLOCK, cmpctblock));
# 2194 : 90 : }
# 2195 : 252 : } else {
# 2196 : 5 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
# 2197 : 5 : }
# 2198 : 257 : }
# 2199 : 5921 : }
# 2200 : :
# 2201 : 29424 : {
# 2202 : 29424 : LOCK(peer.m_block_inv_mutex);
# 2203 : : // Trigger the peer node to send a getblocks request for the next batch of inventory
# 2204 [ - + ]: 29424 : if (inv.hash == peer.m_continuation_block) {
# 2205 : : // Send immediately. This must send even if redundant,
# 2206 : : // and we want it right after the last block so they don't
# 2207 : : // wait for other stuff first.
# 2208 : 0 : std::vector<CInv> vInv;
# 2209 : 0 : vInv.push_back(CInv(MSG_BLOCK, m_chainman.ActiveChain().Tip()->GetBlockHash()));
# 2210 : 0 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::INV, vInv));
# 2211 : 0 : peer.m_continuation_block.SetNull();
# 2212 : 0 : }
# 2213 : 29424 : }
# 2214 : 29424 : }
# 2215 : :
# 2216 : : CTransactionRef PeerManagerImpl::FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now)
# 2217 : 11401 : {
# 2218 : 11401 : auto txinfo = m_mempool.info(gtxid);
# 2219 [ + + ]: 11401 : if (txinfo.tx) {
# 2220 : : // If a TX could have been INVed in reply to a MEMPOOL request,
# 2221 : : // or is older than UNCONDITIONAL_RELAY_DELAY, permit the request
# 2222 : : // unconditionally.
# 2223 [ + + ][ + + ]: 11230 : if ((mempool_req.count() && txinfo.m_time <= mempool_req) || txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
# [ + - ][ + + ]
# 2224 : 4 : return std::move(txinfo.tx);
# 2225 : 4 : }
# 2226 : 11230 : }
# 2227 : :
# 2228 : 11397 : {
# 2229 : 11397 : LOCK(cs_main);
# 2230 : : // Otherwise, the transaction must have been announced recently.
# 2231 [ + + ]: 11397 : if (State(peer.GetId())->m_recently_announced_invs.contains(gtxid.GetHash())) {
# 2232 : : // If it was, it can be relayed from either the mempool...
# 2233 [ + + ]: 11389 : if (txinfo.tx) return std::move(txinfo.tx);
# 2234 : : // ... or the relay pool.
# 2235 : 163 : auto mi = mapRelay.find(gtxid.GetHash());
# 2236 [ + - ]: 163 : if (mi != mapRelay.end()) return mi->second;
# 2237 : 163 : }
# 2238 : 11397 : }
# 2239 : :
# 2240 : 8 : return {};
# 2241 : 11397 : }
# 2242 : :
# 2243 : : void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
# 2244 : 36305 : {
# 2245 : 36305 : AssertLockNotHeld(cs_main);
# 2246 : :
# 2247 : 36305 : auto tx_relay = peer.GetTxRelay();
# 2248 : :
# 2249 : 36305 : std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
# 2250 : 36305 : std::vector<CInv> vNotFound;
# 2251 : 36305 : const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
# 2252 : :
# 2253 : 36305 : const auto now{GetTime<std::chrono::seconds>()};
# 2254 : : // Get last mempool request time
# 2255 [ + - ]: 36305 : const auto mempool_req = tx_relay != nullptr ? tx_relay->m_last_mempool_req.load() : std::chrono::seconds::min();
# 2256 : :
# 2257 : : // Process as many TX items from the front of the getdata queue as
# 2258 : : // possible, since they're common and it's efficient to batch process
# 2259 : : // them.
# 2260 [ + + ][ + + ]: 47706 : while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) {
# [ + + ]
# 2261 [ - + ]: 11401 : if (interruptMsgProc) return;
# 2262 : : // The send buffer provides backpressure. If there's no space in
# 2263 : : // the buffer, pause processing until the next call.
# 2264 [ - + ]: 11401 : if (pfrom.fPauseSend) break;
# 2265 : :
# 2266 : 11401 : const CInv &inv = *it++;
# 2267 : :
# 2268 [ - + ]: 11401 : if (tx_relay == nullptr) {
# 2269 : : // Ignore GETDATA requests for transactions from block-relay-only
# 2270 : : // peers and peers that asked us not to announce transactions.
# 2271 : 0 : continue;
# 2272 : 0 : }
# 2273 : :
# 2274 : 11401 : CTransactionRef tx = FindTxForGetData(pfrom, ToGenTxid(inv), mempool_req, now);
# 2275 [ + + ]: 11401 : if (tx) {
# 2276 : : // WTX and WITNESS_TX imply we serialize with witness
# 2277 [ - + ]: 11393 : int nSendFlags = (inv.IsMsgTx() ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
# 2278 : 11393 : m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *tx));
# 2279 : 11393 : m_mempool.RemoveUnbroadcastTx(tx->GetHash());
# 2280 : : // As we're going to send tx, make sure its unconfirmed parents are made requestable.
# 2281 : 11393 : std::vector<uint256> parent_ids_to_add;
# 2282 : 11393 : {
# 2283 : 11393 : LOCK(m_mempool.cs);
# 2284 : 11393 : auto txiter = m_mempool.GetIter(tx->GetHash());
# 2285 [ + + ]: 11393 : if (txiter) {
# 2286 : 11228 : const CTxMemPoolEntry::Parents& parents = (*txiter)->GetMemPoolParentsConst();
# 2287 : 11228 : parent_ids_to_add.reserve(parents.size());
# 2288 [ + + ]: 11228 : for (const CTxMemPoolEntry& parent : parents) {
# 2289 [ + - ]: 769 : if (parent.GetTime() > now - UNCONDITIONAL_RELAY_DELAY) {
# 2290 : 769 : parent_ids_to_add.push_back(parent.GetTx().GetHash());
# 2291 : 769 : }
# 2292 : 769 : }
# 2293 : 11228 : }
# 2294 : 11393 : }
# 2295 [ + + ]: 11393 : for (const uint256& parent_txid : parent_ids_to_add) {
# 2296 : : // Relaying a transaction with a recent but unconfirmed parent.
# 2297 [ + + ]: 769 : if (WITH_LOCK(tx_relay->m_tx_inventory_mutex, return !tx_relay->m_tx_inventory_known_filter.contains(parent_txid))) {
# 2298 : 1 : LOCK(cs_main);
# 2299 : 1 : State(pfrom.GetId())->m_recently_announced_invs.insert(parent_txid);
# 2300 : 1 : }
# 2301 : 769 : }
# 2302 : 11393 : } else {
# 2303 : 8 : vNotFound.push_back(inv);
# 2304 : 8 : }
# 2305 : 11401 : }
# 2306 : :
# 2307 : : // Only process one BLOCK item per call, since they're uncommon and can be
# 2308 : : // expensive to process.
# 2309 [ + + ][ + + ]: 36305 : if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
# [ + - ]
# 2310 : 29430 : const CInv &inv = *it++;
# 2311 [ + + ]: 29430 : if (inv.IsGenBlkMsg()) {
# 2312 : 29429 : ProcessGetBlockData(pfrom, peer, inv);
# 2313 : 29429 : }
# 2314 : : // else: If the first item on the queue is an unknown type, we erase it
# 2315 : : // and continue processing the queue on the next call.
# 2316 : 29430 : }
# 2317 : :
# 2318 : 36305 : peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
# 2319 : :
# 2320 [ + + ]: 36305 : if (!vNotFound.empty()) {
# 2321 : : // Let the peer know that we didn't find what it asked for, so it doesn't
# 2322 : : // have to wait around forever.
# 2323 : : // SPV clients care about this message: it's needed when they are
# 2324 : : // recursively walking the dependencies of relevant unconfirmed
# 2325 : : // transactions. SPV clients want to do that because they want to know
# 2326 : : // about (and store and rebroadcast and risk analyze) the dependencies
# 2327 : : // of transactions relevant to them, without having to download the
# 2328 : : // entire memory pool.
# 2329 : : // Also, other nodes can use these messages to automatically request a
# 2330 : : // transaction from some other peer that annnounced it, and stop
# 2331 : : // waiting for us to respond.
# 2332 : : // In normal operation, we often send NOTFOUND messages for parents of
# 2333 : : // transactions that we relay; if a peer is missing a parent, they may
# 2334 : : // assume we have them and request the parents from us.
# 2335 : 2 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
# 2336 : 2 : }
# 2337 : 36305 : }
# 2338 : :
# 2339 : : uint32_t PeerManagerImpl::GetFetchFlags(const Peer& peer) const
# 2340 : 30155 : {
# 2341 : 30155 : uint32_t nFetchFlags = 0;
# 2342 [ + + ]: 30155 : if (CanServeWitnesses(peer)) {
# 2343 : 30153 : nFetchFlags |= MSG_WITNESS_FLAG;
# 2344 : 30153 : }
# 2345 : 30155 : return nFetchFlags;
# 2346 : 30155 : }
# 2347 : :
# 2348 : : void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req)
# 2349 : 2297 : {
# 2350 : 2297 : BlockTransactions resp(req);
# 2351 [ + + ]: 6964 : for (size_t i = 0; i < req.indexes.size(); i++) {
# 2352 [ + + ]: 4668 : if (req.indexes[i] >= block.vtx.size()) {
# 2353 : 1 : Misbehaving(peer, 100, "getblocktxn with out-of-bounds tx indices");
# 2354 : 1 : return;
# 2355 : 1 : }
# 2356 : 4667 : resp.txn[i] = block.vtx[req.indexes[i]];
# 2357 : 4667 : }
# 2358 : :
# 2359 : 2296 : const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
# 2360 : 2296 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCKTXN, resp));
# 2361 : 2296 : }
# 2362 : :
# 2363 : : bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer)
# 2364 : 10622 : {
# 2365 : : // Do these headers have proof-of-work matching what's claimed?
# 2366 [ - + ]: 10622 : if (!HasValidProofOfWork(headers, consensusParams)) {
# 2367 : 0 : Misbehaving(peer, 100, "header with invalid proof of work");
# 2368 : 0 : return false;
# 2369 : 0 : }
# 2370 : :
# 2371 : : // Are these headers connected to each other?
# 2372 [ - + ]: 10622 : if (!CheckHeadersAreContinuous(headers)) {
# 2373 : 0 : Misbehaving(peer, 20, "non-continuous headers sequence");
# 2374 : 0 : return false;
# 2375 : 0 : }
# 2376 : 10622 : return true;
# 2377 : 10622 : }
# 2378 : :
# 2379 : : arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold()
# 2380 : 49515 : {
# 2381 : 49515 : arith_uint256 near_chaintip_work = 0;
# 2382 : 49515 : LOCK(cs_main);
# 2383 [ + - ]: 49515 : if (m_chainman.ActiveChain().Tip() != nullptr) {
# 2384 : 49515 : const CBlockIndex *tip = m_chainman.ActiveChain().Tip();
# 2385 : : // Use a 144 block buffer, so that we'll accept headers that fork from
# 2386 : : // near our tip.
# 2387 : 49515 : near_chaintip_work = tip->nChainWork - std::min<arith_uint256>(144*GetBlockProof(*tip), tip->nChainWork);
# 2388 : 49515 : }
# 2389 : 49515 : return std::max(near_chaintip_work, arith_uint256(nMinimumChainWork));
# 2390 : 49515 : }
# 2391 : :
# 2392 : : /**
# 2393 : : * Special handling for unconnecting headers that might be part of a block
# 2394 : : * announcement.
# 2395 : : *
# 2396 : : * We'll send a getheaders message in response to try to connect the chain.
# 2397 : : *
# 2398 : : * The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
# 2399 : : * don't connect before given DoS points.
# 2400 : : *
# 2401 : : * Once a headers message is received that is valid and does connect,
# 2402 : : * nUnconnectingHeaders gets reset back to 0.
# 2403 : : */
# 2404 : : void PeerManagerImpl::HandleFewUnconnectingHeaders(CNode& pfrom, Peer& peer,
# 2405 : : const std::vector<CBlockHeader>& headers)
# 2406 : 70 : {
# 2407 : 70 : const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
# 2408 : :
# 2409 : 70 : LOCK(cs_main);
# 2410 : 70 : CNodeState *nodestate = State(pfrom.GetId());
# 2411 : :
# 2412 : 70 : nodestate->nUnconnectingHeaders++;
# 2413 : : // Try to fill in the missing headers.
# 2414 [ + - ]: 70 : if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), peer)) {
# 2415 [ + - ]: 70 : LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
# 2416 : 70 : headers[0].GetHash().ToString(),
# 2417 : 70 : headers[0].hashPrevBlock.ToString(),
# 2418 : 70 : m_chainman.m_best_header->nHeight,
# 2419 : 70 : pfrom.GetId(), nodestate->nUnconnectingHeaders);
# 2420 : 70 : }
# 2421 : : // Set hashLastUnknownBlock for this peer, so that if we
# 2422 : : // eventually get the headers - even from a different peer -
# 2423 : : // we can use this peer to download.
# 2424 : 70 : UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash());
# 2425 : :
# 2426 : : // The peer may just be broken, so periodically assign DoS points if this
# 2427 : : // condition persists.
# 2428 [ + + ]: 70 : if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
# 2429 : 5 : Misbehaving(peer, 20, strprintf("%d non-connecting headers", nodestate->nUnconnectingHeaders));
# 2430 : 5 : }
# 2431 : 70 : }
# 2432 : :
# 2433 : : bool PeerManagerImpl::CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const
# 2434 : 10622 : {
# 2435 : 10622 : uint256 hashLastBlock;
# 2436 [ + + ]: 527376 : for (const CBlockHeader& header : headers) {
# 2437 [ + + ][ - + ]: 527376 : if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
# 2438 : 0 : return false;
# 2439 : 0 : }
# 2440 : 527376 : hashLastBlock = header.GetHash();
# 2441 : 527376 : }
# 2442 : 10622 : return true;
# 2443 : 10622 : }
# 2444 : :
# 2445 : : bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers)
# 2446 : 10631 : {
# 2447 [ + + ]: 10631 : if (peer.m_headers_sync) {
# 2448 : 27 : auto result = peer.m_headers_sync->ProcessNextHeaders(headers, headers.size() == MAX_HEADERS_RESULTS);
# 2449 [ + + ]: 27 : if (result.request_more) {
# 2450 : 19 : auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
# 2451 : : // If we were instructed to ask for a locator, it should not be empty.
# 2452 : 19 : Assume(!locator.vHave.empty());
# 2453 [ + - ]: 19 : if (!locator.vHave.empty()) {
# 2454 : : // It should be impossible for the getheaders request to fail,
# 2455 : : // because we should have cleared the last getheaders timestamp
# 2456 : : // when processing the headers that triggered this call. But
# 2457 : : // it may be possible to bypass this via compactblock
# 2458 : : // processing, so check the result before logging just to be
# 2459 : : // safe.
# 2460 : 19 : bool sent_getheaders = MaybeSendGetHeaders(pfrom, locator, peer);
# 2461 [ + - ]: 19 : if (sent_getheaders) {
# 2462 [ + - ]: 19 : LogPrint(BCLog::NET, "more getheaders (from %s) to peer=%d\n",
# 2463 : 19 : locator.vHave.front().ToString(), pfrom.GetId());
# 2464 : 19 : } else {
# 2465 [ # # ]: 0 : LogPrint(BCLog::NET, "error sending next getheaders (from %s) to continue sync with peer=%d\n",
# 2466 : 0 : locator.vHave.front().ToString(), pfrom.GetId());
# 2467 : 0 : }
# 2468 : 19 : }
# 2469 : 19 : }
# 2470 : :
# 2471 [ + + ]: 27 : if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) {
# 2472 : 8 : peer.m_headers_sync.reset(nullptr);
# 2473 : :
# 2474 : : // Delete this peer's entry in m_headers_presync_stats.
# 2475 : : // If this is m_headers_presync_bestpeer, it will be replaced later
# 2476 : : // by the next peer that triggers the else{} branch below.
# 2477 : 8 : LOCK(m_headers_presync_mutex);
# 2478 : 8 : m_headers_presync_stats.erase(pfrom.GetId());
# 2479 : 19 : } else {
# 2480 : : // Build statistics for this peer's sync.
# 2481 : 19 : HeadersPresyncStats stats;
# 2482 : 19 : stats.first = peer.m_headers_sync->GetPresyncWork();
# 2483 [ + + ]: 19 : if (peer.m_headers_sync->GetState() == HeadersSyncState::State::PRESYNC) {
# 2484 : 11 : stats.second = {peer.m_headers_sync->GetPresyncHeight(),
# 2485 : 11 : peer.m_headers_sync->GetPresyncTime()};
# 2486 : 11 : }
# 2487 : :
# 2488 : : // Update statistics in stats.
# 2489 : 19 : LOCK(m_headers_presync_mutex);
# 2490 : 19 : m_headers_presync_stats[pfrom.GetId()] = stats;
# 2491 : 19 : auto best_it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
# 2492 : 19 : bool best_updated = false;
# 2493 [ + + ]: 19 : if (best_it == m_headers_presync_stats.end()) {
# 2494 : : // If the cached best peer is outdated, iterate over all remaining ones (including
# 2495 : : // newly updated one) to find the best one.
# 2496 : 4 : NodeId peer_best{-1};
# 2497 : 4 : const HeadersPresyncStats* stat_best{nullptr};
# 2498 [ + + ]: 4 : for (const auto& [peer, stat] : m_headers_presync_stats) {
# 2499 [ + - ][ # # ]: 4 : if (!stat_best || stat > *stat_best) {
# 2500 : 4 : peer_best = peer;
# 2501 : 4 : stat_best = &stat;
# 2502 : 4 : }
# 2503 : 4 : }
# 2504 : 4 : m_headers_presync_bestpeer = peer_best;
# 2505 : 4 : best_updated = (peer_best == pfrom.GetId());
# 2506 [ + - ][ # # ]: 15 : } else if (best_it->first == pfrom.GetId() || stats > best_it->second) {
# 2507 : : // pfrom was and remains the best peer, or pfrom just became best.
# 2508 : 15 : m_headers_presync_bestpeer = pfrom.GetId();
# 2509 : 15 : best_updated = true;
# 2510 : 15 : }
# 2511 [ + - ][ + + ]: 19 : if (best_updated && stats.second.has_value()) {
# 2512 : : // If the best peer updated, and it is in its first phase, signal.
# 2513 : 11 : m_headers_presync_should_signal = true;
# 2514 : 11 : }
# 2515 : 19 : }
# 2516 : :
# 2517 [ + - ]: 27 : if (result.success) {
# 2518 : : // We only overwrite the headers passed in if processing was
# 2519 : : // successful.
# 2520 : 27 : headers.swap(result.pow_validated_headers);
# 2521 : 27 : }
# 2522 : :
# 2523 : 27 : return result.success;
# 2524 : 27 : }
# 2525 : : // Either we didn't have a sync in progress, or something went wrong
# 2526 : : // processing these headers, or we are returning headers to the caller to
# 2527 : : // process.
# 2528 : 10604 : return false;
# 2529 : 10631 : }
# 2530 : :
# 2531 : : bool PeerManagerImpl::TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex* chain_start_header, std::vector<CBlockHeader>& headers)
# 2532 : 4005 : {
# 2533 : : // Calculate the total work on this chain.
# 2534 : 4005 : arith_uint256 total_work = chain_start_header->nChainWork + CalculateHeadersWork(headers);
# 2535 : :
# 2536 : : // Our dynamic anti-DoS threshold (minimum work required on a headers chain
# 2537 : : // before we'll store it)
# 2538 : 4005 : arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
# 2539 : :
# 2540 : : // Avoid DoS via low-difficulty-headers by only processing if the headers
# 2541 : : // are part of a chain with sufficient work.
# 2542 [ + + ]: 4005 : if (total_work < minimum_chain_work) {
# 2543 : : // Only try to sync with this peer if their headers message was full;
# 2544 : : // otherwise they don't have more headers after this so no point in
# 2545 : : // trying to sync their too-little-work chain.
# 2546 [ + + ]: 544 : if (headers.size() == MAX_HEADERS_RESULTS) {
# 2547 : : // Note: we could advance to the last header in this set that is
# 2548 : : // known to us, rather than starting at the first header (which we
# 2549 : : // may already have); however this is unlikely to matter much since
# 2550 : : // ProcessHeadersMessage() already handles the case where all
# 2551 : : // headers in a received message are already known and are
# 2552 : : // ancestors of m_best_header or chainActive.Tip(), by skipping
# 2553 : : // this logic in that case. So even if the first header in this set
# 2554 : : // of headers is known, some header in this set must be new, so
# 2555 : : // advancing to the first unknown header would be a small effect.
# 2556 : 9 : LOCK(peer.m_headers_sync_mutex);
# 2557 : 9 : peer.m_headers_sync.reset(new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(),
# 2558 : 9 : chain_start_header, minimum_chain_work));
# 2559 : :
# 2560 : : // Now a HeadersSyncState object for tracking this synchronization is created,
# 2561 : : // process the headers using it as normal.
# 2562 : 9 : return IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
# 2563 : 535 : } else {
# 2564 [ + - ]: 535 : LogPrint(BCLog::NET, "Ignoring low-work chain (height=%u) from peer=%d\n", chain_start_header->nHeight + headers.size(), pfrom.GetId());
# 2565 : : // Since this is a low-work headers chain, no further processing is required.
# 2566 : 535 : headers = {};
# 2567 : 535 : return true;
# 2568 : 535 : }
# 2569 : 544 : }
# 2570 : 3461 : return false;
# 2571 : 4005 : }
# 2572 : :
# 2573 : : bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex* header)
# 2574 : 10537 : {
# 2575 [ + + ]: 10537 : if (header == nullptr) {
# 2576 : 3999 : return false;
# 2577 [ + - ][ + + ]: 6538 : } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) {
# 2578 : 6529 : return true;
# 2579 [ - + ]: 6529 : } else if (m_chainman.ActiveChain().Contains(header)) {
# 2580 : 0 : return true;
# 2581 : 0 : }
# 2582 : 9 : return false;
# 2583 : 10537 : }
# 2584 : :
# 2585 : : bool PeerManagerImpl::MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer)
# 2586 : 2194 : {
# 2587 : 2194 : const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
# 2588 : :
# 2589 : 2194 : const auto current_time = NodeClock::now();
# 2590 : :
# 2591 : : // Only allow a new getheaders message to go out if we don't have a recent
# 2592 : : // one already in-flight
# 2593 [ + + ]: 2194 : if (current_time - peer.m_last_getheaders_timestamp > HEADERS_RESPONSE_TIME) {
# 2594 : 1940 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, locator, uint256()));
# 2595 : 1940 : peer.m_last_getheaders_timestamp = current_time;
# 2596 : 1940 : return true;
# 2597 : 1940 : }
# 2598 : 254 : return false;
# 2599 : 2194 : }
# 2600 : :
# 2601 : : /*
# 2602 : : * Given a new headers tip ending in pindexLast, potentially request blocks towards that tip.
# 2603 : : * We require that the given tip have at least as much work as our tip, and for
# 2604 : : * our current tip to be "close to synced" (see CanDirectFetch()).
# 2605 : : */
# 2606 : : void PeerManagerImpl::HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex* pindexLast)
# 2607 : 9974 : {
# 2608 : 9974 : const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
# 2609 : :
# 2610 : 9974 : LOCK(cs_main);
# 2611 : 9974 : CNodeState *nodestate = State(pfrom.GetId());
# 2612 : :
# 2613 [ + + ][ + - ]: 9974 : if (CanDirectFetch() && pindexLast->IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= pindexLast->nChainWork) {
# [ + + ]
# 2614 : :
# 2615 : 9072 : std::vector<const CBlockIndex*> vToFetch;
# 2616 : 9072 : const CBlockIndex *pindexWalk = pindexLast;
# 2617 : : // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
# 2618 [ + - ][ + + ]: 104027 : while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
# [ + + ]
# 2619 [ + + ][ + + ]: 94955 : if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
# 2620 [ + + ]: 94955 : !IsBlockRequested(pindexWalk->GetBlockHash()) &&
# 2621 [ + + ][ + + ]: 94955 : (!DeploymentActiveAt(*pindexWalk, m_chainman, Consensus::DEPLOYMENT_SEGWIT) || CanServeWitnesses(peer))) {
# 2622 : : // We don't have this block, and it's not yet in flight.
# 2623 : 60050 : vToFetch.push_back(pindexWalk);
# 2624 : 60050 : }
# 2625 : 94955 : pindexWalk = pindexWalk->pprev;
# 2626 : 94955 : }
# 2627 : : // If pindexWalk still isn't on our main chain, we're looking at a
# 2628 : : // very large reorg at a time we think we're close to caught up to
# 2629 : : // the main chain -- this shouldn't really happen. Bail out on the
# 2630 : : // direct fetch and rely on parallel download instead.
# 2631 [ + + ]: 9072 : if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
# 2632 [ + - ]: 3077 : LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
# 2633 : 3077 : pindexLast->GetBlockHash().ToString(),
# 2634 : 3077 : pindexLast->nHeight);
# 2635 : 5995 : } else {
# 2636 : 5995 : std::vector<CInv> vGetData;
# 2637 : : // Download as much as possible, from earliest to latest.
# 2638 [ + + ]: 5995 : for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
# 2639 [ + + ]: 4025 : if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
# 2640 : : // Can't download any more from this peer
# 2641 : 580 : break;
# 2642 : 580 : }
# 2643 : 3445 : uint32_t nFetchFlags = GetFetchFlags(peer);
# 2644 : 3445 : vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
# 2645 : 3445 : BlockRequested(pfrom.GetId(), *pindex);
# 2646 [ + - ]: 3445 : LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
# 2647 : 3445 : pindex->GetBlockHash().ToString(), pfrom.GetId());
# 2648 : 3445 : }
# 2649 [ + + ]: 5995 : if (vGetData.size() > 1) {
# 2650 [ + - ]: 517 : LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
# 2651 : 517 : pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
# 2652 : 517 : }
# 2653 [ + + ]: 5995 : if (vGetData.size() > 0) {
# 2654 [ + + ]: 2421 : if (!m_ignore_incoming_txs &&
# 2655 [ + + ]: 2421 : nodestate->m_provides_cmpctblocks &&
# 2656 [ + + ]: 2421 : vGetData.size() == 1 &&
# 2657 [ + + ]: 2421 : mapBlocksInFlight.size() == 1 &&
# 2658 [ + + ]: 2421 : pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
# 2659 : : // In any case, we want to download using a compact block, not a regular one
# 2660 : 257 : vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
# 2661 : 257 : }
# 2662 : 2421 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
# 2663 : 2421 : }
# 2664 : 5995 : }
# 2665 : 9072 : }
# 2666 : 9974 : }
# 2667 : :
# 2668 : : /**
# 2669 : : * Given receipt of headers from a peer ending in pindexLast, along with
# 2670 : : * whether that header was new and whether the headers message was full,
# 2671 : : * update the state we keep for the peer.
# 2672 : : */
# 2673 : : void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(CNode& pfrom,
# 2674 : : const CBlockIndex *pindexLast, bool received_new_header, bool may_have_more_headers)
# 2675 : 9974 : {
# 2676 : 9974 : LOCK(cs_main);
# 2677 : 9974 : CNodeState *nodestate = State(pfrom.GetId());
# 2678 [ + + ]: 9974 : if (nodestate->nUnconnectingHeaders > 0) {
# 2679 [ + - ]: 11 : LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom.GetId(), nodestate->nUnconnectingHeaders);
# 2680 : 11 : }
# 2681 : 9974 : nodestate->nUnconnectingHeaders = 0;
# 2682 : :
# 2683 : 9974 : assert(pindexLast);
# 2684 : 0 : UpdateBlockAvailability(pfrom.GetId(), pindexLast->GetBlockHash());
# 2685 : :
# 2686 : : // From here, pindexBestKnownBlock should be guaranteed to be non-null,
# 2687 : : // because it is set in UpdateBlockAvailability. Some nullptr checks
# 2688 : : // are still present, however, as belt-and-suspenders.
# 2689 : :
# 2690 [ + + ][ + + ]: 9974 : if (received_new_header && pindexLast->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
# 2691 : 4932 : nodestate->m_last_block_announcement = GetTime();
# 2692 : 4932 : }
# 2693 : :
# 2694 : : // If we're in IBD, we want outbound peers that will serve us a useful
# 2695 : : // chain. Disconnect peers that are on chains with insufficient work.
# 2696 [ + + ][ + + ]: 9974 : if (m_chainman.ActiveChainstate().IsInitialBlockDownload() && !may_have_more_headers) {
# 2697 : : // If the peer has no more headers to give us, then we know we have
# 2698 : : // their tip.
# 2699 [ + - ][ - + ]: 411 : if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
# 2700 : : // This peer has too little work on their headers chain to help
# 2701 : : // us sync -- disconnect if it is an outbound disconnection
# 2702 : : // candidate.
# 2703 : : // Note: We compare their tip to nMinimumChainWork (rather than
# 2704 : : // m_chainman.ActiveChain().Tip()) because we won't start block download
# 2705 : : // until we have a headers chain that has at least
# 2706 : : // nMinimumChainWork, even if a peer has a chain past our tip,
# 2707 : : // as an anti-DoS measure.
# 2708 [ # # ]: 0 : if (pfrom.IsOutboundOrBlockRelayConn()) {
# 2709 : 0 : LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom.GetId());
# 2710 : 0 : pfrom.fDisconnect = true;
# 2711 : 0 : }
# 2712 : 0 : }
# 2713 : 411 : }
# 2714 : :
# 2715 : : // If this is an outbound full-relay peer, check to see if we should protect
# 2716 : : // it from the bad/lagging chain logic.
# 2717 : : // Note that outbound block-relay peers are excluded from this protection, and
# 2718 : : // thus always subject to eviction under the bad/lagging chain logic.
# 2719 : : // See ChainSyncTimeoutState.
# 2720 [ + - ][ - + ]: 9974 : if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) {
# [ # # ]
# 2721 [ # # ][ # # ]: 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) {
# [ # # ]
# 2722 [ # # ]: 0 : LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId());
# 2723 : 0 : nodestate->m_chain_sync.m_protect = true;
# 2724 : 0 : ++m_outbound_peers_with_protect_from_disconnect;
# 2725 : 0 : }
# 2726 : 0 : }
# 2727 : 9974 : }
# 2728 : :
# 2729 : : void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, Peer& peer,
# 2730 : : std::vector<CBlockHeader>&& headers,
# 2731 : : bool via_compact_block)
# 2732 : 10866 : {
# 2733 : 10866 : size_t nCount = headers.size();
# 2734 : :
# 2735 [ + + ]: 10866 : if (nCount == 0) {
# 2736 : : // Nothing interesting. Stop asking this peers for more headers.
# 2737 : : // If we were in the middle of headers sync, receiving an empty headers
# 2738 : : // message suggests that the peer suddenly has nothing to give us
# 2739 : : // (perhaps it reorged to our chain). Clear download state for this peer.
# 2740 : 244 : LOCK(peer.m_headers_sync_mutex);
# 2741 [ - + ]: 244 : if (peer.m_headers_sync) {
# 2742 : 0 : peer.m_headers_sync.reset(nullptr);
# 2743 : 0 : LOCK(m_headers_presync_mutex);
# 2744 : 0 : m_headers_presync_stats.erase(pfrom.GetId());
# 2745 : 0 : }
# 2746 : 244 : return;
# 2747 : 244 : }
# 2748 : :
# 2749 : : // Before we do any processing, make sure these pass basic sanity checks.
# 2750 : : // We'll rely on headers having valid proof-of-work further down, as an
# 2751 : : // anti-DoS criteria (note: this check is required before passing any
# 2752 : : // headers into HeadersSyncState).
# 2753 [ - + ]: 10622 : if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) {
# 2754 : : // Misbehaving() calls are handled within CheckHeadersPoW(), so we can
# 2755 : : // just return. (Note that even if a header is announced via compact
# 2756 : : // block, the header itself should be valid, so this type of error can
# 2757 : : // always be punished.)
# 2758 : 0 : return;
# 2759 : 0 : }
# 2760 : :
# 2761 : 10622 : const CBlockIndex *pindexLast = nullptr;
# 2762 : :
# 2763 : : // We'll set already_validated_work to true if these headers are
# 2764 : : // successfully processed as part of a low-work headers sync in progress
# 2765 : : // (either in PRESYNC or REDOWNLOAD phase).
# 2766 : : // If true, this will mean that any headers returned to us (ie during
# 2767 : : // REDOWNLOAD) can be validated without further anti-DoS checks.
# 2768 : 10622 : bool already_validated_work = false;
# 2769 : :
# 2770 : : // If we're in the middle of headers sync, let it do its magic.
# 2771 : 10622 : bool have_headers_sync = false;
# 2772 : 10622 : {
# 2773 : 10622 : LOCK(peer.m_headers_sync_mutex);
# 2774 : :
# 2775 : 10622 : already_validated_work = IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
# 2776 : :
# 2777 : : // The headers we passed in may have been:
# 2778 : : // - untouched, perhaps if no headers-sync was in progress, or some
# 2779 : : // failure occurred
# 2780 : : // - erased, such as if the headers were successfully processed and no
# 2781 : : // additional headers processing needs to take place (such as if we
# 2782 : : // are still in PRESYNC)
# 2783 : : // - replaced with headers that are now ready for validation, such as
# 2784 : : // during the REDOWNLOAD phase of a low-work headers sync.
# 2785 : : // So just check whether we still have headers that we need to process,
# 2786 : : // or not.
# 2787 [ + + ]: 10622 : if (headers.empty()) {
# 2788 : 15 : return;
# 2789 : 15 : }
# 2790 : :
# 2791 : 10607 : have_headers_sync = !!peer.m_headers_sync;
# 2792 : 10607 : }
# 2793 : :
# 2794 : : // Do these headers connect to something in our block index?
# 2795 : 10607 : const CBlockIndex *chain_start_header{WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock))};
# 2796 : 10607 : bool headers_connect_blockindex{chain_start_header != nullptr};
# 2797 : :
# 2798 [ + + ]: 10607 : if (!headers_connect_blockindex) {
# 2799 [ + - ]: 70 : if (nCount <= MAX_BLOCKS_TO_ANNOUNCE) {
# 2800 : : // If this looks like it could be a BIP 130 block announcement, use
# 2801 : : // special logic for handling headers that don't connect, as this
# 2802 : : // could be benign.
# 2803 : 70 : HandleFewUnconnectingHeaders(pfrom, peer, headers);
# 2804 : 70 : } else {
# 2805 : 0 : Misbehaving(peer, 10, "invalid header received");
# 2806 : 0 : }
# 2807 : 70 : return;
# 2808 : 70 : }
# 2809 : :
# 2810 : : // If the headers we received are already in memory and an ancestor of
# 2811 : : // m_best_header or our tip, skip anti-DoS checks. These headers will not
# 2812 : : // use any more memory (and we are not leaking information that could be
# 2813 : : // used to fingerprint us).
# 2814 : 10537 : const CBlockIndex *last_received_header{nullptr};
# 2815 : 10537 : {
# 2816 : 10537 : LOCK(cs_main);
# 2817 : 10537 : last_received_header = m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash());
# 2818 [ + + ]: 10537 : if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
# 2819 : 6529 : already_validated_work = true;
# 2820 : 6529 : }
# 2821 : 10537 : }
# 2822 : :
# 2823 : : // At this point, the headers connect to something in our block index.
# 2824 : : // Do anti-DoS checks to determine if we should process or store for later
# 2825 : : // processing.
# 2826 [ + + ][ + + ]: 10537 : if (!already_validated_work && TryLowWorkHeadersSync(peer, pfrom,
# 2827 : 4005 : chain_start_header, headers)) {
# 2828 : : // If we successfully started a low-work headers sync, then there
# 2829 : : // should be no headers to process any further.
# 2830 : 544 : Assume(headers.empty());
# 2831 : 544 : return;
# 2832 : 544 : }
# 2833 : :
# 2834 : : // At this point, we have a set of headers with sufficient work on them
# 2835 : : // which can be processed.
# 2836 : :
# 2837 : : // If we don't have the last header, then this peer will have given us
# 2838 : : // something new (if these headers are valid).
# 2839 : 9993 : bool received_new_header{last_received_header != nullptr};
# 2840 : :
# 2841 : : // Now process all the headers.
# 2842 : 9993 : BlockValidationState state;
# 2843 [ + + ]: 9993 : if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true, state, &pindexLast)) {
# 2844 [ + - ]: 19 : if (state.IsInvalid()) {
# 2845 : 19 : MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received");
# 2846 : 19 : return;
# 2847 : 19 : }
# 2848 : 19 : }
# 2849 : 9974 : Assume(pindexLast);
# 2850 : :
# 2851 : : // Consider fetching more headers if we are not using our headers-sync mechanism.
# 2852 [ + + ][ + - ]: 9974 : if (nCount == MAX_HEADERS_RESULTS && !have_headers_sync) {
# 2853 : : // Headers message had its maximum size; the peer may have more headers.
# 2854 [ + - ]: 10 : if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) {
# 2855 [ + - ]: 10 : LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
# 2856 : 10 : pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
# 2857 : 10 : }
# 2858 : 10 : }
# 2859 : :
# 2860 : 9974 : UpdatePeerStateForReceivedHeaders(pfrom, pindexLast, received_new_header, nCount == MAX_HEADERS_RESULTS);
# 2861 : :
# 2862 : : // Consider immediately downloading blocks.
# 2863 : 9974 : HeadersDirectFetchBlocks(pfrom, peer, pindexLast);
# 2864 : :
# 2865 : 9974 : return;
# 2866 : 9993 : }
# 2867 : :
# 2868 : : /**
# 2869 : : * Reconsider orphan transactions after a parent has been accepted to the mempool.
# 2870 : : *
# 2871 : : * @param[in,out] orphan_work_set The set of orphan transactions to reconsider. Generally only one
# 2872 : : * orphan will be reconsidered on each call of this function. This set
# 2873 : : * may be added to if accepting an orphan causes its children to be
# 2874 : : * reconsidered.
# 2875 : : */
# 2876 : : void PeerManagerImpl::ProcessOrphanTx(std::set<uint256>& orphan_work_set)
# 2877 : 10785 : {
# 2878 : 10785 : AssertLockHeld(cs_main);
# 2879 : 10785 : AssertLockHeld(g_cs_orphans);
# 2880 : :
# 2881 [ + + ]: 10785 : while (!orphan_work_set.empty()) {
# 2882 : 5 : const uint256 orphanHash = *orphan_work_set.begin();
# 2883 : 5 : orphan_work_set.erase(orphan_work_set.begin());
# 2884 : :
# 2885 : 5 : const auto [porphanTx, from_peer] = m_orphanage.GetTx(orphanHash);
# 2886 [ - + ]: 5 : if (porphanTx == nullptr) continue;
# 2887 : :
# 2888 : 5 : const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx);
# 2889 : 5 : const TxValidationState& state = result.m_state;
# 2890 : :
# 2891 [ + + ]: 5 : if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
# 2892 [ + - ]: 3 : LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
# 2893 : 3 : RelayTransaction(orphanHash, porphanTx->GetWitnessHash());
# 2894 : 3 : m_orphanage.AddChildrenToWorkSet(*porphanTx, orphan_work_set);
# 2895 : 3 : m_orphanage.EraseTx(orphanHash);
# 2896 [ - + ]: 3 : for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) {
# 2897 : 0 : AddToCompactExtraTransactions(removedTx);
# 2898 : 0 : }
# 2899 : 3 : break;
# 2900 [ + - ]: 3 : } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) {
# 2901 [ + - ]: 2 : if (state.IsInvalid()) {
# 2902 [ + - ]: 2 : LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s from peer=%d. %s\n",
# 2903 : 2 : orphanHash.ToString(),
# 2904 : 2 : from_peer,
# 2905 : 2 : state.ToString());
# 2906 : : // Maybe punish peer that gave us an invalid orphan tx
# 2907 : 2 : MaybePunishNodeForTx(from_peer, state);
# 2908 : 2 : }
# 2909 : : // Has inputs but not accepted to mempool
# 2910 : : // Probably non-standard or insufficient fee
# 2911 [ + - ]: 2 : LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
# 2912 [ + - ]: 2 : if (state.GetResult() != TxValidationResult::TX_WITNESS_STRIPPED) {
# 2913 : : // We can add the wtxid of this transaction to our reject filter.
# 2914 : : // Do not add txids of witness transactions or witness-stripped
# 2915 : : // transactions to the filter, as they can have been malleated;
# 2916 : : // adding such txids to the reject filter would potentially
# 2917 : : // interfere with relay of valid transactions from peers that
# 2918 : : // do not support wtxid-based relay. See
# 2919 : : // https://github.com/bitcoin/bitcoin/issues/8279 for details.
# 2920 : : // We can remove this restriction (and always add wtxids to
# 2921 : : // the filter even for witness stripped transactions) once
# 2922 : : // wtxid-based relay is broadly deployed.
# 2923 : : // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
# 2924 : : // for concerns around weakening security of unupgraded nodes
# 2925 : : // if we start doing this too early.
# 2926 : 2 : m_recent_rejects.insert(porphanTx->GetWitnessHash());
# 2927 : : // If the transaction failed for TX_INPUTS_NOT_STANDARD,
# 2928 : : // then we know that the witness was irrelevant to the policy
# 2929 : : // failure, since this check depends only on the txid
# 2930 : : // (the scriptPubKey being spent is covered by the txid).
# 2931 : : // Add the txid to the reject filter to prevent repeated
# 2932 : : // processing of this transaction in the event that child
# 2933 : : // transactions are later received (resulting in
# 2934 : : // parent-fetching by txid via the orphan-handling logic).
# 2935 [ - + ][ # # ]: 2 : if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && porphanTx->GetWitnessHash() != porphanTx->GetHash()) {
# 2936 : : // We only add the txid if it differs from the wtxid, to
# 2937 : : // avoid wasting entries in the rolling bloom filter.
# 2938 : 0 : m_recent_rejects.insert(porphanTx->GetHash());
# 2939 : 0 : }
# 2940 : 2 : }
# 2941 : 2 : m_orphanage.EraseTx(orphanHash);
# 2942 : 2 : break;
# 2943 : 2 : }
# 2944 : 5 : }
# 2945 : 10785 : }
# 2946 : :
# 2947 : : bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& node, Peer& peer,
# 2948 : : BlockFilterType filter_type, uint32_t start_height,
# 2949 : : const uint256& stop_hash, uint32_t max_height_diff,
# 2950 : : const CBlockIndex*& stop_index,
# 2951 : : BlockFilterIndex*& filter_index)
# 2952 : 14 : {
# 2953 : 14 : const bool supported_filter_type =
# 2954 [ + + ]: 14 : (filter_type == BlockFilterType::BASIC &&
# 2955 [ + + ]: 14 : (peer.m_our_services & NODE_COMPACT_FILTERS));
# 2956 [ + + ]: 14 : if (!supported_filter_type) {
# 2957 [ + - ]: 4 : LogPrint(BCLog::NET, "peer %d requested unsupported block filter type: %d\n",
# 2958 : 4 : node.GetId(), static_cast<uint8_t>(filter_type));
# 2959 : 4 : node.fDisconnect = true;
# 2960 : 4 : return false;
# 2961 : 4 : }
# 2962 : :
# 2963 : 10 : {
# 2964 : 10 : LOCK(cs_main);
# 2965 : 10 : stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
# 2966 : :
# 2967 : : // Check that the stop block exists and the peer would be allowed to fetch it.
# 2968 [ + + ][ - + ]: 10 : if (!stop_index || !BlockRequestAllowed(stop_index)) {
# 2969 [ + - ]: 1 : LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
# 2970 : 1 : node.GetId(), stop_hash.ToString());
# 2971 : 1 : node.fDisconnect = true;
# 2972 : 1 : return false;
# 2973 : 1 : }
# 2974 : 10 : }
# 2975 : :
# 2976 : 9 : uint32_t stop_height = stop_index->nHeight;
# 2977 [ - + ]: 9 : if (start_height > stop_height) {
# 2978 [ # # ]: 0 : LogPrint(BCLog::NET, "peer %d sent invalid getcfilters/getcfheaders with " /* Continued */
# 2979 : 0 : "start height %d and stop height %d\n",
# 2980 : 0 : node.GetId(), start_height, stop_height);
# 2981 : 0 : node.fDisconnect = true;
# 2982 : 0 : return false;
# 2983 : 0 : }
# 2984 [ + + ]: 9 : if (stop_height - start_height >= max_height_diff) {
# 2985 [ + - ]: 2 : LogPrint(BCLog::NET, "peer %d requested too many cfilters/cfheaders: %d / %d\n",
# 2986 : 2 : node.GetId(), stop_height - start_height + 1, max_height_diff);
# 2987 : 2 : node.fDisconnect = true;
# 2988 : 2 : return false;
# 2989 : 2 : }
# 2990 : :
# 2991 : 7 : filter_index = GetBlockFilterIndex(filter_type);
# 2992 [ - + ]: 7 : if (!filter_index) {
# 2993 [ # # ]: 0 : LogPrint(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type));
# 2994 : 0 : return false;
# 2995 : 0 : }
# 2996 : :
# 2997 : 7 : return true;
# 2998 : 7 : }
# 2999 : :
# 3000 : : void PeerManagerImpl::ProcessGetCFilters(CNode& node,Peer& peer, CDataStream& vRecv)
# 3001 : 4 : {
# 3002 : 4 : uint8_t filter_type_ser;
# 3003 : 4 : uint32_t start_height;
# 3004 : 4 : uint256 stop_hash;
# 3005 : :
# 3006 : 4 : vRecv >> filter_type_ser >> start_height >> stop_hash;
# 3007 : :
# 3008 : 4 : const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
# 3009 : :
# 3010 : 4 : const CBlockIndex* stop_index;
# 3011 : 4 : BlockFilterIndex* filter_index;
# 3012 [ + + ]: 4 : if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
# 3013 : 4 : MAX_GETCFILTERS_SIZE, stop_index, filter_index)) {
# 3014 : 2 : return;
# 3015 : 2 : }
# 3016 : :
# 3017 : 2 : std::vector<BlockFilter> filters;
# 3018 [ - + ]: 2 : if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
# 3019 [ # # ]: 0 : LogPrint(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
# 3020 : 0 : BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
# 3021 : 0 : return;
# 3022 : 0 : }
# 3023 : :
# 3024 [ + + ]: 11 : for (const auto& filter : filters) {
# 3025 : 11 : CSerializedNetMsg msg = CNetMsgMaker(node.GetCommonVersion())
# 3026 : 11 : .Make(NetMsgType::CFILTER, filter);
# 3027 : 11 : m_connman.PushMessage(&node, std::move(msg));
# 3028 : 11 : }
# 3029 : 2 : }
# 3030 : :
# 3031 : : void PeerManagerImpl::ProcessGetCFHeaders(CNode& node, Peer& peer, CDataStream& vRecv)
# 3032 : 4 : {
# 3033 : 4 : uint8_t filter_type_ser;
# 3034 : 4 : uint32_t start_height;
# 3035 : 4 : uint256 stop_hash;
# 3036 : :
# 3037 : 4 : vRecv >> filter_type_ser >> start_height >> stop_hash;
# 3038 : :
# 3039 : 4 : const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
# 3040 : :
# 3041 : 4 : const CBlockIndex* stop_index;
# 3042 : 4 : BlockFilterIndex* filter_index;
# 3043 [ + + ]: 4 : if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
# 3044 : 4 : MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) {
# 3045 : 2 : return;
# 3046 : 2 : }
# 3047 : :
# 3048 : 2 : uint256 prev_header;
# 3049 [ + - ]: 2 : if (start_height > 0) {
# 3050 : 2 : const CBlockIndex* const prev_block =
# 3051 : 2 : stop_index->GetAncestor(static_cast<int>(start_height - 1));
# 3052 [ - + ]: 2 : if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
# 3053 [ # # ]: 0 : LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
# 3054 : 0 : BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString());
# 3055 : 0 : return;
# 3056 : 0 : }
# 3057 : 2 : }
# 3058 : :
# 3059 : 2 : std::vector<uint256> filter_hashes;
# 3060 [ - + ]: 2 : if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) {
# 3061 [ # # ]: 0 : LogPrint(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
# 3062 : 0 : BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
# 3063 : 0 : return;
# 3064 : 0 : }
# 3065 : :
# 3066 : 2 : CSerializedNetMsg msg = CNetMsgMaker(node.GetCommonVersion())
# 3067 : 2 : .Make(NetMsgType::CFHEADERS,
# 3068 : 2 : filter_type_ser,
# 3069 : 2 : stop_index->GetBlockHash(),
# 3070 : 2 : prev_header,
# 3071 : 2 : filter_hashes);
# 3072 : 2 : m_connman.PushMessage(&node, std::move(msg));
# 3073 : 2 : }
# 3074 : :
# 3075 : : void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, CDataStream& vRecv)
# 3076 : 6 : {
# 3077 : 6 : uint8_t filter_type_ser;
# 3078 : 6 : uint256 stop_hash;
# 3079 : :
# 3080 : 6 : vRecv >> filter_type_ser >> stop_hash;
# 3081 : :
# 3082 : 6 : const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
# 3083 : :
# 3084 : 6 : const CBlockIndex* stop_index;
# 3085 : 6 : BlockFilterIndex* filter_index;
# 3086 [ + + ]: 6 : if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash,
# 3087 : 6 : /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
# 3088 : 6 : stop_index, filter_index)) {
# 3089 : 3 : return;
# 3090 : 3 : }
# 3091 : :
# 3092 : 3 : std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
# 3093 : :
# 3094 : : // Populate headers.
# 3095 : 3 : const CBlockIndex* block_index = stop_index;
# 3096 [ + + ]: 7 : for (int i = headers.size() - 1; i >= 0; i--) {
# 3097 : 4 : int height = (i + 1) * CFCHECKPT_INTERVAL;
# 3098 : 4 : block_index = block_index->GetAncestor(height);
# 3099 : :
# 3100 [ - + ]: 4 : if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
# 3101 [ # # ]: 0 : LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
# 3102 : 0 : BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());
# 3103 : 0 : return;
# 3104 : 0 : }
# 3105 : 4 : }
# 3106 : :
# 3107 : 3 : CSerializedNetMsg msg = CNetMsgMaker(node.GetCommonVersion())
# 3108 : 3 : .Make(NetMsgType::CFCHECKPT,
# 3109 : 3 : filter_type_ser,
# 3110 : 3 : stop_index->GetBlockHash(),
# 3111 : 3 : headers);
# 3112 : 3 : m_connman.PushMessage(&node, std::move(msg));
# 3113 : 3 : }
# 3114 : :
# 3115 : : void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)
# 3116 : 41867 : {
# 3117 : 41867 : bool new_block{false};
# 3118 : 41867 : m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block);
# 3119 [ + + ]: 41867 : if (new_block) {
# 3120 : 41108 : node.m_last_block_time = GetTime<std::chrono::seconds>();
# 3121 : 41108 : } else {
# 3122 : 759 : LOCK(cs_main);
# 3123 : 759 : mapBlockSource.erase(block->GetHash());
# 3124 : 759 : }
# 3125 : 41867 : }
# 3126 : :
# 3127 : : void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
# 3128 : : const std::chrono::microseconds time_received,
# 3129 : : const std::atomic<bool>& interruptMsgProc)
# 3130 : 138534 : {
# 3131 [ + - ]: 138534 : LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
# 3132 : :
# 3133 : 138534 : PeerRef peer = GetPeerRef(pfrom.GetId());
# 3134 [ - + ]: 138534 : if (peer == nullptr) return;
# 3135 : :
# 3136 [ + + ]: 138534 : if (msg_type == NetMsgType::VERSION) {
# 3137 [ + + ]: 1163 : if (pfrom.nVersion != 0) {
# 3138 [ + - ]: 1 : LogPrint(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId());
# 3139 : 1 : return;
# 3140 : 1 : }
# 3141 : :
# 3142 : 1162 : int64_t nTime;
# 3143 : 1162 : CService addrMe;
# 3144 : 1162 : uint64_t nNonce = 1;
# 3145 : 1162 : ServiceFlags nServices;
# 3146 : 1162 : int nVersion;
# 3147 : 1162 : std::string cleanSubVer;
# 3148 : 1162 : int starting_height = -1;
# 3149 : 1162 : bool fRelay = true;
# 3150 : :
# 3151 : 1162 : vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
# 3152 [ - + ]: 1162 : if (nTime < 0) {
# 3153 : 0 : nTime = 0;
# 3154 : 0 : }
# 3155 : 1162 : vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer
# 3156 : 1162 : vRecv >> addrMe;
# 3157 [ + + ]: 1162 : if (!pfrom.IsInboundConn())
# 3158 : 415 : {
# 3159 : 415 : m_addrman.SetServices(pfrom.addr, nServices);
# 3160 : 415 : }
# 3161 [ + + ][ - + ]: 1162 : if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices))
# 3162 : 0 : {
# 3163 [ # # ]: 0 : LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom.GetId(), nServices, GetDesirableServiceFlags(nServices));
# 3164 : 0 : pfrom.fDisconnect = true;
# 3165 : 0 : return;
# 3166 : 0 : }
# 3167 : :
# 3168 [ + + ]: 1162 : if (nVersion < MIN_PEER_PROTO_VERSION) {
# 3169 : : // disconnect from peers older than this proto version
# 3170 [ + - ]: 1 : LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom.GetId(), nVersion);
# 3171 : 1 : pfrom.fDisconnect = true;
# 3172 : 1 : return;
# 3173 : 1 : }
# 3174 : :
# 3175 [ + + ]: 1161 : if (!vRecv.empty()) {
# 3176 : : // The version message includes information about the sending node which we don't use:
# 3177 : : // - 8 bytes (service bits)
# 3178 : : // - 16 bytes (ipv6 address)
# 3179 : : // - 2 bytes (port)
# 3180 : 1159 : vRecv.ignore(26);
# 3181 : 1159 : vRecv >> nNonce;
# 3182 : 1159 : }
# 3183 [ + + ]: 1161 : if (!vRecv.empty()) {
# 3184 : 1159 : std::string strSubVer;
# 3185 : 1159 : vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
# 3186 : 1159 : cleanSubVer = SanitizeString(strSubVer);
# 3187 : 1159 : }
# 3188 [ + + ]: 1161 : if (!vRecv.empty()) {
# 3189 : 1159 : vRecv >> starting_height;
# 3190 : 1159 : }
# 3191 [ + + ]: 1161 : if (!vRecv.empty())
# 3192 : 1159 : vRecv >> fRelay;
# 3193 : : // Disconnect if we connected to ourself
# 3194 [ + + ][ - + ]: 1161 : if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce))
# 3195 : 0 : {
# 3196 : 0 : LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToString());
# 3197 : 0 : pfrom.fDisconnect = true;
# 3198 : 0 : return;
# 3199 : 0 : }
# 3200 : :
# 3201 [ + + ][ - + ]: 1161 : if (pfrom.IsInboundConn() && addrMe.IsRoutable())
# 3202 : 0 : {
# 3203 : 0 : SeenLocal(addrMe);
# 3204 : 0 : }
# 3205 : :
# 3206 : : // Inbound peers send us their version message when they connect.
# 3207 : : // We send our version message in response.
# 3208 [ + + ]: 1161 : if (pfrom.IsInboundConn()) {
# 3209 : 746 : PushNodeVersion(pfrom, *peer);
# 3210 : 746 : }
# 3211 : :
# 3212 : : // Change version
# 3213 : 1161 : const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION);
# 3214 : 1161 : pfrom.SetCommonVersion(greatest_common_version);
# 3215 : 1161 : pfrom.nVersion = nVersion;
# 3216 : :
# 3217 : 1161 : const CNetMsgMaker msg_maker(greatest_common_version);
# 3218 : :
# 3219 [ + + ]: 1161 : if (greatest_common_version >= WTXID_RELAY_VERSION) {
# 3220 : 1160 : m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::WTXIDRELAY));
# 3221 : 1160 : }
# 3222 : :
# 3223 : : // Signal ADDRv2 support (BIP155).
# 3224 [ + + ]: 1161 : if (greatest_common_version >= 70016) {
# 3225 : : // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some
# 3226 : : // implementations reject messages they don't know. As a courtesy, don't send
# 3227 : : // it to nodes with a version before 70016, as no software is known to support
# 3228 : : // BIP155 that doesn't announce at least that protocol version number.
# 3229 : 1160 : m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::SENDADDRV2));
# 3230 : 1160 : }
# 3231 : :
# 3232 : 1161 : m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::VERACK));
# 3233 : :
# 3234 : 1161 : pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices);
# 3235 : 1161 : peer->m_their_services = nServices;
# 3236 : 1161 : pfrom.SetAddrLocal(addrMe);
# 3237 : 1161 : {
# 3238 : 1161 : LOCK(pfrom.m_subver_mutex);
# 3239 : 1161 : pfrom.cleanSubVer = cleanSubVer;
# 3240 : 1161 : }
# 3241 : 1161 : peer->m_starting_height = starting_height;
# 3242 : :
# 3243 : : // We only initialize the m_tx_relay data structure if:
# 3244 : : // - this isn't an outbound block-relay-only connection; and
# 3245 : : // - fRelay=true or we're offering NODE_BLOOM to this peer
# 3246 : : // (NODE_BLOOM means that the peer may turn on tx relay later)
# 3247 [ + + ]: 1161 : if (!pfrom.IsBlockOnlyConn() &&
# 3248 [ + + ][ + - ]: 1161 : (fRelay || (peer->m_our_services & NODE_BLOOM))) {
# 3249 : 1142 : auto* const tx_relay = peer->SetTxRelay();
# 3250 : 1142 : {
# 3251 : 1142 : LOCK(tx_relay->m_bloom_filter_mutex);
# 3252 : 1142 : tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message
# 3253 : 1142 : }
# 3254 [ + + ]: 1142 : if (fRelay) pfrom.m_relays_txs = true;
# 3255 : 1142 : }
# 3256 : :
# 3257 : : // Potentially mark this peer as a preferred download peer.
# 3258 : 1161 : {
# 3259 : 1161 : LOCK(cs_main);
# 3260 : 1161 : CNodeState* state = State(pfrom.GetId());
# 3261 [ + + ][ + + ]: 1161 : state->fPreferredDownload = (!pfrom.IsInboundConn() || pfrom.HasPermission(NetPermissionFlags::NoBan)) && !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer);
# [ + + ][ + - ]
# 3262 : 1161 : m_num_preferred_download_peers += state->fPreferredDownload;
# 3263 : 1161 : }
# 3264 : :
# 3265 : : // Self advertisement & GETADDR logic
# 3266 [ + + ][ + + ]: 1161 : if (!pfrom.IsInboundConn() && SetupAddressRelay(pfrom, *peer)) {
# 3267 : : // For outbound peers, we try to relay our address (so that other
# 3268 : : // nodes can try to find us more quickly, as we have no guarantee
# 3269 : : // that an outbound peer is even aware of how to reach us) and do a
# 3270 : : // one-time address fetch (to help populate/update our addrman). If
# 3271 : : // we're starting up for the first time, our addrman may be pretty
# 3272 : : // empty and no one will know who we are, so these mechanisms are
# 3273 : : // important to help us connect to the network.
# 3274 : : //
# 3275 : : // We skip this for block-relay-only peers. We want to avoid
# 3276 : : // potentially leaking addr information and we do not want to
# 3277 : : // indicate to the peer that we will participate in addr relay.
# 3278 [ + - ][ + + ]: 396 : if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload())
# 3279 : 267 : {
# 3280 : 267 : CAddress addr{GetLocalAddress(pfrom.addr), peer->m_our_services, Now<NodeSeconds>()};
# 3281 : 267 : FastRandomContext insecure_rand;
# 3282 [ - + ]: 267 : if (addr.IsRoutable())
# 3283 : 0 : {
# 3284 [ # # ]: 0 : LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
# 3285 : 0 : PushAddress(*peer, addr, insecure_rand);
# 3286 [ + + ]: 267 : } else if (IsPeerAddrLocalGood(&pfrom)) {
# 3287 : : // Override just the address with whatever the peer sees us as.
# 3288 : : // Leave the port in addr as it was returned by GetLocalAddress()
# 3289 : : // above, as this is an outbound connection and the peer cannot
# 3290 : : // observe our listening port.
# 3291 : 2 : addr.SetIP(addrMe);
# 3292 [ + - ]: 2 : LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
# 3293 : 2 : PushAddress(*peer, addr, insecure_rand);
# 3294 : 2 : }
# 3295 : 267 : }
# 3296 : :
# 3297 : : // Get recent addresses
# 3298 : 396 : m_connman.PushMessage(&pfrom, CNetMsgMaker(greatest_common_version).Make(NetMsgType::GETADDR));
# 3299 : 396 : peer->m_getaddr_sent = true;
# 3300 : : // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response
# 3301 : : // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
# 3302 : 396 : peer->m_addr_token_bucket += MAX_ADDR_TO_SEND;
# 3303 : 396 : }
# 3304 : :
# 3305 [ + + ]: 1161 : if (!pfrom.IsInboundConn()) {
# 3306 : : // For non-inbound connections, we update the addrman to record
# 3307 : : // connection success so that addrman will have an up-to-date
# 3308 : : // notion of which peers are online and available.
# 3309 : : //
# 3310 : : // While we strive to not leak information about block-relay-only
# 3311 : : // connections via the addrman, not moving an address to the tried
# 3312 : : // table is also potentially detrimental because new-table entries
# 3313 : : // are subject to eviction in the event of addrman collisions. We
# 3314 : : // mitigate the information-leak by never calling
# 3315 : : // AddrMan::Connected() on block-relay-only peers; see
# 3316 : : // FinalizeNode().
# 3317 : : //
# 3318 : : // This moves an address from New to Tried table in Addrman,
# 3319 : : // resolves tried-table collisions, etc.
# 3320 : 415 : m_addrman.Good(pfrom.addr);
# 3321 : 415 : }
# 3322 : :
# 3323 : 1161 : std::string remoteAddr;
# 3324 [ + + ]: 1161 : if (fLogIPs)
# 3325 : 2 : remoteAddr = ", peeraddr=" + pfrom.addr.ToString();
# 3326 : :
# 3327 [ + - ]: 1161 : LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s\n",
# 3328 : 1161 : cleanSubVer, pfrom.nVersion,
# 3329 : 1161 : peer->m_starting_height, addrMe.ToString(), fRelay, pfrom.GetId(),
# 3330 : 1161 : remoteAddr);
# 3331 : :
# 3332 : 1161 : int64_t nTimeOffset = nTime - GetTime();
# 3333 : 1161 : pfrom.nTimeOffset = nTimeOffset;
# 3334 [ + + ]: 1161 : if (!pfrom.IsInboundConn()) {
# 3335 : : // Don't use timedata samples from inbound peers to make it
# 3336 : : // harder for others to tamper with our adjusted time.
# 3337 : 415 : AddTimeData(pfrom.addr, nTimeOffset);
# 3338 : 415 : }
# 3339 : :
# 3340 : : // If the peer is old enough to have the old alert system, send it the final alert.
# 3341 [ - + ]: 1161 : if (greatest_common_version <= 70012) {
# 3342 : 0 : CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
# 3343 : 0 : m_connman.PushMessage(&pfrom, CNetMsgMaker(greatest_common_version).Make("alert", finalAlert));
# 3344 : 0 : }
# 3345 : :
# 3346 : : // Feeler connections exist only to verify if address is online.
# 3347 [ + + ]: 1161 : if (pfrom.IsFeelerConn()) {
# 3348 [ + - ]: 1 : LogPrint(BCLog::NET, "feeler connection completed peer=%d; disconnecting\n", pfrom.GetId());
# 3349 : 1 : pfrom.fDisconnect = true;
# 3350 : 1 : }
# 3351 : 1161 : return;
# 3352 : 1161 : }
# 3353 : :
# 3354 [ + + ]: 137371 : if (pfrom.nVersion == 0) {
# 3355 : : // Must have a version message before anything else
# 3356 [ + - ]: 2 : LogPrint(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
# 3357 : 2 : return;
# 3358 : 2 : }
# 3359 : :
# 3360 : : // At this point, the outgoing message serialization version can't change.
# 3361 : 137369 : const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
# 3362 : :
# 3363 [ + + ]: 137369 : if (msg_type == NetMsgType::VERACK) {
# 3364 [ + + ]: 1158 : if (pfrom.fSuccessfullyConnected) {
# 3365 [ + - ]: 1 : LogPrint(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId());
# 3366 : 1 : return;
# 3367 : 1 : }
# 3368 : :
# 3369 [ + + ]: 1157 : if (!pfrom.IsInboundConn()) {
# 3370 [ + + ]: 414 : LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s (%s)\n",
# 3371 : 414 : pfrom.nVersion.load(), peer->m_starting_height,
# 3372 : 414 : pfrom.GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToString()) : ""),
# 3373 : 414 : pfrom.ConnectionTypeAsString());
# 3374 : 414 : }
# 3375 : :
# 3376 [ + - ]: 1157 : if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) {
# 3377 : : // Tell our peer we are willing to provide version 2 cmpctblocks.
# 3378 : : // However, we do not request new block announcements using
# 3379 : : // cmpctblock messages.
# 3380 : : // We send this to non-NODE NETWORK peers as well, because
# 3381 : : // they may wish to request compact blocks from us
# 3382 : 1157 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION));
# 3383 : 1157 : }
# 3384 : 1157 : pfrom.fSuccessfullyConnected = true;
# 3385 : 1157 : return;
# 3386 : 1158 : }
# 3387 : :
# 3388 [ + + ]: 136211 : if (msg_type == NetMsgType::SENDHEADERS) {
# 3389 : 587 : LOCK(cs_main);
# 3390 : 587 : State(pfrom.GetId())->fPreferHeaders = true;
# 3391 : 587 : return;
# 3392 : 587 : }
# 3393 : :
# 3394 [ + + ]: 135624 : if (msg_type == NetMsgType::SENDCMPCT) {
# 3395 : 1020 : bool sendcmpct_hb{false};
# 3396 : 1020 : uint64_t sendcmpct_version{0};
# 3397 : 1020 : vRecv >> sendcmpct_hb >> sendcmpct_version;
# 3398 : :
# 3399 : : // Only support compact block relay with witnesses
# 3400 [ + + ]: 1020 : if (sendcmpct_version != CMPCTBLOCKS_VERSION) return;
# 3401 : :
# 3402 : 1014 : LOCK(cs_main);
# 3403 : 1014 : CNodeState* nodestate = State(pfrom.GetId());
# 3404 : 1014 : nodestate->m_provides_cmpctblocks = true;
# 3405 : 1014 : nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
# 3406 : : // save whether peer selects us as BIP152 high-bandwidth peer
# 3407 : : // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth)
# 3408 : 1014 : pfrom.m_bip152_highbandwidth_from = sendcmpct_hb;
# 3409 : 1014 : return;
# 3410 : 1020 : }
# 3411 : :
# 3412 : : // BIP339 defines feature negotiation of wtxidrelay, which must happen between
# 3413 : : // VERSION and VERACK to avoid relay problems from switching after a connection is up.
# 3414 [ + + ]: 134604 : if (msg_type == NetMsgType::WTXIDRELAY) {
# 3415 [ - + ]: 1086 : if (pfrom.fSuccessfullyConnected) {
# 3416 : : // Disconnect peers that send a wtxidrelay message after VERACK.
# 3417 [ # # ]: 0 : LogPrint(BCLog::NET, "wtxidrelay received after verack from peer=%d; disconnecting\n", pfrom.GetId());
# 3418 : 0 : pfrom.fDisconnect = true;
# 3419 : 0 : return;
# 3420 : 0 : }
# 3421 [ + - ]: 1086 : if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) {
# 3422 [ + - ]: 1086 : if (!peer->m_wtxid_relay) {
# 3423 : 1086 : peer->m_wtxid_relay = true;
# 3424 : 1086 : m_wtxid_relay_peers++;
# 3425 : 1086 : } else {
# 3426 [ # # ]: 0 : LogPrint(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId());
# 3427 : 0 : }
# 3428 : 1086 : } else {
# 3429 [ # # ]: 0 : LogPrint(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId());
# 3430 : 0 : }
# 3431 : 1086 : return;
# 3432 : 1086 : }
# 3433 : :
# 3434 : : // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen
# 3435 : : // between VERSION and VERACK.
# 3436 [ + + ]: 133518 : if (msg_type == NetMsgType::SENDADDRV2) {
# 3437 [ - + ]: 711 : if (pfrom.fSuccessfullyConnected) {
# 3438 : : // Disconnect peers that send a SENDADDRV2 message after VERACK.
# 3439 [ # # ]: 0 : LogPrint(BCLog::NET, "sendaddrv2 received after verack from peer=%d; disconnecting\n", pfrom.GetId());
# 3440 : 0 : pfrom.fDisconnect = true;
# 3441 : 0 : return;
# 3442 : 0 : }
# 3443 : 711 : peer->m_wants_addrv2 = true;
# 3444 : 711 : return;
# 3445 : 711 : }
# 3446 : :
# 3447 [ + + ]: 132807 : if (!pfrom.fSuccessfullyConnected) {
# 3448 [ + - ]: 6 : LogPrint(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
# 3449 : 6 : return;
# 3450 : 6 : }
# 3451 : :
# 3452 [ + + ][ + + ]: 132801 : if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
# 3453 : 55 : int stream_version = vRecv.GetVersion();
# 3454 [ + + ]: 55 : if (msg_type == NetMsgType::ADDRV2) {
# 3455 : : // Add ADDRV2_FORMAT to the version so that the CNetAddr and CAddress
# 3456 : : // unserialize methods know that an address in v2 format is coming.
# 3457 : 8 : stream_version |= ADDRV2_FORMAT;
# 3458 : 8 : }
# 3459 : :
# 3460 : 55 : OverrideStream<CDataStream> s(&vRecv, vRecv.GetType(), stream_version);
# 3461 : 55 : std::vector<CAddress> vAddr;
# 3462 : :
# 3463 : 55 : s >> vAddr;
# 3464 : :
# 3465 [ + + ]: 55 : if (!SetupAddressRelay(pfrom, *peer)) {
# 3466 [ + - ]: 5 : LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
# 3467 : 5 : return;
# 3468 : 5 : }
# 3469 : :
# 3470 [ + + ]: 50 : if (vAddr.size() > MAX_ADDR_TO_SEND)
# 3471 : 2 : {
# 3472 : 2 : Misbehaving(*peer, 20, strprintf("%s message size = %u", msg_type, vAddr.size()));
# 3473 : 2 : return;
# 3474 : 2 : }
# 3475 : :
# 3476 : : // Store the new addresses
# 3477 : 48 : std::vector<CAddress> vAddrOk;
# 3478 : 48 : const auto current_a_time{Now<NodeSeconds>()};
# 3479 : :
# 3480 : : // Update/increment addr rate limiting bucket.
# 3481 : 48 : const auto current_time{GetTime<std::chrono::microseconds>()};
# 3482 [ + + ]: 48 : if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
# 3483 : : // Don't increment bucket if it's already full
# 3484 : 42 : const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us);
# 3485 : 42 : const double increment = Ticks<SecondsDouble>(time_diff) * MAX_ADDR_RATE_PER_SECOND;
# 3486 : 42 : peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET);
# 3487 : 42 : }
# 3488 : 48 : peer->m_addr_token_timestamp = current_time;
# 3489 : :
# 3490 : 48 : const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr);
# 3491 : 48 : uint64_t num_proc = 0;
# 3492 : 48 : uint64_t num_rate_limit = 0;
# 3493 : 48 : Shuffle(vAddr.begin(), vAddr.end(), FastRandomContext());
# 3494 [ + + ]: 48 : for (CAddress& addr : vAddr)
# 3495 : 3279 : {
# 3496 [ - + ]: 3279 : if (interruptMsgProc)
# 3497 : 0 : return;
# 3498 : :
# 3499 : : // Apply rate limiting.
# 3500 [ + + ]: 3279 : if (peer->m_addr_token_bucket < 1.0) {
# 3501 [ + + ]: 2019 : if (rate_limited) {
# 3502 : 1998 : ++num_rate_limit;
# 3503 : 1998 : continue;
# 3504 : 1998 : }
# 3505 : 2019 : } else {
# 3506 : 1260 : peer->m_addr_token_bucket -= 1.0;
# 3507 : 1260 : }
# 3508 : : // We only bother storing full nodes, though this may include
# 3509 : : // things which we would not make an outbound connection to, in
# 3510 : : // part because we may make feeler connections to them.
# 3511 [ - + ][ # # ]: 1281 : if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices))
# 3512 : 0 : continue;
# 3513 : :
# 3514 [ - + ][ - + ]: 1281 : if (addr.nTime <= NodeSeconds{100000000s} || addr.nTime > current_a_time + 10min) {
# [ - + ]
# 3515 : 0 : addr.nTime = current_a_time - 5 * 24h;
# 3516 : 0 : }
# 3517 : 1281 : AddAddressKnown(*peer, addr);
# 3518 [ + - ][ - + ]: 1281 : if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
# [ - + ]
# 3519 : : // Do not process banned/discouraged addresses beyond remembering we received them
# 3520 : 0 : continue;
# 3521 : 0 : }
# 3522 : 1281 : ++num_proc;
# 3523 : 1281 : bool fReachable = IsReachable(addr);
# 3524 [ + - ][ + + ]: 1281 : if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) {
# [ + + ][ + + ]
# [ + + ]
# 3525 : : // Relay to a limited number of other nodes
# 3526 : 53 : RelayAddress(pfrom.GetId(), addr, fReachable);
# 3527 : 53 : }
# 3528 : : // Do not store addresses outside our network
# 3529 [ + + ]: 1281 : if (fReachable)
# 3530 : 1280 : vAddrOk.push_back(addr);
# 3531 : 1281 : }
# 3532 : 48 : peer->m_addr_processed += num_proc;
# 3533 : 48 : peer->m_addr_rate_limited += num_rate_limit;
# 3534 [ + + ]: 48 : LogPrint(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n",
# 3535 : 48 : vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
# 3536 : :
# 3537 : 48 : m_addrman.Add(vAddrOk, pfrom.addr, 2h);
# 3538 [ + + ]: 48 : if (vAddr.size() < 1000) peer->m_getaddr_sent = false;
# 3539 : :
# 3540 : : // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements
# 3541 [ + + ][ + + ]: 48 : if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
# 3542 [ + - ]: 1 : LogPrint(BCLog::NET, "addrfetch connection completed peer=%d; disconnecting\n", pfrom.GetId());
# 3543 : 1 : pfrom.fDisconnect = true;
# 3544 : 1 : }
# 3545 : 48 : return;
# 3546 : 48 : }
# 3547 : :
# 3548 [ + + ]: 132746 : if (msg_type == NetMsgType::INV) {
# 3549 : 11321 : std::vector<CInv> vInv;
# 3550 : 11321 : vRecv >> vInv;
# 3551 [ + + ]: 11321 : if (vInv.size() > MAX_INV_SZ)
# 3552 : 1 : {
# 3553 : 1 : Misbehaving(*peer, 20, strprintf("inv message size = %u", vInv.size()));
# 3554 : 1 : return;
# 3555 : 1 : }
# 3556 : :
# 3557 : 11320 : const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
# 3558 : :
# 3559 : 11320 : LOCK(cs_main);
# 3560 : :
# 3561 : 11320 : const auto current_time{GetTime<std::chrono::microseconds>()};
# 3562 : 11320 : uint256* best_block{nullptr};
# 3563 : :
# 3564 [ + + ]: 27168 : for (CInv& inv : vInv) {
# 3565 [ - + ]: 27168 : if (interruptMsgProc) return;
# 3566 : :
# 3567 : : // Ignore INVs that don't match wtxidrelay setting.
# 3568 : : // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting.
# 3569 : : // This is fine as no INV messages are involved in that process.
# 3570 [ + + ]: 27168 : if (peer->m_wtxid_relay) {
# 3571 [ + + ]: 27155 : if (inv.IsMsgTx()) continue;
# 3572 : 27155 : } else {
# 3573 [ - + ]: 13 : if (inv.IsMsgWtx()) continue;
# 3574 : 13 : }
# 3575 : :
# 3576 [ + + ]: 27148 : if (inv.IsMsgBlk()) {
# 3577 : 1440 : const bool fAlreadyHave = AlreadyHaveBlock(inv.hash);
# 3578 [ + - ][ + + ]: 1440 : LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
# 3579 : :
# 3580 : 1440 : UpdateBlockAvailability(pfrom.GetId(), inv.hash);
# 3581 [ + + ][ + - ]: 1440 : if (!fAlreadyHave && !fImporting && !fReindex && !IsBlockRequested(inv.hash)) {
# [ + - ][ + - ]
# 3582 : : // Headers-first is the primary method of announcement on
# 3583 : : // the network. If a node fell back to sending blocks by
# 3584 : : // inv, it may be for a re-org, or because we haven't
# 3585 : : // completed initial headers sync. The final block hash
# 3586 : : // provided should be the highest, so send a getheaders and
# 3587 : : // then fetch the blocks we need to catch up.
# 3588 : 945 : best_block = &inv.hash;
# 3589 : 945 : }
# 3590 [ + - ]: 25708 : } else if (inv.IsGenTxMsg()) {
# 3591 [ + + ]: 25708 : if (reject_tx_invs) {
# 3592 [ + - ]: 2 : LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId());
# 3593 : 2 : pfrom.fDisconnect = true;
# 3594 : 2 : return;
# 3595 : 2 : }
# 3596 : 25706 : const GenTxid gtxid = ToGenTxid(inv);
# 3597 : 25706 : const bool fAlreadyHave = AlreadyHaveTx(gtxid);
# 3598 [ + - ][ + + ]: 25706 : LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
# 3599 : :
# 3600 : 25706 : AddKnownTx(*peer, inv.hash);
# 3601 [ + + ][ + + ]: 25706 : if (!fAlreadyHave && !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
# 3602 : 21583 : AddTxAnnouncement(pfrom, gtxid, current_time);
# 3603 : 21583 : }
# 3604 : 25706 : } else {
# 3605 [ # # ]: 0 : LogPrint(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId());
# 3606 : 0 : }
# 3607 : 27148 : }
# 3608 : :
# 3609 [ + + ]: 11318 : if (best_block != nullptr) {
# 3610 : : // If we haven't started initial headers-sync with this peer, then
# 3611 : : // consider sending a getheaders now. On initial startup, there's a
# 3612 : : // reliability vs bandwidth tradeoff, where we are only trying to do
# 3613 : : // initial headers sync with one peer at a time, with a long
# 3614 : : // timeout (at which point, if the sync hasn't completed, we will
# 3615 : : // disconnect the peer and then choose another). In the meantime,
# 3616 : : // as new blocks are found, we are willing to add one new peer per
# 3617 : : // block to sync with as well, to sync quicker in the case where
# 3618 : : // our initial peer is unresponsive (but less bandwidth than we'd
# 3619 : : // use if we turned on sync with all peers).
# 3620 : 945 : CNodeState& state{*Assert(State(pfrom.GetId()))};
# 3621 [ + + ][ + + ]: 945 : if (state.fSyncStarted || (!peer->m_inv_triggered_getheaders_before_sync && *best_block != m_last_block_inv_triggering_headers_sync)) {
# [ + + ]
# 3622 [ + + ]: 929 : if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer)) {
# 3623 [ + - ]: 683 : LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n",
# 3624 : 683 : m_chainman.m_best_header->nHeight, best_block->ToString(),
# 3625 : 683 : pfrom.GetId());
# 3626 : 683 : }
# 3627 [ + + ]: 929 : if (!state.fSyncStarted) {
# 3628 : 19 : peer->m_inv_triggered_getheaders_before_sync = true;
# 3629 : : // Update the last block hash that triggered a new headers
# 3630 : : // sync, so that we don't turn on headers sync with more
# 3631 : : // than 1 new peer every new block.
# 3632 : 19 : m_last_block_inv_triggering_headers_sync = *best_block;
# 3633 : 19 : }
# 3634 : 929 : }
# 3635 : 945 : }
# 3636 : :
# 3637 : 11318 : return;
# 3638 : 11320 : }
# 3639 : :
# 3640 [ + + ]: 121425 : if (msg_type == NetMsgType::GETDATA) {
# 3641 : 34872 : std::vector<CInv> vInv;
# 3642 : 34872 : vRecv >> vInv;
# 3643 [ + + ]: 34872 : if (vInv.size() > MAX_INV_SZ)
# 3644 : 1 : {
# 3645 : 1 : Misbehaving(*peer, 20, strprintf("getdata message size = %u", vInv.size()));
# 3646 : 1 : return;
# 3647 : 1 : }
# 3648 : :
# 3649 [ + - ]: 34871 : LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId());
# 3650 : :
# 3651 [ + - ]: 34871 : if (vInv.size() > 0) {
# 3652 [ + - ]: 34871 : LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
# 3653 : 34871 : }
# 3654 : :
# 3655 : 34871 : {
# 3656 : 34871 : LOCK(peer->m_getdata_requests_mutex);
# 3657 : 34871 : peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end());
# 3658 : 34871 : ProcessGetData(pfrom, *peer, interruptMsgProc);
# 3659 : 34871 : }
# 3660 : :
# 3661 : 34871 : return;
# 3662 : 34872 : }
# 3663 : :
# 3664 [ + + ]: 86553 : if (msg_type == NetMsgType::GETBLOCKS) {
# 3665 : 4 : CBlockLocator locator;
# 3666 : 4 : uint256 hashStop;
# 3667 : 4 : vRecv >> locator >> hashStop;
# 3668 : :
# 3669 [ + + ]: 4 : if (locator.vHave.size() > MAX_LOCATOR_SZ) {
# 3670 [ + - ]: 1 : LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
# 3671 : 1 : pfrom.fDisconnect = true;
# 3672 : 1 : return;
# 3673 : 1 : }
# 3674 : :
# 3675 : : // We might have announced the currently-being-connected tip using a
# 3676 : : // compact block, which resulted in the peer sending a getblocks
# 3677 : : // request, which we would otherwise respond to without the new block.
# 3678 : : // To avoid this situation we simply verify that we are on our best
# 3679 : : // known chain now. This is super overkill, but we handle it better
# 3680 : : // for getheaders requests, and there are no known nodes which support
# 3681 : : // compact blocks but still use getblocks to request blocks.
# 3682 : 3 : {
# 3683 : 3 : std::shared_ptr<const CBlock> a_recent_block;
# 3684 : 3 : {
# 3685 : 3 : LOCK(m_most_recent_block_mutex);
# 3686 : 3 : a_recent_block = m_most_recent_block;
# 3687 : 3 : }
# 3688 : 3 : BlockValidationState state;
# 3689 [ - + ]: 3 : if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
# 3690 [ # # ]: 0 : LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
# 3691 : 0 : }
# 3692 : 3 : }
# 3693 : :
# 3694 : 3 : LOCK(cs_main);
# 3695 : :
# 3696 : : // Find the last block the caller has in the main chain
# 3697 : 3 : const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
# 3698 : :
# 3699 : : // Send the rest of the chain
# 3700 [ + - ]: 3 : if (pindex)
# 3701 : 3 : pindex = m_chainman.ActiveChain().Next(pindex);
# 3702 : 3 : int nLimit = 500;
# 3703 [ + - ][ + - ]: 3 : 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());
# [ + - ]
# 3704 [ + + ]: 22 : for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
# 3705 : 19 : {
# 3706 [ - + ]: 19 : if (pindex->GetBlockHash() == hashStop)
# 3707 : 0 : {
# 3708 [ # # ]: 0 : LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
# 3709 : 0 : break;
# 3710 : 0 : }
# 3711 : : // If pruning, don't inv blocks unless we have on disk and are likely to still have
# 3712 : : // for some reasonable time window (1 hour) that block relay might require.
# 3713 : 19 : const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
# 3714 [ - + ][ # # ]: 19 : if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave))
# [ # # ]
# 3715 : 0 : {
# 3716 [ # # ]: 0 : LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
# 3717 : 0 : break;
# 3718 : 0 : }
# 3719 : 19 : WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
# 3720 [ - + ]: 19 : if (--nLimit <= 0) {
# 3721 : : // When this block is requested, we'll send an inv that'll
# 3722 : : // trigger the peer to getblocks the next batch of inventory.
# 3723 [ # # ]: 0 : LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
# 3724 : 0 : WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();});
# 3725 : 0 : break;
# 3726 : 0 : }
# 3727 : 19 : }
# 3728 : 3 : return;
# 3729 : 4 : }
# 3730 : :
# 3731 [ + + ]: 86549 : if (msg_type == NetMsgType::GETBLOCKTXN) {
# 3732 : 2299 : BlockTransactionsRequest req;
# 3733 : 2299 : vRecv >> req;
# 3734 : :
# 3735 : 2299 : std::shared_ptr<const CBlock> recent_block;
# 3736 : 2299 : {
# 3737 : 2299 : LOCK(m_most_recent_block_mutex);
# 3738 [ + + ]: 2299 : if (m_most_recent_block_hash == req.blockhash)
# 3739 : 2239 : recent_block = m_most_recent_block;
# 3740 : : // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion
# 3741 : 2299 : }
# 3742 [ + + ]: 2299 : if (recent_block) {
# 3743 : 2239 : SendBlockTransactions(pfrom, *peer, *recent_block, req);
# 3744 : 2239 : return;
# 3745 : 2239 : }
# 3746 : :
# 3747 : 60 : {
# 3748 : 60 : LOCK(cs_main);
# 3749 : :
# 3750 : 60 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
# 3751 [ - + ][ + + ]: 60 : if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
# 3752 [ + - ]: 1 : LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId());
# 3753 : 1 : return;
# 3754 : 1 : }
# 3755 : :
# 3756 [ + + ]: 59 : if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
# 3757 : 58 : CBlock block;
# 3758 : 58 : bool ret = ReadBlockFromDisk(block, pindex, m_chainparams.GetConsensus());
# 3759 : 58 : assert(ret);
# 3760 : :
# 3761 : 0 : SendBlockTransactions(pfrom, *peer, block, req);
# 3762 : 58 : return;
# 3763 : 58 : }
# 3764 : 59 : }
# 3765 : :
# 3766 : : // If an older block is requested (should never happen in practice,
# 3767 : : // but can happen in tests) send a block response instead of a
# 3768 : : // blocktxn response. Sending a full block response instead of a
# 3769 : : // small blocktxn response is preferable in the case where a peer
# 3770 : : // might maliciously send lots of getblocktxn requests to trigger
# 3771 : : // expensive disk reads, because it will require the peer to
# 3772 : : // actually receive all the data read from disk over the network.
# 3773 [ + - ]: 1 : LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
# 3774 : 1 : CInv inv{MSG_WITNESS_BLOCK, req.blockhash};
# 3775 : 1 : WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv));
# 3776 : : // The message processing loop will go around again (without pausing) and we'll respond then
# 3777 : 1 : return;
# 3778 : 59 : }
# 3779 : :
# 3780 [ + + ]: 84250 : if (msg_type == NetMsgType::GETHEADERS) {
# 3781 : 1449 : CBlockLocator locator;
# 3782 : 1449 : uint256 hashStop;
# 3783 : 1449 : vRecv >> locator >> hashStop;
# 3784 : :
# 3785 [ + + ]: 1449 : if (locator.vHave.size() > MAX_LOCATOR_SZ) {
# 3786 [ + - ]: 1 : LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
# 3787 : 1 : pfrom.fDisconnect = true;
# 3788 : 1 : return;
# 3789 : 1 : }
# 3790 : :
# 3791 [ - + ][ - + ]: 1448 : if (fImporting || fReindex) {
# 3792 [ # # ]: 0 : LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId());
# 3793 : 0 : return;
# 3794 : 0 : }
# 3795 : :
# 3796 : 1448 : LOCK(cs_main);
# 3797 : :
# 3798 : : // Note that if we were to be on a chain that forks from the checkpointed
# 3799 : : // chain, then serving those headers to a peer that has seen the
# 3800 : : // checkpointed chain would cause that peer to disconnect us. Requiring
# 3801 : : // that our chainwork exceed nMinimumChainWork is a protection against
# 3802 : : // being fed a bogus chain when we started up for the first time and
# 3803 : : // getting partitioned off the honest network for serving that chain to
# 3804 : : // others.
# 3805 [ - + ]: 1448 : if (m_chainman.ActiveTip() == nullptr ||
# 3806 [ + + ][ + - ]: 1448 : (m_chainman.ActiveTip()->nChainWork < nMinimumChainWork && !pfrom.HasPermission(NetPermissionFlags::Download))) {
# 3807 [ + - ]: 9 : LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId());
# 3808 : : // Just respond with an empty headers message, to tell the peer to
# 3809 : : // go away but not treat us as unresponsive.
# 3810 : 9 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::HEADERS, std::vector<CBlock>()));
# 3811 : 9 : return;
# 3812 : 9 : }
# 3813 : :
# 3814 : 1439 : CNodeState *nodestate = State(pfrom.GetId());
# 3815 : 1439 : const CBlockIndex* pindex = nullptr;
# 3816 [ + + ]: 1439 : if (locator.IsNull())
# 3817 : 6 : {
# 3818 : : // If locator is null, return the hashStop block
# 3819 : 6 : pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
# 3820 [ - + ]: 6 : if (!pindex) {
# 3821 : 0 : return;
# 3822 : 0 : }
# 3823 : :
# 3824 [ + + ]: 6 : if (!BlockRequestAllowed(pindex)) {
# 3825 [ + - ]: 2 : LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId());
# 3826 : 2 : return;
# 3827 : 2 : }
# 3828 : 6 : }
# 3829 : 1433 : else
# 3830 : 1433 : {
# 3831 : : // Find the last block the caller has in the main chain
# 3832 : 1433 : pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
# 3833 [ + - ]: 1433 : if (pindex)
# 3834 : 1433 : pindex = m_chainman.ActiveChain().Next(pindex);
# 3835 : 1433 : }
# 3836 : :
# 3837 : : // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
# 3838 : 1437 : std::vector<CBlock> vHeaders;
# 3839 : 1437 : int nLimit = MAX_HEADERS_RESULTS;
# 3840 [ + - ][ + + ]: 1437 : LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId());
# [ + + ]
# 3841 [ + + ]: 506429 : for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
# 3842 : 505022 : {
# 3843 : 505022 : vHeaders.push_back(pindex->GetBlockHeader());
# 3844 [ + + ][ + + ]: 505022 : if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
# [ + + ]
# 3845 : 30 : break;
# 3846 : 505022 : }
# 3847 : : // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR
# 3848 : : // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty
# 3849 : : // headers message). In both cases it's safe to update
# 3850 : : // pindexBestHeaderSent to be our tip.
# 3851 : : //
# 3852 : : // It is important that we simply reset the BestHeaderSent value here,
# 3853 : : // and not max(BestHeaderSent, newHeaderSent). We might have announced
# 3854 : : // the currently-being-connected tip using a compact block, which
# 3855 : : // resulted in the peer sending a headers request, which we respond to
# 3856 : : // without the new block. By resetting the BestHeaderSent, we ensure we
# 3857 : : // will re-announce the new block via headers (or compact blocks again)
# 3858 : : // in the SendMessages logic.
# 3859 [ + + ]: 1437 : nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip();
# 3860 : 1437 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
# 3861 : 1437 : return;
# 3862 : 1439 : }
# 3863 : :
# 3864 [ + + ]: 82801 : if (msg_type == NetMsgType::TX) {
# 3865 [ + + ]: 11170 : if (RejectIncomingTxs(pfrom)) {
# 3866 [ + - ]: 2 : LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom.GetId());
# 3867 : 2 : pfrom.fDisconnect = true;
# 3868 : 2 : return;
# 3869 : 2 : }
# 3870 : :
# 3871 : : // Stop processing the transaction early if we are still in IBD since we don't
# 3872 : : // have enough information to validate it yet. Sending unsolicited transactions
# 3873 : : // is not considered a protocol violation, so don't punish the peer.
# 3874 [ + + ]: 11168 : if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) return;
# 3875 : :
# 3876 : 11167 : CTransactionRef ptx;
# 3877 : 11167 : vRecv >> ptx;
# 3878 : 11167 : const CTransaction& tx = *ptx;
# 3879 : :
# 3880 : 11167 : const uint256& txid = ptx->GetHash();
# 3881 : 11167 : const uint256& wtxid = ptx->GetWitnessHash();
# 3882 : :
# 3883 [ + + ]: 11167 : const uint256& hash = peer->m_wtxid_relay ? wtxid : txid;
# 3884 : 11167 : AddKnownTx(*peer, hash);
# 3885 [ + + ][ + + ]: 11167 : if (peer->m_wtxid_relay && txid != wtxid) {
# 3886 : : // Insert txid into m_tx_inventory_known_filter, even for
# 3887 : : // wtxidrelay peers. This prevents re-adding of
# 3888 : : // unconfirmed parents to the recently_announced
# 3889 : : // filter, when a child tx is requested. See
# 3890 : : // ProcessGetData().
# 3891 : 10291 : AddKnownTx(*peer, txid);
# 3892 : 10291 : }
# 3893 : :
# 3894 : 11167 : LOCK2(cs_main, g_cs_orphans);
# 3895 : :
# 3896 : 11167 : m_txrequest.ReceivedResponse(pfrom.GetId(), txid);
# 3897 [ + + ]: 11167 : if (tx.HasWitness()) m_txrequest.ReceivedResponse(pfrom.GetId(), wtxid);
# 3898 : :
# 3899 : : // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the
# 3900 : : // absence of witness malleation, this is strictly better, because the
# 3901 : : // recent rejects filter may contain the wtxid but rarely contains
# 3902 : : // the txid of a segwit transaction that has been rejected.
# 3903 : : // In the presence of witness malleation, it's possible that by only
# 3904 : : // doing the check with wtxid, we could overlook a transaction which
# 3905 : : // was confirmed with a different witness, or exists in our mempool
# 3906 : : // with a different witness, but this has limited downside:
# 3907 : : // mempool validation does its own lookup of whether we have the txid
# 3908 : : // already; and an adversary can already relay us old transactions
# 3909 : : // (older than our recency filter) if trying to DoS us, without any need
# 3910 : : // for witness malleation.
# 3911 [ + + ]: 11167 : if (AlreadyHaveTx(GenTxid::Wtxid(wtxid))) {
# 3912 [ + + ]: 55 : if (pfrom.HasPermission(NetPermissionFlags::ForceRelay)) {
# 3913 : : // Always relay transactions received from peers with forcerelay
# 3914 : : // permission, even if they were already in the mempool, allowing
# 3915 : : // the node to function as a gateway for nodes hidden behind it.
# 3916 [ + + ]: 2 : if (!m_mempool.exists(GenTxid::Txid(tx.GetHash()))) {
# 3917 : 1 : LogPrintf("Not relaying non-mempool transaction %s from forcerelay peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
# 3918 : 1 : } else {
# 3919 : 1 : LogPrintf("Force relaying tx %s from peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
# 3920 : 1 : RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
# 3921 : 1 : }
# 3922 : 2 : }
# 3923 : 55 : return;
# 3924 : 55 : }
# 3925 : :
# 3926 : 11112 : const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx);
# 3927 : 11112 : const TxValidationState& state = result.m_state;
# 3928 : :
# 3929 [ + + ]: 11112 : if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
# 3930 : : // As this version of the transaction was acceptable, we can forget about any
# 3931 : : // requests for it.
# 3932 : 10782 : m_txrequest.ForgetTxHash(tx.GetHash());
# 3933 : 10782 : m_txrequest.ForgetTxHash(tx.GetWitnessHash());
# 3934 : 10782 : RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
# 3935 : 10782 : m_orphanage.AddChildrenToWorkSet(tx, peer->m_orphan_work_set);
# 3936 : :
# 3937 : 10782 : pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
# 3938 : :
# 3939 [ + - ]: 10782 : LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
# 3940 : 10782 : pfrom.GetId(),
# 3941 : 10782 : tx.GetHash().ToString(),
# 3942 : 10782 : m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000);
# 3943 : :
# 3944 [ + + ]: 10782 : for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) {
# 3945 : 411 : AddToCompactExtraTransactions(removedTx);
# 3946 : 411 : }
# 3947 : :
# 3948 : : // Recursively process any orphan transactions that depended on this one
# 3949 : 10782 : ProcessOrphanTx(peer->m_orphan_work_set);
# 3950 : 10782 : }
# 3951 [ + + ]: 330 : else if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS)
# 3952 : 170 : {
# 3953 : 170 : bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
# 3954 : :
# 3955 : : // Deduplicate parent txids, so that we don't have to loop over
# 3956 : : // the same parent txid more than once down below.
# 3957 : 170 : std::vector<uint256> unique_parents;
# 3958 : 170 : unique_parents.reserve(tx.vin.size());
# 3959 [ + + ]: 171 : for (const CTxIn& txin : tx.vin) {
# 3960 : : // We start with all parents, and then remove duplicates below.
# 3961 : 171 : unique_parents.push_back(txin.prevout.hash);
# 3962 : 171 : }
# 3963 : 170 : std::sort(unique_parents.begin(), unique_parents.end());
# 3964 : 170 : unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end());
# 3965 [ + + ]: 171 : for (const uint256& parent_txid : unique_parents) {
# 3966 [ + + ]: 171 : if (m_recent_rejects.contains(parent_txid)) {
# 3967 : 3 : fRejectedParents = true;
# 3968 : 3 : break;
# 3969 : 3 : }
# 3970 : 171 : }
# 3971 [ + + ]: 170 : if (!fRejectedParents) {
# 3972 : 167 : const auto current_time{GetTime<std::chrono::microseconds>()};
# 3973 : :
# 3974 [ + + ]: 168 : for (const uint256& parent_txid : unique_parents) {
# 3975 : : // Here, we only have the txid (and not wtxid) of the
# 3976 : : // inputs, so we only request in txid mode, even for
# 3977 : : // wtxidrelay peers.
# 3978 : : // Eventually we should replace this with an improved
# 3979 : : // protocol for getting all unconfirmed parents.
# 3980 : 168 : const auto gtxid{GenTxid::Txid(parent_txid)};
# 3981 : 168 : AddKnownTx(*peer, parent_txid);
# 3982 [ + + ]: 168 : if (!AlreadyHaveTx(gtxid)) AddTxAnnouncement(pfrom, gtxid, current_time);
# 3983 : 168 : }
# 3984 : :
# 3985 [ + - ]: 167 : if (m_orphanage.AddTx(ptx, pfrom.GetId())) {
# 3986 : 167 : AddToCompactExtraTransactions(ptx);
# 3987 : 167 : }
# 3988 : :
# 3989 : : // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore.
# 3990 : 167 : m_txrequest.ForgetTxHash(tx.GetHash());
# 3991 : 167 : m_txrequest.ForgetTxHash(tx.GetWitnessHash());
# 3992 : :
# 3993 : : // DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789)
# 3994 : 167 : unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetIntArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
# 3995 : 167 : m_orphanage.LimitOrphans(nMaxOrphanTx);
# 3996 : 167 : } else {
# 3997 [ + - ]: 3 : LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
# 3998 : : // We will continue to reject this tx since it has rejected
# 3999 : : // parents so avoid re-requesting it from other peers.
# 4000 : : // Here we add both the txid and the wtxid, as we know that
# 4001 : : // regardless of what witness is provided, we will not accept
# 4002 : : // this, so we don't need to allow for redownload of this txid
# 4003 : : // from any of our non-wtxidrelay peers.
# 4004 : 3 : m_recent_rejects.insert(tx.GetHash());
# 4005 : 3 : m_recent_rejects.insert(tx.GetWitnessHash());
# 4006 : 3 : m_txrequest.ForgetTxHash(tx.GetHash());
# 4007 : 3 : m_txrequest.ForgetTxHash(tx.GetWitnessHash());
# 4008 : 3 : }
# 4009 : 170 : } else {
# 4010 [ + + ]: 160 : if (state.GetResult() != TxValidationResult::TX_WITNESS_STRIPPED) {
# 4011 : : // We can add the wtxid of this transaction to our reject filter.
# 4012 : : // Do not add txids of witness transactions or witness-stripped
# 4013 : : // transactions to the filter, as they can have been malleated;
# 4014 : : // adding such txids to the reject filter would potentially
# 4015 : : // interfere with relay of valid transactions from peers that
# 4016 : : // do not support wtxid-based relay. See
# 4017 : : // https://github.com/bitcoin/bitcoin/issues/8279 for details.
# 4018 : : // We can remove this restriction (and always add wtxids to
# 4019 : : // the filter even for witness stripped transactions) once
# 4020 : : // wtxid-based relay is broadly deployed.
# 4021 : : // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
# 4022 : : // for concerns around weakening security of unupgraded nodes
# 4023 : : // if we start doing this too early.
# 4024 : 157 : m_recent_rejects.insert(tx.GetWitnessHash());
# 4025 : 157 : m_txrequest.ForgetTxHash(tx.GetWitnessHash());
# 4026 : : // If the transaction failed for TX_INPUTS_NOT_STANDARD,
# 4027 : : // then we know that the witness was irrelevant to the policy
# 4028 : : // failure, since this check depends only on the txid
# 4029 : : // (the scriptPubKey being spent is covered by the txid).
# 4030 : : // Add the txid to the reject filter to prevent repeated
# 4031 : : // processing of this transaction in the event that child
# 4032 : : // transactions are later received (resulting in
# 4033 : : // parent-fetching by txid via the orphan-handling logic).
# 4034 [ + + ][ + + ]: 157 : if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && tx.GetWitnessHash() != tx.GetHash()) {
# 4035 : 1 : m_recent_rejects.insert(tx.GetHash());
# 4036 : 1 : m_txrequest.ForgetTxHash(tx.GetHash());
# 4037 : 1 : }
# 4038 [ + + ]: 157 : if (RecursiveDynamicUsage(*ptx) < 100000) {
# 4039 : 156 : AddToCompactExtraTransactions(ptx);
# 4040 : 156 : }
# 4041 : 157 : }
# 4042 : 160 : }
# 4043 : :
# 4044 : : // If a tx has been detected by m_recent_rejects, we will have reached
# 4045 : : // this point and the tx will have been ignored. Because we haven't
# 4046 : : // submitted the tx to our mempool, we won't have computed a DoS
# 4047 : : // score for it or determined exactly why we consider it invalid.
# 4048 : : //
# 4049 : : // This means we won't penalize any peer subsequently relaying a DoSy
# 4050 : : // tx (even if we penalized the first peer who gave it to us) because
# 4051 : : // we have to account for m_recent_rejects showing false positives. In
# 4052 : : // other words, we shouldn't penalize a peer if we aren't *sure* they
# 4053 : : // submitted a DoSy tx.
# 4054 : : //
# 4055 : : // Note that m_recent_rejects doesn't just record DoSy or invalid
# 4056 : : // transactions, but any tx not accepted by the mempool, which may be
# 4057 : : // due to node policy (vs. consensus). So we can't blanket penalize a
# 4058 : : // peer simply for relaying a tx that our m_recent_rejects has caught,
# 4059 : : // regardless of false positives.
# 4060 : :
# 4061 [ + + ]: 11112 : if (state.IsInvalid()) {
# 4062 [ + - ]: 328 : LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
# 4063 : 328 : pfrom.GetId(),
# 4064 : 328 : state.ToString());
# 4065 : 328 : MaybePunishNodeForTx(pfrom.GetId(), state);
# 4066 : 328 : }
# 4067 : 11112 : return;
# 4068 : 11167 : }
# 4069 : :
# 4070 [ + + ]: 71631 : if (msg_type == NetMsgType::CMPCTBLOCK)
# 4071 : 15083 : {
# 4072 : : // Ignore cmpctblock received while importing
# 4073 [ - + ][ - + ]: 15083 : if (fImporting || fReindex) {
# 4074 [ # # ]: 0 : LogPrint(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId());
# 4075 : 0 : return;
# 4076 : 0 : }
# 4077 : :
# 4078 : 15083 : CBlockHeaderAndShortTxIDs cmpctblock;
# 4079 : 15083 : vRecv >> cmpctblock;
# 4080 : :
# 4081 : 15083 : bool received_new_header = false;
# 4082 : :
# 4083 : 15083 : {
# 4084 : 15083 : LOCK(cs_main);
# 4085 : :
# 4086 : 15083 : const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock);
# 4087 [ + + ]: 15083 : if (!prev_block) {
# 4088 : : // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
# 4089 [ + - ]: 25 : if (!m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
# 4090 : 25 : MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer);
# 4091 : 25 : }
# 4092 : 25 : return;
# 4093 [ + + ]: 15058 : } else if (prev_block->nChainWork + CalculateHeadersWork({cmpctblock.header}) < GetAntiDoSWorkThreshold()) {
# 4094 : : // If we get a low-work header in a compact block, we can ignore it.
# 4095 [ + - ]: 2 : LogPrint(BCLog::NET, "Ignoring low-work compact block from peer %d\n", pfrom.GetId());
# 4096 : 2 : return;
# 4097 : 2 : }
# 4098 : :
# 4099 [ + + ]: 15056 : if (!m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.GetHash())) {
# 4100 : 14334 : received_new_header = true;
# 4101 : 14334 : }
# 4102 : 15056 : }
# 4103 : :
# 4104 : 0 : const CBlockIndex *pindex = nullptr;
# 4105 : 15056 : BlockValidationState state;
# 4106 [ + + ]: 15056 : if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header}, /*min_pow_checked=*/true, state, &pindex)) {
# 4107 [ + - ]: 2 : if (state.IsInvalid()) {
# 4108 : 2 : MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block=*/true, "invalid header via cmpctblock");
# 4109 : 2 : return;
# 4110 : 2 : }
# 4111 : 2 : }
# 4112 : :
# 4113 : : // When we succeed in decoding a block's txids from a cmpctblock
# 4114 : : // message we typically jump to the BLOCKTXN handling code, with a
# 4115 : : // dummy (empty) BLOCKTXN message, to re-use the logic there in
# 4116 : : // completing processing of the putative block (without cs_main).
# 4117 : 15054 : bool fProcessBLOCKTXN = false;
# 4118 : 15054 : CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
# 4119 : :
# 4120 : : // If we end up treating this as a plain headers message, call that as well
# 4121 : : // without cs_main.
# 4122 : 15054 : bool fRevertToHeaderProcessing = false;
# 4123 : :
# 4124 : : // Keep a CBlock for "optimistic" compactblock reconstructions (see
# 4125 : : // below)
# 4126 : 15054 : std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
# 4127 : 15054 : bool fBlockReconstructed = false;
# 4128 : :
# 4129 : 15054 : {
# 4130 : 15054 : LOCK2(cs_main, g_cs_orphans);
# 4131 : : // If AcceptBlockHeader returned true, it set pindex
# 4132 : 15054 : assert(pindex);
# 4133 : 0 : UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
# 4134 : :
# 4135 : 15054 : CNodeState *nodestate = State(pfrom.GetId());
# 4136 : :
# 4137 : : // If this was a new header with more work than our tip, update the
# 4138 : : // peer's last block announcement time
# 4139 [ + + ][ + + ]: 15054 : if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
# 4140 : 14156 : nodestate->m_last_block_announcement = GetTime();
# 4141 : 14156 : }
# 4142 : :
# 4143 : 15054 : std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
# 4144 : 15054 : bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
# 4145 : :
# 4146 [ + + ]: 15054 : if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
# 4147 : 293 : return;
# 4148 : :
# 4149 [ + + ]: 14761 : if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better
# 4150 [ - + ]: 14761 : pindex->nTx != 0) { // We had this block at some point, but pruned it
# 4151 [ + + ]: 180 : if (fAlreadyInFlight) {
# 4152 : : // We requested this block for some reason, but our mempool will probably be useless
# 4153 : : // so we just grab the block via normal getdata
# 4154 : 4 : std::vector<CInv> vInv(1);
# 4155 : 4 : vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), cmpctblock.header.GetHash());
# 4156 : 4 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
# 4157 : 4 : }
# 4158 : 180 : return;
# 4159 : 180 : }
# 4160 : :
# 4161 : : // If we're not close to tip yet, give up and let parallel block fetch work its magic
# 4162 [ + + ][ + + ]: 14581 : if (!fAlreadyInFlight && !CanDirectFetch()) {
# 4163 : 16 : return;
# 4164 : 16 : }
# 4165 : :
# 4166 : : // We want to be a bit conservative just to be extra careful about DoS
# 4167 : : // possibilities in compact block processing...
# 4168 [ + + ]: 14565 : if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
# 4169 [ + + ][ + + ]: 11428 : if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
# 4170 [ + + ][ + + ]: 11428 : (fAlreadyInFlight && blockInFlightIt->second.first == pfrom.GetId())) {
# 4171 : 11291 : std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
# 4172 [ + + ]: 11291 : if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) {
# 4173 [ + - ]: 230 : if (!(*queuedBlockIt)->partialBlock)
# 4174 : 230 : (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool));
# 4175 : 0 : else {
# 4176 : : // The block was already in flight using compact blocks from the same peer
# 4177 [ # # ]: 0 : LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
# 4178 : 0 : return;
# 4179 : 0 : }
# 4180 : 230 : }
# 4181 : :
# 4182 : 11291 : PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
# 4183 : 11291 : ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
# 4184 [ + + ]: 11291 : if (status == READ_STATUS_INVALID) {
# 4185 : 1 : RemoveBlockRequest(pindex->GetBlockHash()); // Reset in-flight state in case Misbehaving does not result in a disconnect
# 4186 : 1 : Misbehaving(*peer, 100, "invalid compact block");
# 4187 : 1 : return;
# 4188 [ - + ]: 11290 : } else if (status == READ_STATUS_FAILED) {
# 4189 : : // Duplicate txindexes, the block is now in-flight, so just request it
# 4190 : 0 : std::vector<CInv> vInv(1);
# 4191 : 0 : vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), cmpctblock.header.GetHash());
# 4192 : 0 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
# 4193 : 0 : return;
# 4194 : 0 : }
# 4195 : :
# 4196 : 11290 : BlockTransactionsRequest req;
# 4197 [ + + ]: 37117 : for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
# 4198 [ + + ]: 25827 : if (!partialBlock.IsTxAvailable(i))
# 4199 : 4649 : req.indexes.push_back(i);
# 4200 : 25827 : }
# 4201 [ + + ]: 11290 : if (req.indexes.empty()) {
# 4202 : : // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
# 4203 : 8997 : BlockTransactions txn;
# 4204 : 8997 : txn.blockhash = cmpctblock.header.GetHash();
# 4205 : 8997 : blockTxnMsg << txn;
# 4206 : 8997 : fProcessBLOCKTXN = true;
# 4207 : 8997 : } else {
# 4208 : 2293 : req.blockhash = pindex->GetBlockHash();
# 4209 : 2293 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
# 4210 : 2293 : }
# 4211 : 11290 : } else {
# 4212 : : // This block is either already in flight from a different
# 4213 : : // peer, or this peer has too many blocks outstanding to
# 4214 : : // download from.
# 4215 : : // Optimistically try to reconstruct anyway since we might be
# 4216 : : // able to without any round trips.
# 4217 : 137 : PartiallyDownloadedBlock tempBlock(&m_mempool);
# 4218 : 137 : ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
# 4219 [ - + ]: 137 : if (status != READ_STATUS_OK) {
# 4220 : : // TODO: don't ignore failures
# 4221 : 0 : return;
# 4222 : 0 : }
# 4223 : 137 : std::vector<CTransactionRef> dummy;
# 4224 : 137 : status = tempBlock.FillBlock(*pblock, dummy);
# 4225 [ + + ]: 137 : if (status == READ_STATUS_OK) {
# 4226 : 126 : fBlockReconstructed = true;
# 4227 : 126 : }
# 4228 : 137 : }
# 4229 : 11428 : } else {
# 4230 [ + + ]: 3137 : if (fAlreadyInFlight) {
# 4231 : : // We requested this block, but its far into the future, so our
# 4232 : : // mempool will probably be useless - request the block normally
# 4233 : 59 : std::vector<CInv> vInv(1);
# 4234 : 59 : vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), cmpctblock.header.GetHash());
# 4235 : 59 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
# 4236 : 59 : return;
# 4237 : 3078 : } else {
# 4238 : : // If this was an announce-cmpctblock, we want the same treatment as a header message
# 4239 : 3078 : fRevertToHeaderProcessing = true;
# 4240 : 3078 : }
# 4241 : 3137 : }
# 4242 : 14565 : } // cs_main
# 4243 : :
# 4244 [ + + ]: 14505 : if (fProcessBLOCKTXN) {
# 4245 : 8997 : return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, time_received, interruptMsgProc);
# 4246 : 8997 : }
# 4247 : :
# 4248 [ + + ]: 5508 : if (fRevertToHeaderProcessing) {
# 4249 : : // Headers received from HB compact block peers are permitted to be
# 4250 : : // relayed before full validation (see BIP 152), so we don't want to disconnect
# 4251 : : // the peer if the header turns out to be for an invalid block.
# 4252 : : // Note that if a peer tries to build on an invalid chain, that
# 4253 : : // will be detected and the peer will be disconnected/discouraged.
# 4254 : 3078 : return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true);
# 4255 : 3078 : }
# 4256 : :
# 4257 [ + + ]: 2430 : if (fBlockReconstructed) {
# 4258 : : // If we got here, we were able to optimistically reconstruct a
# 4259 : : // block that is in flight from some other peer.
# 4260 : 126 : {
# 4261 : 126 : LOCK(cs_main);
# 4262 : 126 : mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false));
# 4263 : 126 : }
# 4264 : : // Setting force_processing to true means that we bypass some of
# 4265 : : // our anti-DoS protections in AcceptBlock, which filters
# 4266 : : // unrequested blocks that might be trying to waste our resources
# 4267 : : // (eg disk space). Because we only try to reconstruct blocks when
# 4268 : : // we're close to caught up (via the CanDirectFetch() requirement
# 4269 : : // above, combined with the behavior of not requesting blocks until
# 4270 : : // we have a chain with at least nMinimumChainWork), and we ignore
# 4271 : : // compact blocks with less work than our tip, it is safe to treat
# 4272 : : // reconstructed compact blocks as having been requested.
# 4273 : 126 : ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
# 4274 : 126 : LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
# 4275 [ + + ]: 126 : if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
# 4276 : : // Clear download state for this block, which is in
# 4277 : : // process from some other peer. We do this after calling
# 4278 : : // ProcessNewBlock so that a malleated cmpctblock announcement
# 4279 : : // can't be used to interfere with block relay.
# 4280 : 125 : RemoveBlockRequest(pblock->GetHash());
# 4281 : 125 : }
# 4282 : 126 : }
# 4283 : 2430 : return;
# 4284 : 5508 : }
# 4285 : :
# 4286 [ + + ]: 56548 : if (msg_type == NetMsgType::BLOCKTXN)
# 4287 : 11289 : {
# 4288 : : // Ignore blocktxn received while importing
# 4289 [ - + ][ - + ]: 11289 : if (fImporting || fReindex) {
# 4290 [ # # ]: 0 : LogPrint(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId());
# 4291 : 0 : return;
# 4292 : 0 : }
# 4293 : :
# 4294 : 11289 : BlockTransactions resp;
# 4295 : 11289 : vRecv >> resp;
# 4296 : :
# 4297 : 11289 : std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
# 4298 : 11289 : bool fBlockRead = false;
# 4299 : 11289 : {
# 4300 : 11289 : LOCK(cs_main);
# 4301 : :
# 4302 : 11289 : std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
# 4303 [ - + ][ - + ]: 11289 : if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
# [ - + ]
# 4304 [ - + ]: 11289 : it->second.first != pfrom.GetId()) {
# 4305 [ # # ]: 0 : LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId());
# 4306 : 0 : return;
# 4307 : 0 : }
# 4308 : :
# 4309 : 11289 : PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
# 4310 : 11289 : ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
# 4311 [ - + ]: 11289 : if (status == READ_STATUS_INVALID) {
# 4312 : 0 : RemoveBlockRequest(resp.blockhash); // Reset in-flight state in case Misbehaving does not result in a disconnect
# 4313 : 0 : Misbehaving(*peer, 100, "invalid compact block/non-matching block transactions");
# 4314 : 0 : return;
# 4315 [ + + ]: 11289 : } else if (status == READ_STATUS_FAILED) {
# 4316 : : // Might have collided, fall back to getdata now :(
# 4317 : 1 : std::vector<CInv> invs;
# 4318 : 1 : invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(*peer), resp.blockhash));
# 4319 : 1 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
# 4320 : 11288 : } else {
# 4321 : : // Block is either okay, or possibly we received
# 4322 : : // READ_STATUS_CHECKBLOCK_FAILED.
# 4323 : : // Note that CheckBlock can only fail for one of a few reasons:
# 4324 : : // 1. bad-proof-of-work (impossible here, because we've already
# 4325 : : // accepted the header)
# 4326 : : // 2. merkleroot doesn't match the transactions given (already
# 4327 : : // caught in FillBlock with READ_STATUS_FAILED, so
# 4328 : : // impossible here)
# 4329 : : // 3. the block is otherwise invalid (eg invalid coinbase,
# 4330 : : // block is too big, too many legacy sigops, etc).
# 4331 : : // So if CheckBlock failed, #3 is the only possibility.
# 4332 : : // Under BIP 152, we don't discourage the peer unless proof of work is
# 4333 : : // invalid (we don't require all the stateless checks to have
# 4334 : : // been run). This is handled below, so just treat this as
# 4335 : : // though the block was successfully read, and rely on the
# 4336 : : // handling in ProcessNewBlock to ensure the block index is
# 4337 : : // updated, etc.
# 4338 : 11288 : RemoveBlockRequest(resp.blockhash); // it is now an empty pointer
# 4339 : 11288 : fBlockRead = true;
# 4340 : : // mapBlockSource is used for potentially punishing peers and
# 4341 : : // updating which peers send us compact blocks, so the race
# 4342 : : // between here and cs_main in ProcessNewBlock is fine.
# 4343 : : // BIP 152 permits peers to relay compact blocks after validating
# 4344 : : // the header only; we should not punish peers if the block turns
# 4345 : : // out to be invalid.
# 4346 : 11288 : mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom.GetId(), false));
# 4347 : 11288 : }
# 4348 : 11289 : } // Don't hold cs_main when we call into ProcessNewBlock
# 4349 [ + + ]: 11289 : if (fBlockRead) {
# 4350 : : // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
# 4351 : : // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
# 4352 : : // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
# 4353 : : // disk-space attacks), but this should be safe due to the
# 4354 : : // protections in the compact block handler -- see related comment
# 4355 : : // in compact block optimistic reconstruction handling.
# 4356 : 11288 : ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
# 4357 : 11288 : }
# 4358 : 11289 : return;
# 4359 : 11289 : }
# 4360 : :
# 4361 [ + + ]: 45259 : if (msg_type == NetMsgType::HEADERS)
# 4362 : 7789 : {
# 4363 : : // Ignore headers received while importing
# 4364 [ - + ][ - + ]: 7789 : if (fImporting || fReindex) {
# 4365 [ # # ]: 0 : LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
# 4366 : 0 : return;
# 4367 : 0 : }
# 4368 : :
# 4369 : : // Assume that this is in response to any outstanding getheaders
# 4370 : : // request we may have sent, and clear out the time of our last request
# 4371 : 7789 : peer->m_last_getheaders_timestamp = {};
# 4372 : :
# 4373 : 7789 : std::vector<CBlockHeader> headers;
# 4374 : :
# 4375 : : // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
# 4376 : 7789 : unsigned int nCount = ReadCompactSize(vRecv);
# 4377 [ + + ]: 7789 : if (nCount > MAX_HEADERS_RESULTS) {
# 4378 : 1 : Misbehaving(*peer, 20, strprintf("headers message size = %u", nCount));
# 4379 : 1 : return;
# 4380 : 1 : }
# 4381 : 7788 : headers.resize(nCount);
# 4382 [ + + ]: 532086 : for (unsigned int n = 0; n < nCount; n++) {
# 4383 : 524298 : vRecv >> headers[n];
# 4384 : 524298 : ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
# 4385 : 524298 : }
# 4386 : :
# 4387 : 7788 : ProcessHeadersMessage(pfrom, *peer, std::move(headers), /*via_compact_block=*/false);
# 4388 : :
# 4389 : : // Check if the headers presync progress needs to be reported to validation.
# 4390 : : // This needs to be done without holding the m_headers_presync_mutex lock.
# 4391 [ + + ]: 7788 : if (m_headers_presync_should_signal.exchange(false)) {
# 4392 : 11 : HeadersPresyncStats stats;
# 4393 : 11 : {
# 4394 : 11 : LOCK(m_headers_presync_mutex);
# 4395 : 11 : auto it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
# 4396 [ + - ]: 11 : if (it != m_headers_presync_stats.end()) stats = it->second;
# 4397 : 11 : }
# 4398 [ + - ]: 11 : if (stats.second) {
# 4399 : 11 : m_chainman.ReportHeadersPresync(stats.first, stats.second->first, stats.second->second);
# 4400 : 11 : }
# 4401 : 11 : }
# 4402 : :
# 4403 : 7788 : return;
# 4404 : 7789 : }
# 4405 : :
# 4406 [ + + ]: 37470 : if (msg_type == NetMsgType::BLOCK)
# 4407 : 30455 : {
# 4408 : : // Ignore block received while importing
# 4409 [ - + ][ - + ]: 30455 : if (fImporting || fReindex) {
# 4410 [ # # ]: 0 : LogPrint(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId());
# 4411 : 0 : return;
# 4412 : 0 : }
# 4413 : :
# 4414 : 30455 : std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
# 4415 : 30455 : vRecv >> *pblock;
# 4416 : :
# 4417 [ + + ]: 30455 : LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId());
# 4418 : :
# 4419 : 30455 : bool forceProcessing = false;
# 4420 : 30455 : const uint256 hash(pblock->GetHash());
# 4421 : 30455 : bool min_pow_checked = false;
# 4422 : 30455 : {
# 4423 : 30455 : LOCK(cs_main);
# 4424 : : // Always process the block if we requested it, since we may
# 4425 : : // need it even when it's not a candidate for a new best tip.
# 4426 : 30455 : forceProcessing = IsBlockRequested(hash);
# 4427 : 30455 : RemoveBlockRequest(hash);
# 4428 : : // mapBlockSource is only used for punishing peers and setting
# 4429 : : // which peers send us compact blocks, so the race between here and
# 4430 : : // cs_main in ProcessNewBlock is fine.
# 4431 : 30455 : mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
# 4432 : :
# 4433 : : // Check work on this block against our anti-dos thresholds.
# 4434 : 30455 : const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock);
# 4435 [ + + ][ + + ]: 30455 : if (prev_block && prev_block->nChainWork + CalculateHeadersWork({pblock->GetBlockHeader()}) >= GetAntiDoSWorkThreshold()) {
# [ + + ]
# 4436 : 21841 : min_pow_checked = true;
# 4437 : 21841 : }
# 4438 : 30455 : }
# 4439 : 30455 : ProcessBlock(pfrom, pblock, forceProcessing, min_pow_checked);
# 4440 : 30455 : return;
# 4441 : 30455 : }
# 4442 : :
# 4443 [ + + ]: 7015 : if (msg_type == NetMsgType::GETADDR) {
# 4444 : : // This asymmetric behavior for inbound and outbound connections was introduced
# 4445 : : // to prevent a fingerprinting attack: an attacker can send specific fake addresses
# 4446 : : // to users' AddrMan and later request them by sending getaddr messages.
# 4447 : : // Making nodes which are behind NAT and can only make outgoing connections ignore
# 4448 : : // the getaddr message mitigates the attack.
# 4449 [ + + ]: 816 : if (!pfrom.IsInboundConn()) {
# 4450 [ + - ]: 57 : LogPrint(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId());
# 4451 : 57 : return;
# 4452 : 57 : }
# 4453 : :
# 4454 : : // Since this must be an inbound connection, SetupAddressRelay will
# 4455 : : // never fail.
# 4456 : 759 : Assume(SetupAddressRelay(pfrom, *peer));
# 4457 : :
# 4458 : : // Only send one GetAddr response per connection to reduce resource waste
# 4459 : : // and discourage addr stamping of INV announcements.
# 4460 [ + + ]: 759 : if (peer->m_getaddr_recvd) {
# 4461 [ + - ]: 18 : LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId());
# 4462 : 18 : return;
# 4463 : 18 : }
# 4464 : 741 : peer->m_getaddr_recvd = true;
# 4465 : :
# 4466 : 741 : peer->m_addrs_to_send.clear();
# 4467 : 741 : std::vector<CAddress> vAddr;
# 4468 [ + + ]: 741 : if (pfrom.HasPermission(NetPermissionFlags::Addr)) {
# 4469 : 31 : vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /*network=*/std::nullopt);
# 4470 : 710 : } else {
# 4471 : 710 : vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
# 4472 : 710 : }
# 4473 : 741 : FastRandomContext insecure_rand;
# 4474 [ + + ]: 18877 : for (const CAddress &addr : vAddr) {
# 4475 : 18877 : PushAddress(*peer, addr, insecure_rand);
# 4476 : 18877 : }
# 4477 : 741 : return;
# 4478 : 759 : }
# 4479 : :
# 4480 [ + + ]: 6199 : if (msg_type == NetMsgType::MEMPOOL) {
# 4481 [ + + ][ + - ]: 2 : if (!(peer->m_our_services & NODE_BLOOM) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
# 4482 : 1 : {
# 4483 [ + - ]: 1 : if (!pfrom.HasPermission(NetPermissionFlags::NoBan))
# 4484 : 1 : {
# 4485 [ + - ]: 1 : LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom.GetId());
# 4486 : 1 : pfrom.fDisconnect = true;
# 4487 : 1 : }
# 4488 : 1 : return;
# 4489 : 1 : }
# 4490 : :
# 4491 [ - + ][ # # ]: 1 : if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
# 4492 : 0 : {
# 4493 [ # # ]: 0 : if (!pfrom.HasPermission(NetPermissionFlags::NoBan))
# 4494 : 0 : {
# 4495 [ # # ]: 0 : LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom.GetId());
# 4496 : 0 : pfrom.fDisconnect = true;
# 4497 : 0 : }
# 4498 : 0 : return;
# 4499 : 0 : }
# 4500 : :
# 4501 [ + - ]: 1 : if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
# 4502 : 1 : LOCK(tx_relay->m_tx_inventory_mutex);
# 4503 : 1 : tx_relay->m_send_mempool = true;
# 4504 : 1 : }
# 4505 : 1 : return;
# 4506 : 1 : }
# 4507 : :
# 4508 [ + + ]: 6197 : if (msg_type == NetMsgType::PING) {
# 4509 [ + - ]: 3197 : if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
# 4510 : 3197 : uint64_t nonce = 0;
# 4511 : 3197 : vRecv >> nonce;
# 4512 : : // Echo the message back with the nonce. This allows for two useful features:
# 4513 : : //
# 4514 : : // 1) A remote node can quickly check if the connection is operational
# 4515 : : // 2) Remote nodes can measure the latency of the network thread. If this node
# 4516 : : // is overloaded it won't respond to pings quickly and the remote node can
# 4517 : : // avoid sending us more work, like chain download requests.
# 4518 : : //
# 4519 : : // The nonce stops the remote getting confused between different pings: without
# 4520 : : // it, if the remote node sends a ping once per second and this node takes 5
# 4521 : : // seconds to respond to each, the 5th ping the remote sends would appear to
# 4522 : : // return very quickly.
# 4523 : 3197 : m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
# 4524 : 3197 : }
# 4525 : 3197 : return;
# 4526 : 3197 : }
# 4527 : :
# 4528 [ + + ]: 3000 : if (msg_type == NetMsgType::PONG) {
# 4529 : 2033 : const auto ping_end = time_received;
# 4530 : 2033 : uint64_t nonce = 0;
# 4531 : 2033 : size_t nAvail = vRecv.in_avail();
# 4532 : 2033 : bool bPingFinished = false;
# 4533 : 2033 : std::string sProblem;
# 4534 : :
# 4535 [ + + ]: 2033 : if (nAvail >= sizeof(nonce)) {
# 4536 : 2032 : vRecv >> nonce;
# 4537 : :
# 4538 : : // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
# 4539 [ + + ]: 2032 : if (peer->m_ping_nonce_sent != 0) {
# 4540 [ + + ]: 2031 : if (nonce == peer->m_ping_nonce_sent) {
# 4541 : : // Matching pong received, this ping is no longer outstanding
# 4542 : 2029 : bPingFinished = true;
# 4543 : 2029 : const auto ping_time = ping_end - peer->m_ping_start.load();
# 4544 [ + - ]: 2029 : if (ping_time.count() >= 0) {
# 4545 : : // Let connman know about this successful ping-pong
# 4546 : 2029 : pfrom.PongReceived(ping_time);
# 4547 : 2029 : } else {
# 4548 : : // This should never happen
# 4549 : 0 : sProblem = "Timing mishap";
# 4550 : 0 : }
# 4551 : 2029 : } else {
# 4552 : : // Nonce mismatches are normal when pings are overlapping
# 4553 : 2 : sProblem = "Nonce mismatch";
# 4554 [ + + ]: 2 : if (nonce == 0) {
# 4555 : : // This is most likely a bug in another implementation somewhere; cancel this ping
# 4556 : 1 : bPingFinished = true;
# 4557 : 1 : sProblem = "Nonce zero";
# 4558 : 1 : }
# 4559 : 2 : }
# 4560 : 2031 : } else {
# 4561 : 1 : sProblem = "Unsolicited pong without ping";
# 4562 : 1 : }
# 4563 : 2032 : } else {
# 4564 : : // This is most likely a bug in another implementation somewhere; cancel this ping
# 4565 : 1 : bPingFinished = true;
# 4566 : 1 : sProblem = "Short payload";
# 4567 : 1 : }
# 4568 : :
# 4569 [ + + ]: 2033 : if (!(sProblem.empty())) {
# 4570 [ + - ]: 4 : LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
# 4571 : 4 : pfrom.GetId(),
# 4572 : 4 : sProblem,
# 4573 : 4 : peer->m_ping_nonce_sent,
# 4574 : 4 : nonce,
# 4575 : 4 : nAvail);
# 4576 : 4 : }
# 4577 [ + + ]: 2033 : if (bPingFinished) {
# 4578 : 2031 : peer->m_ping_nonce_sent = 0;
# 4579 : 2031 : }
# 4580 : 2033 : return;
# 4581 : 2033 : }
# 4582 : :
# 4583 [ + + ]: 967 : if (msg_type == NetMsgType::FILTERLOAD) {
# 4584 [ + + ]: 10 : if (!(peer->m_our_services & NODE_BLOOM)) {
# 4585 [ + - ]: 1 : LogPrint(BCLog::NET, "filterload received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
# 4586 : 1 : pfrom.fDisconnect = true;
# 4587 : 1 : return;
# 4588 : 1 : }
# 4589 : 9 : CBloomFilter filter;
# 4590 : 9 : vRecv >> filter;
# 4591 : :
# 4592 [ + + ]: 9 : if (!filter.IsWithinSizeConstraints())
# 4593 : 2 : {
# 4594 : : // There is no excuse for sending a too-large filter
# 4595 : 2 : Misbehaving(*peer, 100, "too-large bloom filter");
# 4596 [ + - ]: 7 : } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
# 4597 : 7 : {
# 4598 : 7 : LOCK(tx_relay->m_bloom_filter_mutex);
# 4599 : 7 : tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
# 4600 : 7 : tx_relay->m_relay_txs = true;
# 4601 : 7 : }
# 4602 : 7 : pfrom.m_bloom_filter_loaded = true;
# 4603 : 7 : pfrom.m_relays_txs = true;
# 4604 : 7 : }
# 4605 : 9 : return;
# 4606 : 10 : }
# 4607 : :
# 4608 [ + + ]: 957 : if (msg_type == NetMsgType::FILTERADD) {
# 4609 [ + + ]: 7 : if (!(peer->m_our_services & NODE_BLOOM)) {
# 4610 [ + - ]: 1 : LogPrint(BCLog::NET, "filteradd received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
# 4611 : 1 : pfrom.fDisconnect = true;
# 4612 : 1 : return;
# 4613 : 1 : }
# 4614 : 6 : std::vector<unsigned char> vData;
# 4615 : 6 : vRecv >> vData;
# 4616 : :
# 4617 : : // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
# 4618 : : // and thus, the maximum size any matched object can have) in a filteradd message
# 4619 : 6 : bool bad = false;
# 4620 [ + + ]: 6 : if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
# 4621 : 1 : bad = true;
# 4622 [ + - ]: 5 : } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
# 4623 : 5 : LOCK(tx_relay->m_bloom_filter_mutex);
# 4624 [ + + ]: 5 : if (tx_relay->m_bloom_filter) {
# 4625 : 3 : tx_relay->m_bloom_filter->insert(vData);
# 4626 : 3 : } else {
# 4627 : 2 : bad = true;
# 4628 : 2 : }
# 4629 : 5 : }
# 4630 [ + + ]: 6 : if (bad) {
# 4631 : 3 : Misbehaving(*peer, 100, "bad filteradd message");
# 4632 : 3 : }
# 4633 : 6 : return;
# 4634 : 7 : }
# 4635 : :
# 4636 [ + + ]: 950 : if (msg_type == NetMsgType::FILTERCLEAR) {
# 4637 [ + + ]: 5 : if (!(peer->m_our_services & NODE_BLOOM)) {
# 4638 [ + - ]: 1 : LogPrint(BCLog::NET, "filterclear received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
# 4639 : 1 : pfrom.fDisconnect = true;
# 4640 : 1 : return;
# 4641 : 1 : }
# 4642 : 4 : auto tx_relay = peer->GetTxRelay();
# 4643 [ - + ]: 4 : if (!tx_relay) return;
# 4644 : :
# 4645 : 4 : {
# 4646 : 4 : LOCK(tx_relay->m_bloom_filter_mutex);
# 4647 : 4 : tx_relay->m_bloom_filter = nullptr;
# 4648 : 4 : tx_relay->m_relay_txs = true;
# 4649 : 4 : }
# 4650 : 4 : pfrom.m_bloom_filter_loaded = false;
# 4651 : 4 : pfrom.m_relays_txs = true;
# 4652 : 4 : return;
# 4653 : 4 : }
# 4654 : :
# 4655 [ + + ]: 945 : if (msg_type == NetMsgType::FEEFILTER) {
# 4656 : 928 : CAmount newFeeFilter = 0;
# 4657 : 928 : vRecv >> newFeeFilter;
# 4658 [ + - ]: 928 : if (MoneyRange(newFeeFilter)) {
# 4659 [ + - ]: 928 : if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
# 4660 : 928 : tx_relay->m_fee_filter_received = newFeeFilter;
# 4661 : 928 : }
# 4662 [ + - ]: 928 : LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
# 4663 : 928 : }
# 4664 : 928 : return;
# 4665 : 928 : }
# 4666 : :
# 4667 [ + + ]: 17 : if (msg_type == NetMsgType::GETCFILTERS) {
# 4668 : 4 : ProcessGetCFilters(pfrom, *peer, vRecv);
# 4669 : 4 : return;
# 4670 : 4 : }
# 4671 : :
# 4672 [ + + ]: 13 : if (msg_type == NetMsgType::GETCFHEADERS) {
# 4673 : 4 : ProcessGetCFHeaders(pfrom, *peer, vRecv);
# 4674 : 4 : return;
# 4675 : 4 : }
# 4676 : :
# 4677 [ + + ]: 9 : if (msg_type == NetMsgType::GETCFCHECKPT) {
# 4678 : 6 : ProcessGetCFCheckPt(pfrom, *peer, vRecv);
# 4679 : 6 : return;
# 4680 : 6 : }
# 4681 : :
# 4682 [ + - ]: 3 : if (msg_type == NetMsgType::NOTFOUND) {
# 4683 : 3 : std::vector<CInv> vInv;
# 4684 : 3 : vRecv >> vInv;
# 4685 [ + - ]: 3 : if (vInv.size() <= MAX_PEER_TX_ANNOUNCEMENTS + MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
# 4686 : 3 : LOCK(::cs_main);
# 4687 [ + + ]: 9 : for (CInv &inv : vInv) {
# 4688 [ + - ]: 9 : if (inv.IsGenTxMsg()) {
# 4689 : : // If we receive a NOTFOUND message for a tx we requested, mark the announcement for it as
# 4690 : : // completed in TxRequestTracker.
# 4691 : 9 : m_txrequest.ReceivedResponse(pfrom.GetId(), inv.hash);
# 4692 : 9 : }
# 4693 : 9 : }
# 4694 : 3 : }
# 4695 : 3 : return;
# 4696 : 3 : }
# 4697 : :
# 4698 : : // Ignore unknown commands for extensibility
# 4699 [ # # ]: 0 : LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
# 4700 : 0 : return;
# 4701 : 3 : }
# 4702 : :
# 4703 : : bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer)
# 4704 : 348823 : {
# 4705 : 348823 : {
# 4706 : 348823 : LOCK(peer.m_misbehavior_mutex);
# 4707 : :
# 4708 : : // There's nothing to do if the m_should_discourage flag isn't set
# 4709 [ + + ]: 348823 : if (!peer.m_should_discourage) return false;
# 4710 : :
# 4711 : 104 : peer.m_should_discourage = false;
# 4712 : 104 : } // peer.m_misbehavior_mutex
# 4713 : :
# 4714 [ + + ]: 104 : if (pnode.HasPermission(NetPermissionFlags::NoBan)) {
# 4715 : : // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission
# 4716 : 7 : LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id);
# 4717 : 7 : return false;
# 4718 : 7 : }
# 4719 : :
# 4720 [ + + ]: 97 : if (pnode.IsManualConn()) {
# 4721 : : // We never disconnect or discourage manual peers for bad behavior
# 4722 : 1 : LogPrintf("Warning: not punishing manually connected peer %d!\n", peer.m_id);
# 4723 : 1 : return false;
# 4724 : 1 : }
# 4725 : :
# 4726 [ + + ]: 96 : if (pnode.addr.IsLocal()) {
# 4727 : : // We disconnect local peers for bad behavior but don't discourage (since that would discourage
# 4728 : : // all peers on the same local address)
# 4729 [ + - ][ - + ]: 88 : LogPrint(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n",
# 4730 : 88 : pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
# 4731 : 88 : pnode.fDisconnect = true;
# 4732 : 88 : return true;
# 4733 : 88 : }
# 4734 : :
# 4735 : : // Normal case: Disconnect the peer and discourage all nodes sharing the address
# 4736 [ + - ]: 8 : LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id);
# 4737 [ + - ]: 8 : if (m_banman) m_banman->Discourage(pnode.addr);
# 4738 : 8 : m_connman.DisconnectNode(pnode.addr);
# 4739 : 8 : return true;
# 4740 : 96 : }
# 4741 : :
# 4742 : : bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
# 4743 : 348809 : {
# 4744 : 348809 : bool fMoreWork = false;
# 4745 : :
# 4746 : 348809 : PeerRef peer = GetPeerRef(pfrom->GetId());
# 4747 [ - + ]: 348809 : if (peer == nullptr) return false;
# 4748 : :
# 4749 : 348809 : {
# 4750 : 348809 : LOCK(peer->m_getdata_requests_mutex);
# 4751 [ + + ]: 348809 : if (!peer->m_getdata_requests.empty()) {
# 4752 : 1434 : ProcessGetData(*pfrom, *peer, interruptMsgProc);
# 4753 : 1434 : }
# 4754 : 348809 : }
# 4755 : :
# 4756 : 348809 : {
# 4757 : 348809 : LOCK2(cs_main, g_cs_orphans);
# 4758 [ + + ]: 348809 : if (!peer->m_orphan_work_set.empty()) {
# 4759 : 3 : ProcessOrphanTx(peer->m_orphan_work_set);
# 4760 : 3 : }
# 4761 : 348809 : }
# 4762 : :
# 4763 [ + + ]: 348809 : if (pfrom->fDisconnect)
# 4764 : 1 : return false;
# 4765 : :
# 4766 : : // this maintains the order of responses
# 4767 : : // and prevents m_getdata_requests to grow unbounded
# 4768 : 348808 : {
# 4769 : 348808 : LOCK(peer->m_getdata_requests_mutex);
# 4770 [ + + ]: 348808 : if (!peer->m_getdata_requests.empty()) return true;
# 4771 : 348808 : }
# 4772 : :
# 4773 : 347947 : {
# 4774 : 347947 : LOCK(g_cs_orphans);
# 4775 [ + + ]: 347947 : if (!peer->m_orphan_work_set.empty()) return true;
# 4776 : 347947 : }
# 4777 : :
# 4778 : : // Don't bother if send buffer is too full to respond anyway
# 4779 [ + + ]: 347945 : if (pfrom->fPauseSend) return false;
# 4780 : :
# 4781 : 347944 : std::list<CNetMessage> msgs;
# 4782 : 347944 : {
# 4783 : 347944 : LOCK(pfrom->cs_vProcessMsg);
# 4784 [ + + ]: 347944 : if (pfrom->vProcessMsg.empty()) return false;
# 4785 : : // Just take one message
# 4786 : 129533 : msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
# 4787 : 129533 : pfrom->nProcessQueueSize -= msgs.front().m_raw_message_size;
# 4788 : 129533 : pfrom->fPauseRecv = pfrom->nProcessQueueSize > m_connman.GetReceiveFloodSize();
# 4789 : 129533 : fMoreWork = !pfrom->vProcessMsg.empty();
# 4790 : 129533 : }
# 4791 : 0 : CNetMessage& msg(msgs.front());
# 4792 : :
# 4793 : 129533 : TRACE6(net, inbound_message,
# 4794 : 129533 : pfrom->GetId(),
# 4795 : 129533 : pfrom->m_addr_name.c_str(),
# 4796 : 129533 : pfrom->ConnectionTypeAsString().c_str(),
# 4797 : 129533 : msg.m_type.c_str(),
# 4798 : 129533 : msg.m_recv.size(),
# 4799 : 129533 : msg.m_recv.data()
# 4800 : 129533 : );
# 4801 : :
# 4802 [ + + ]: 129533 : if (gArgs.GetBoolArg("-capturemessages", false)) {
# 4803 : 6 : CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true);
# 4804 : 6 : }
# 4805 : :
# 4806 : 129533 : msg.SetVersion(pfrom->GetCommonVersion());
# 4807 : :
# 4808 : 129533 : try {
# 4809 : 129533 : ProcessMessage(*pfrom, msg.m_type, msg.m_recv, msg.m_time, interruptMsgProc);
# 4810 [ + + ]: 129533 : if (interruptMsgProc) return false;
# 4811 : 129531 : {
# 4812 : 129531 : LOCK(peer->m_getdata_requests_mutex);
# 4813 [ + + ]: 129531 : if (!peer->m_getdata_requests.empty()) fMoreWork = true;
# 4814 : 129531 : }
# 4815 : 129531 : } catch (const std::exception& e) {
# 4816 [ + - ]: 6 : 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());
# 4817 : 6 : } catch (...) {
# 4818 [ # # ]: 0 : LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size);
# 4819 : 0 : }
# 4820 : :
# 4821 : 129531 : return fMoreWork;
# 4822 : 129533 : }
# 4823 : :
# 4824 : : void PeerManagerImpl::ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds)
# 4825 : 345498 : {
# 4826 : 345498 : AssertLockHeld(cs_main);
# 4827 : :
# 4828 : 345498 : CNodeState &state = *State(pto.GetId());
# 4829 : 345498 : const CNetMsgMaker msgMaker(pto.GetCommonVersion());
# 4830 : :
# 4831 [ + - ][ + + ]: 345498 : if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) {
# [ + + ]
# 4832 : : // This is an outbound peer subject to disconnection if they don't
# 4833 : : // announce a block with as much work as the current tip within
# 4834 : : // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
# 4835 : : // their chain has more work than ours, we should sync to it,
# 4836 : : // unless it's invalid, in which case we should find that out and
# 4837 : : // disconnect from them elsewhere).
# 4838 [ - + ][ # # ]: 2138 : if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
# 4839 [ # # ]: 0 : if (state.m_chain_sync.m_timeout != 0s) {
# 4840 : 0 : state.m_chain_sync.m_timeout = 0s;
# 4841 : 0 : state.m_chain_sync.m_work_header = nullptr;
# 4842 : 0 : state.m_chain_sync.m_sent_getheaders = false;
# 4843 : 0 : }
# 4844 [ + + ][ + + ]: 2138 : } 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)) {
# [ + - ][ - + ]
# [ # # ]
# 4845 : : // Our best block known by this peer is behind our tip, and we're either noticing
# 4846 : : // that for the first time, OR this peer was able to catch up to some earlier point
# 4847 : : // where we checked against our tip.
# 4848 : : // Either way, set a new timeout based on current tip.
# 4849 : 55 : state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
# 4850 : 55 : state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
# 4851 : 55 : state.m_chain_sync.m_sent_getheaders = false;
# 4852 [ + - ][ + + ]: 2083 : } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) {
# [ + + ]
# 4853 : : // No evidence yet that our peer has synced to a chain with work equal to that
# 4854 : : // of our tip, when we first detected it was behind. Send a single getheaders
# 4855 : : // message to give the peer a chance to update us.
# 4856 [ + + ]: 5 : if (state.m_chain_sync.m_sent_getheaders) {
# 4857 : : // They've run out of time to catch up!
# 4858 [ - + ]: 2 : LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
# 4859 : 2 : pto.fDisconnect = true;
# 4860 : 3 : } else {
# 4861 : 3 : assert(state.m_chain_sync.m_work_header);
# 4862 : : // Here, we assume that the getheaders message goes out,
# 4863 : : // because it'll either go out or be skipped because of a
# 4864 : : // getheaders in-flight already, in which case the peer should
# 4865 : : // still respond to us with a sufficiently high work chain tip.
# 4866 : 0 : MaybeSendGetHeaders(pto,
# 4867 : 3 : GetLocator(state.m_chain_sync.m_work_header->pprev),
# 4868 : 3 : peer);
# 4869 [ + - ][ - + ]: 3 : 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());
# 4870 : 3 : state.m_chain_sync.m_sent_getheaders = true;
# 4871 : : // Bump the timeout to allow a response, which could clear the timeout
# 4872 : : // (if the response shows the peer has synced), reset the timeout (if
# 4873 : : // the peer syncs to the required work but not to our tip), or result
# 4874 : : // in disconnect (if we advance to the timeout and pindexBestKnownBlock
# 4875 : : // has not sufficiently progressed)
# 4876 : 3 : state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
# 4877 : 3 : }
# 4878 : 5 : }
# 4879 : 2138 : }
# 4880 : 345498 : }
# 4881 : :
# 4882 : : void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now)
# 4883 : 141 : {
# 4884 : : // If we have any extra block-relay-only peers, disconnect the youngest unless
# 4885 : : // it's given us a block -- in which case, compare with the second-youngest, and
# 4886 : : // out of those two, disconnect the peer who least recently gave us a block.
# 4887 : : // The youngest block-relay-only peer would be the extra peer we connected
# 4888 : : // to temporarily in order to sync our tip; see net.cpp.
# 4889 : : // Note that we use higher nodeid as a measure for most recent connection.
# 4890 [ + + ]: 141 : if (m_connman.GetExtraBlockRelayCount() > 0) {
# 4891 : 6 : std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0};
# 4892 : :
# 4893 : 18 : m_connman.ForEachNode([&](CNode* pnode) {
# 4894 [ - + ][ - + ]: 18 : if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return;
# 4895 [ + - ]: 18 : if (pnode->GetId() > youngest_peer.first) {
# 4896 : 18 : next_youngest_peer = youngest_peer;
# 4897 : 18 : youngest_peer.first = pnode->GetId();
# 4898 : 18 : youngest_peer.second = pnode->m_last_block_time;
# 4899 : 18 : }
# 4900 : 18 : });
# 4901 : 6 : NodeId to_disconnect = youngest_peer.first;
# 4902 [ + + ]: 6 : if (youngest_peer.second > next_youngest_peer.second) {
# 4903 : : // Our newest block-relay-only peer gave us a block more recently;
# 4904 : : // disconnect our second youngest.
# 4905 : 2 : to_disconnect = next_youngest_peer.first;
# 4906 : 2 : }
# 4907 : 6 : m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
# 4908 : 6 : AssertLockHeld(::cs_main);
# 4909 : : // Make sure we're not getting a block right now, and that
# 4910 : : // we've been connected long enough for this eviction to happen
# 4911 : : // at all.
# 4912 : : // Note that we only request blocks from a peer if we learn of a
# 4913 : : // valid headers chain with at least as much work as our tip.
# 4914 : 6 : CNodeState *node_state = State(pnode->GetId());
# 4915 [ - + ][ + + ]: 6 : if (node_state == nullptr ||
# 4916 [ + + ][ + - ]: 6 : (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->nBlocksInFlight == 0)) {
# 4917 : 4 : pnode->fDisconnect = true;
# 4918 [ + - ]: 4 : LogPrint(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n",
# 4919 : 4 : pnode->GetId(), count_seconds(pnode->m_last_block_time));
# 4920 : 4 : return true;
# 4921 : 4 : } else {
# 4922 [ + - ]: 2 : LogPrint(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
# 4923 : 2 : pnode->GetId(), count_seconds(pnode->m_connected), node_state->nBlocksInFlight);
# 4924 : 2 : }
# 4925 : 2 : return false;
# 4926 : 6 : });
# 4927 : 6 : }
# 4928 : :
# 4929 : : // Check whether we have too many outbound-full-relay peers
# 4930 [ + + ]: 141 : if (m_connman.GetExtraFullOutboundCount() > 0) {
# 4931 : : // If we have more outbound-full-relay peers than we target, disconnect one.
# 4932 : : // Pick the outbound-full-relay peer that least recently announced
# 4933 : : // us a new block, with ties broken by choosing the more recent
# 4934 : : // connection (higher node id)
# 4935 : 4 : NodeId worst_peer = -1;
# 4936 : 4 : int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
# 4937 : :
# 4938 : 36 : m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
# 4939 : 36 : AssertLockHeld(::cs_main);
# 4940 : :
# 4941 : : // Only consider outbound-full-relay peers that are not already
# 4942 : : // marked for disconnection
# 4943 [ - + ][ - + ]: 36 : if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return;
# 4944 : 36 : CNodeState *state = State(pnode->GetId());
# 4945 [ - + ]: 36 : if (state == nullptr) return; // shouldn't be possible, but just in case
# 4946 : : // Don't evict our protected peers
# 4947 [ - + ]: 36 : if (state->m_chain_sync.m_protect) return;
# 4948 [ + + ][ + + ]: 36 : if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
# [ + - ]
# 4949 : 34 : worst_peer = pnode->GetId();
# 4950 : 34 : oldest_block_announcement = state->m_last_block_announcement;
# 4951 : 34 : }
# 4952 : 36 : });
# 4953 [ + - ]: 4 : if (worst_peer != -1) {
# 4954 : 4 : bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
# 4955 : 4 : AssertLockHeld(::cs_main);
# 4956 : :
# 4957 : : // Only disconnect a peer that has been connected to us for
# 4958 : : // some reasonable fraction of our check-frequency, to give
# 4959 : : // it time for new information to have arrived.
# 4960 : : // Also don't disconnect any peer we're trying to download a
# 4961 : : // block from.
# 4962 : 4 : CNodeState &state = *State(pnode->GetId());
# 4963 [ + - ][ + - ]: 4 : if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
# [ + - ]
# 4964 [ + - ]: 4 : LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
# 4965 : 4 : pnode->fDisconnect = true;
# 4966 : 4 : return true;
# 4967 : 4 : } else {
# 4968 [ # # ]: 0 : LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
# 4969 : 0 : pnode->GetId(), count_seconds(pnode->m_connected), state.nBlocksInFlight);
# 4970 : 0 : return false;
# 4971 : 0 : }
# 4972 : 4 : });
# 4973 [ + - ]: 4 : if (disconnected) {
# 4974 : : // If we disconnected an extra peer, that means we successfully
# 4975 : : // connected to at least one peer after the last time we
# 4976 : : // detected a stale tip. Don't try any more extra peers until
# 4977 : : // we next detect a stale tip, to limit the load we put on the
# 4978 : : // network from these extra connections.
# 4979 : 4 : m_connman.SetTryNewOutboundPeer(false);
# 4980 : 4 : }
# 4981 : 4 : }
# 4982 : 4 : }
# 4983 : 141 : }
# 4984 : :
# 4985 : : void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
# 4986 : 141 : {
# 4987 : 141 : LOCK(cs_main);
# 4988 : :
# 4989 : 141 : auto now{GetTime<std::chrono::seconds>()};
# 4990 : :
# 4991 : 141 : EvictExtraOutboundPeers(now);
# 4992 : :
# 4993 [ + + ]: 141 : if (now > m_stale_tip_check_time) {
# 4994 : : // Check whether our tip is stale, and if so, allow using an extra
# 4995 : : // outbound peer
# 4996 [ + - ][ + - ]: 69 : if (!fImporting && !fReindex && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
# [ + - ][ + + ]
# [ + + ]
# 4997 : 2 : LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
# 4998 : 2 : count_seconds(now - m_last_tip_update.load()));
# 4999 : 2 : m_connman.SetTryNewOutboundPeer(true);
# 5000 [ - + ]: 67 : } else if (m_connman.GetTryNewOutboundPeer()) {
# 5001 : 0 : m_connman.SetTryNewOutboundPeer(false);
# 5002 : 0 : }
# 5003 : 69 : m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
# 5004 : 69 : }
# 5005 : :
# 5006 [ + + ][ + + ]: 141 : if (!m_initial_sync_finished && CanDirectFetch()) {
# 5007 : 52 : m_connman.StartExtraBlockRelayPeers();
# 5008 : 52 : m_initial_sync_finished = true;
# 5009 : 52 : }
# 5010 : 141 : }
# 5011 : :
# 5012 : : void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now)
# 5013 : 345499 : {
# 5014 [ + + ][ + + ]: 345499 : if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
# 5015 [ + + ]: 345499 : peer.m_ping_nonce_sent &&
# 5016 [ + + ]: 345499 : now > peer.m_ping_start.load() + TIMEOUT_INTERVAL)
# 5017 : 1 : {
# 5018 : : // The ping timeout is using mocktime. To disable the check during
# 5019 : : // testing, increase -peertimeout.
# 5020 [ + - ]: 1 : LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), peer.m_id);
# 5021 : 1 : node_to.fDisconnect = true;
# 5022 : 1 : return;
# 5023 : 1 : }
# 5024 : :
# 5025 : 345498 : const CNetMsgMaker msgMaker(node_to.GetCommonVersion());
# 5026 : 345498 : bool pingSend = false;
# 5027 : :
# 5028 [ + + ]: 345498 : if (peer.m_ping_queued) {
# 5029 : : // RPC ping request by user
# 5030 : 3 : pingSend = true;
# 5031 : 3 : }
# 5032 : :
# 5033 [ + + ][ + + ]: 345498 : if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) {
# [ + + ]
# 5034 : : // Ping automatically sent as a latency probe & keepalive.
# 5035 : 2035 : pingSend = true;
# 5036 : 2035 : }
# 5037 : :
# 5038 [ + + ]: 345498 : if (pingSend) {
# 5039 : 2038 : uint64_t nonce;
# 5040 : 2038 : do {
# 5041 : 2038 : nonce = GetRand<uint64_t>();
# 5042 [ - + ]: 2038 : } while (nonce == 0);
# 5043 : 2038 : peer.m_ping_queued = false;
# 5044 : 2038 : peer.m_ping_start = now;
# 5045 [ + - ]: 2038 : if (node_to.GetCommonVersion() > BIP0031_VERSION) {
# 5046 : 2038 : peer.m_ping_nonce_sent = nonce;
# 5047 : 2038 : m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING, nonce));
# 5048 : 2038 : } else {
# 5049 : : // Peer is too old to support ping command with nonce, pong will never arrive.
# 5050 : 0 : peer.m_ping_nonce_sent = 0;
# 5051 : 0 : m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING));
# 5052 : 0 : }
# 5053 : 2038 : }
# 5054 : 345498 : }
# 5055 : :
# 5056 : : void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time)
# 5057 : 345498 : {
# 5058 : : // Nothing to do for non-address-relay peers
# 5059 [ + + ]: 345498 : if (!peer.m_addr_relay_enabled) return;
# 5060 : :
# 5061 : 344035 : LOCK(peer.m_addr_send_times_mutex);
# 5062 : : // Periodically advertise our local address to the peer.
# 5063 [ + - ][ + + ]: 344035 : if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
# 5064 [ + + ]: 344035 : peer.m_next_local_addr_send < current_time) {
# 5065 : : // If we've sent before, clear the bloom filter for the peer, so that our
# 5066 : : // self-announcement will actually go out.
# 5067 : : // This might be unnecessary if the bloom filter has already rolled
# 5068 : : // over since our last self-announcement, but there is only a small
# 5069 : : // bandwidth cost that we can incur by doing this (which happens
# 5070 : : // once a day on average).
# 5071 [ + + ]: 1284 : if (peer.m_next_local_addr_send != 0us) {
# 5072 : 233 : peer.m_addr_known->reset();
# 5073 : 233 : }
# 5074 [ + + ]: 1284 : if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
# 5075 : 7 : CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()};
# 5076 : 7 : FastRandomContext insecure_rand;
# 5077 : 7 : PushAddress(peer, local_addr, insecure_rand);
# 5078 : 7 : }
# 5079 : 1284 : peer.m_next_local_addr_send = GetExponentialRand(current_time, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
# 5080 : 1284 : }
# 5081 : :
# 5082 : : // We sent an `addr` message to this peer recently. Nothing more to do.
# 5083 [ + + ]: 344035 : if (current_time <= peer.m_next_addr_send) return;
# 5084 : :
# 5085 : 2481 : peer.m_next_addr_send = GetExponentialRand(current_time, AVG_ADDRESS_BROADCAST_INTERVAL);
# 5086 : :
# 5087 [ - + ]: 2481 : if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) {
# 5088 : : // Should be impossible since we always check size before adding to
# 5089 : : // m_addrs_to_send. Recover by trimming the vector.
# 5090 : 0 : peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND);
# 5091 : 0 : }
# 5092 : :
# 5093 : : // Remove addr records that the peer already knows about, and add new
# 5094 : : // addrs to the m_addr_known filter on the same pass.
# 5095 : 18945 : auto addr_already_known = [&peer](const CAddress& addr) {
# 5096 : 18945 : bool ret = peer.m_addr_known->contains(addr.GetKey());
# 5097 [ + + ]: 18945 : if (!ret) peer.m_addr_known->insert(addr.GetKey());
# 5098 : 18945 : return ret;
# 5099 : 18945 : };
# 5100 : 2481 : peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known),
# 5101 : 2481 : peer.m_addrs_to_send.end());
# 5102 : :
# 5103 : : // No addr messages to send
# 5104 [ + + ]: 2481 : if (peer.m_addrs_to_send.empty()) return;
# 5105 : :
# 5106 : 105 : const char* msg_type;
# 5107 : 105 : int make_flags;
# 5108 [ + + ]: 105 : if (peer.m_wants_addrv2) {
# 5109 : 3 : msg_type = NetMsgType::ADDRV2;
# 5110 : 3 : make_flags = ADDRV2_FORMAT;
# 5111 : 102 : } else {
# 5112 : 102 : msg_type = NetMsgType::ADDR;
# 5113 : 102 : make_flags = 0;
# 5114 : 102 : }
# 5115 : 105 : m_connman.PushMessage(&node, CNetMsgMaker(node.GetCommonVersion()).Make(make_flags, msg_type, peer.m_addrs_to_send));
# 5116 : 105 : peer.m_addrs_to_send.clear();
# 5117 : :
# 5118 : : // we only send the big addr message once
# 5119 [ + + ]: 105 : if (peer.m_addrs_to_send.capacity() > 40) {
# 5120 : 21 : peer.m_addrs_to_send.shrink_to_fit();
# 5121 : 21 : }
# 5122 : 105 : }
# 5123 : :
# 5124 : : void PeerManagerImpl::MaybeSendSendHeaders(CNode& node, Peer& peer)
# 5125 : 345498 : {
# 5126 : : // Delay sending SENDHEADERS (BIP 130) until we're done with an
# 5127 : : // initial-headers-sync with this peer. Receiving headers announcements for
# 5128 : : // new blocks while trying to sync their headers chain is problematic,
# 5129 : : // because of the state tracking done.
# 5130 [ + + ][ + - ]: 345498 : if (!peer.m_sent_sendheaders && node.GetCommonVersion() >= SENDHEADERS_VERSION) {
# 5131 : 102568 : LOCK(cs_main);
# 5132 : 102568 : CNodeState &state = *State(node.GetId());
# 5133 [ + + ]: 102568 : if (state.pindexBestKnownBlock != nullptr &&
# 5134 [ + + ]: 102568 : state.pindexBestKnownBlock->nChainWork > nMinimumChainWork) {
# 5135 : : // Tell our peer we prefer to receive headers rather than inv's
# 5136 : : // We send this to non-NODE NETWORK peers as well, because even
# 5137 : : // non-NODE NETWORK peers can announce blocks (such as pruning
# 5138 : : // nodes)
# 5139 : 664 : m_connman.PushMessage(&node, CNetMsgMaker(node.GetCommonVersion()).Make(NetMsgType::SENDHEADERS));
# 5140 : 664 : peer.m_sent_sendheaders = true;
# 5141 : 664 : }
# 5142 : 102568 : }
# 5143 : 345498 : }
# 5144 : :
# 5145 : : void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time)
# 5146 : 345498 : {
# 5147 [ + + ]: 345498 : if (m_ignore_incoming_txs) return;
# 5148 [ - + ]: 345006 : if (pto.GetCommonVersion() < FEEFILTER_VERSION) return;
# 5149 : : // peers with the forcerelay permission should not filter txs to us
# 5150 [ + + ]: 345006 : if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return;
# 5151 : : // Don't send feefilter messages to outbound block-relay-only peers since they should never announce
# 5152 : : // transactions to us, regardless of feefilter state.
# 5153 [ + + ]: 344854 : if (pto.IsBlockOnlyConn()) return;
# 5154 : :
# 5155 : 344169 : CAmount currentFilter = m_mempool.GetMinFee().GetFeePerK();
# 5156 : 344169 : static FeeFilterRounder g_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}};
# 5157 : :
# 5158 [ + + ]: 344169 : if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
# 5159 : : // Received tx-inv messages are discarded when the active
# 5160 : : // chainstate is in IBD, so tell the peer to not send them.
# 5161 : 12810 : currentFilter = MAX_MONEY;
# 5162 : 331359 : } else {
# 5163 : 331359 : static const CAmount MAX_FILTER{g_filter_rounder.round(MAX_MONEY)};
# 5164 [ + + ]: 331359 : if (peer.m_fee_filter_sent == MAX_FILTER) {
# 5165 : : // Send the current filter if we sent MAX_FILTER previously
# 5166 : : // and made it out of IBD.
# 5167 : 241 : peer.m_next_send_feefilter = 0us;
# 5168 : 241 : }
# 5169 : 331359 : }
# 5170 [ + + ]: 344169 : if (current_time > peer.m_next_send_feefilter) {
# 5171 : 2460 : CAmount filterToSend = g_filter_rounder.round(currentFilter);
# 5172 : : // We always have a fee filter of at least the min relay fee
# 5173 : 2460 : filterToSend = std::max(filterToSend, m_mempool.m_min_relay_feerate.GetFeePerK());
# 5174 [ + + ]: 2460 : if (filterToSend != peer.m_fee_filter_sent) {
# 5175 : 1367 : m_connman.PushMessage(&pto, CNetMsgMaker(pto.GetCommonVersion()).Make(NetMsgType::FEEFILTER, filterToSend));
# 5176 : 1367 : peer.m_fee_filter_sent = filterToSend;
# 5177 : 1367 : }
# 5178 : 2460 : peer.m_next_send_feefilter = GetExponentialRand(current_time, AVG_FEEFILTER_BROADCAST_INTERVAL);
# 5179 : 2460 : }
# 5180 : : // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
# 5181 : : // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
# 5182 [ + + ][ + + ]: 341709 : else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter &&
# 5183 [ + + ][ + - ]: 341709 : (currentFilter < 3 * peer.m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
# 5184 : 1463 : peer.m_next_send_feefilter = current_time + GetRandomDuration<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
# 5185 : 1463 : }
# 5186 : 344169 : }
# 5187 : :
# 5188 : : namespace {
# 5189 : : class CompareInvMempoolOrder
# 5190 : : {
# 5191 : : CTxMemPool* mp;
# 5192 : : bool m_wtxid_relay;
# 5193 : : public:
# 5194 : : explicit CompareInvMempoolOrder(CTxMemPool *_mempool, bool use_wtxid)
# 5195 : 86957 : {
# 5196 : 86957 : mp = _mempool;
# 5197 : 86957 : m_wtxid_relay = use_wtxid;
# 5198 : 86957 : }
# 5199 : :
# 5200 : : bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
# 5201 : 89593 : {
# 5202 : : /* As std::make_heap produces a max-heap, we want the entries with the
# 5203 : : * fewest ancestors/highest fee to sort later. */
# 5204 : 89593 : return mp->CompareDepthAndScore(*b, *a, m_wtxid_relay);
# 5205 : 89593 : }
# 5206 : : };
# 5207 : : } // namespace
# 5208 : :
# 5209 : : bool PeerManagerImpl::RejectIncomingTxs(const CNode& peer) const
# 5210 : 22490 : {
# 5211 : : // block-relay-only peers may never send txs to us
# 5212 [ + + ]: 22490 : if (peer.IsBlockOnlyConn()) return true;
# 5213 : : // In -blocksonly mode, peers need the 'relay' permission to send txs to us
# 5214 [ + + ][ + + ]: 22488 : if (m_ignore_incoming_txs && !peer.HasPermission(NetPermissionFlags::Relay)) return true;
# 5215 : 22486 : return false;
# 5216 : 22488 : }
# 5217 : :
# 5218 : : bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer)
# 5219 : 1227 : {
# 5220 : : // We don't participate in addr relay with outbound block-relay-only
# 5221 : : // connections to prevent providing adversaries with the additional
# 5222 : : // information of addr traffic to infer the link.
# 5223 [ + + ]: 1227 : if (node.IsBlockOnlyConn()) return false;
# 5224 : :
# 5225 [ + + ]: 1203 : if (!peer.m_addr_relay_enabled.exchange(true)) {
# 5226 : : // First addr message we have received from the peer, initialize
# 5227 : : // m_addr_known
# 5228 : 1139 : peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
# 5229 : 1139 : }
# 5230 : :
# 5231 : 1203 : return true;
# 5232 : 1227 : }
# 5233 : :
# 5234 : : bool PeerManagerImpl::SendMessages(CNode* pto)
# 5235 : 348823 : {
# 5236 : 348823 : PeerRef peer = GetPeerRef(pto->GetId());
# 5237 [ - + ]: 348823 : if (!peer) return false;
# 5238 : 348823 : const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
# 5239 : :
# 5240 : : // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
# 5241 : : // disconnect misbehaving peers even before the version handshake is complete.
# 5242 [ + + ]: 348823 : if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true;
# 5243 : :
# 5244 : : // Don't send anything until the version handshake is complete
# 5245 [ + + ][ + + ]: 348727 : if (!pto->fSuccessfullyConnected || pto->fDisconnect)
# 5246 : 3227 : return true;
# 5247 : :
# 5248 : : // If we get here, the outgoing message serialization version is set and can't change.
# 5249 : 345500 : const CNetMsgMaker msgMaker(pto->GetCommonVersion());
# 5250 : :
# 5251 : 345500 : const auto current_time{GetTime<std::chrono::microseconds>()};
# 5252 : :
# 5253 [ + + ][ + + ]: 345500 : if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
# [ + + ]
# 5254 [ + - ]: 1 : LogPrint(BCLog::NET, "addrfetch connection timeout; disconnecting peer=%d\n", pto->GetId());
# 5255 : 1 : pto->fDisconnect = true;
# 5256 : 1 : return true;
# 5257 : 1 : }
# 5258 : :
# 5259 : 345499 : MaybeSendPing(*pto, *peer, current_time);
# 5260 : :
# 5261 : : // MaybeSendPing may have marked peer for disconnection
# 5262 [ + + ]: 345499 : if (pto->fDisconnect) return true;
# 5263 : :
# 5264 : 345498 : MaybeSendAddr(*pto, *peer, current_time);
# 5265 : :
# 5266 : 345498 : MaybeSendSendHeaders(*pto, *peer);
# 5267 : :
# 5268 : 345498 : {
# 5269 : 345498 : LOCK(cs_main);
# 5270 : :
# 5271 : 345498 : CNodeState &state = *State(pto->GetId());
# 5272 : :
# 5273 : : // Start block sync
# 5274 [ - + ]: 345498 : if (m_chainman.m_best_header == nullptr) {
# 5275 : 0 : m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
# 5276 : 0 : }
# 5277 : :
# 5278 : : // Determine whether we might try initial headers sync or parallel
# 5279 : : // block download from this peer -- this mostly affects behavior while
# 5280 : : // in IBD (once out of IBD, we sync from all peers).
# 5281 : 345498 : bool sync_blocks_and_headers_from_peer = false;
# 5282 [ + + ]: 345498 : if (state.fPreferredDownload) {
# 5283 : 238666 : sync_blocks_and_headers_from_peer = true;
# 5284 [ + + ][ + + ]: 238666 : } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) {
# 5285 : : // Typically this is an inbound peer. If we don't have any outbound
# 5286 : : // peers, or if we aren't downloading any blocks from such peers,
# 5287 : : // then allow block downloads from this peer, too.
# 5288 : : // We prefer downloading blocks from outbound peers to avoid
# 5289 : : // putting undue load on (say) some home user who is just making
# 5290 : : // outbound connections to the network, but if our only source of
# 5291 : : // the latest blocks is from an inbound peer, we have to be sure to
# 5292 : : // eventually download it (and not just wait indefinitely for an
# 5293 : : // outbound peer to have it).
# 5294 [ + + ][ + + ]: 106167 : if (m_num_preferred_download_peers == 0 || mapBlocksInFlight.empty()) {
# 5295 : 100125 : sync_blocks_and_headers_from_peer = true;
# 5296 : 100125 : }
# 5297 : 106167 : }
# 5298 : :
# 5299 [ + + ][ + + ]: 345498 : if (!state.fSyncStarted && CanServeBlocks(*peer) && !fImporting && !fReindex) {
# [ + - ][ + - ]
# 5300 : : // Only actively request headers from a single peer, unless we're close to today.
# 5301 [ + + ][ + + ]: 2861 : if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->Time() > GetAdjustedTime() - 24h) {
# [ + + ][ + + ]
# 5302 : 1138 : const CBlockIndex* pindexStart = m_chainman.m_best_header;
# 5303 : : /* If possible, start at the block preceding the currently
# 5304 : : best known header. This ensures that we always get a
# 5305 : : non-empty list of headers back as long as the peer
# 5306 : : is up-to-date. With a non-empty response, we can initialise
# 5307 : : the peer's known best block. This wouldn't be possible
# 5308 : : if we requested starting at m_chainman.m_best_header and
# 5309 : : got back an empty response. */
# 5310 [ + + ]: 1138 : if (pindexStart->pprev)
# 5311 : 916 : pindexStart = pindexStart->pprev;
# 5312 [ + + ]: 1138 : if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) {
# 5313 [ + - ]: 1136 : LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height);
# 5314 : :
# 5315 : 1136 : state.fSyncStarted = true;
# 5316 : 1136 : state.m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
# 5317 : 1136 : (
# 5318 : : // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
# 5319 : : // to maintain precision
# 5320 : 1136 : std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
# 5321 : 1136 : Ticks<std::chrono::seconds>(GetAdjustedTime() - m_chainman.m_best_header->Time()) / consensusParams.nPowTargetSpacing
# 5322 : 1136 : );
# 5323 : 1136 : nSyncStarted++;
# 5324 : 1136 : }
# 5325 : 1138 : }
# 5326 : 2861 : }
# 5327 : :
# 5328 : : //
# 5329 : : // Try sending block announcements via headers
# 5330 : : //
# 5331 : 345498 : {
# 5332 : : // If we have no more than MAX_BLOCKS_TO_ANNOUNCE in our
# 5333 : : // list of block hashes we're relaying, and our peer wants
# 5334 : : // headers announcements, then find the first header
# 5335 : : // not yet known to our peer but would connect, and send.
# 5336 : : // If no header would connect, or if we have too many
# 5337 : : // blocks, or if the peer doesn't want headers, just
# 5338 : : // add all to the inv queue.
# 5339 : 345498 : LOCK(peer->m_block_inv_mutex);
# 5340 : 345498 : std::vector<CBlock> vHeaders;
# 5341 [ + + ]: 345498 : bool fRevertToInv = ((!state.fPreferHeaders &&
# 5342 [ + + ][ - + ]: 345498 : (!state.m_requested_hb_cmpctblocks || peer->m_blocks_for_headers_relay.size() > 1)) ||
# 5343 [ + + ]: 345498 : peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE);
# 5344 : 345498 : const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
# 5345 : 345498 : ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
# 5346 : :
# 5347 [ + + ]: 345498 : if (!fRevertToInv) {
# 5348 : 226404 : bool fFoundStartingHeader = false;
# 5349 : : // Try to find first header that our peer doesn't have, and
# 5350 : : // then send all headers past that one. If we come across any
# 5351 : : // headers that aren't on m_chainman.ActiveChain(), give up.
# 5352 [ + + ]: 226404 : for (const uint256& hash : peer->m_blocks_for_headers_relay) {
# 5353 : 41446 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
# 5354 : 41446 : assert(pindex);
# 5355 [ - + ]: 41446 : if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
# 5356 : : // Bail out if we reorged away from this block
# 5357 : 0 : fRevertToInv = true;
# 5358 : 0 : break;
# 5359 : 0 : }
# 5360 [ + + ][ - + ]: 41446 : if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
# 5361 : : // This means that the list of blocks to announce don't
# 5362 : : // connect to each other.
# 5363 : : // This shouldn't really be possible to hit during
# 5364 : : // regular operation (because reorgs should take us to
# 5365 : : // a chain that has some block not on the prior chain,
# 5366 : : // which should be caught by the prior check), but one
# 5367 : : // way this could happen is by using invalidateblock /
# 5368 : : // reconsiderblock repeatedly on the tip, causing it to
# 5369 : : // be added multiple times to m_blocks_for_headers_relay.
# 5370 : : // Robustly deal with this rare situation by reverting
# 5371 : : // to an inv.
# 5372 : 0 : fRevertToInv = true;
# 5373 : 0 : break;
# 5374 : 0 : }
# 5375 : 41446 : pBestIndex = pindex;
# 5376 [ + + ]: 41446 : if (fFoundStartingHeader) {
# 5377 : : // add this to the headers message
# 5378 : 3117 : vHeaders.push_back(pindex->GetBlockHeader());
# 5379 [ + + ]: 38329 : } else if (PeerHasHeader(&state, pindex)) {
# 5380 : 29581 : continue; // keep looking for the first new block
# 5381 [ - + ][ + + ]: 29581 : } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
# 5382 : : // Peer doesn't have this header but they do have the prior one.
# 5383 : : // Start sending headers.
# 5384 : 8270 : fFoundStartingHeader = true;
# 5385 : 8270 : vHeaders.push_back(pindex->GetBlockHeader());
# 5386 : 8270 : } else {
# 5387 : : // Peer doesn't have this header or the prior one -- nothing will
# 5388 : : // connect, so bail out.
# 5389 : 478 : fRevertToInv = true;
# 5390 : 478 : break;
# 5391 : 478 : }
# 5392 : 41446 : }
# 5393 : 226404 : }
# 5394 [ + + ][ + + ]: 345498 : if (!fRevertToInv && !vHeaders.empty()) {
# 5395 [ + + ][ + + ]: 8270 : if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
# 5396 : : // We only send up to 1 block as header-and-ids, as otherwise
# 5397 : : // probably means we're doing an initial-ish-sync or they're slow
# 5398 [ + - ]: 2042 : LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
# 5399 : 2042 : vHeaders.front().GetHash().ToString(), pto->GetId());
# 5400 : :
# 5401 : 2042 : std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
# 5402 : 2042 : {
# 5403 : 2042 : LOCK(m_most_recent_block_mutex);
# 5404 [ + + ]: 2042 : if (m_most_recent_block_hash == pBestIndex->GetBlockHash()) {
# 5405 : 58 : cached_cmpctblock_msg = msgMaker.Make(NetMsgType::CMPCTBLOCK, *m_most_recent_compact_block);
# 5406 : 58 : }
# 5407 : 2042 : }
# 5408 [ + + ]: 2042 : if (cached_cmpctblock_msg.has_value()) {
# 5409 : 58 : m_connman.PushMessage(pto, std::move(cached_cmpctblock_msg.value()));
# 5410 : 1984 : } else {
# 5411 : 1984 : CBlock block;
# 5412 : 1984 : bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
# 5413 : 1984 : assert(ret);
# 5414 : 0 : CBlockHeaderAndShortTxIDs cmpctblock{block};
# 5415 : 1984 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::CMPCTBLOCK, cmpctblock));
# 5416 : 1984 : }
# 5417 : 0 : state.pindexBestHeaderSent = pBestIndex;
# 5418 [ + - ]: 6228 : } else if (state.fPreferHeaders) {
# 5419 [ + + ]: 6228 : if (vHeaders.size() > 1) {
# 5420 [ + - ]: 1955 : LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
# 5421 : 1955 : vHeaders.size(),
# 5422 : 1955 : vHeaders.front().GetHash().ToString(),
# 5423 : 1955 : vHeaders.back().GetHash().ToString(), pto->GetId());
# 5424 : 4273 : } else {
# 5425 [ + - ]: 4273 : LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
# 5426 : 4273 : vHeaders.front().GetHash().ToString(), pto->GetId());
# 5427 : 4273 : }
# 5428 : 6228 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
# 5429 : 6228 : state.pindexBestHeaderSent = pBestIndex;
# 5430 : 6228 : } else
# 5431 : 0 : fRevertToInv = true;
# 5432 : 8270 : }
# 5433 [ + + ]: 345498 : if (fRevertToInv) {
# 5434 : : // If falling back to using an inv, just try to inv the tip.
# 5435 : : // The last entry in m_blocks_for_headers_relay was our tip at some point
# 5436 : : // in the past.
# 5437 [ + + ]: 119572 : if (!peer->m_blocks_for_headers_relay.empty()) {
# 5438 : 22639 : const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back();
# 5439 : 22639 : const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
# 5440 : 22639 : assert(pindex);
# 5441 : :
# 5442 : : // Warn if we're announcing a block that is not on the main chain.
# 5443 : : // This should be very rare and could be optimized out.
# 5444 : : // Just log for now.
# 5445 [ + + ]: 22639 : if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
# 5446 [ + - ]: 1 : LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
# 5447 : 1 : hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString());
# 5448 : 1 : }
# 5449 : :
# 5450 : : // If the peer's chain has this block, don't inv it back.
# 5451 [ + + ]: 22639 : if (!PeerHasHeader(&state, pindex)) {
# 5452 : 6868 : peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
# 5453 [ + - ]: 6868 : LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
# 5454 : 6868 : pto->GetId(), hashToAnnounce.ToString());
# 5455 : 6868 : }
# 5456 : 22639 : }
# 5457 : 119572 : }
# 5458 : 0 : peer->m_blocks_for_headers_relay.clear();
# 5459 : 345498 : }
# 5460 : :
# 5461 : : //
# 5462 : : // Message: inventory
# 5463 : : //
# 5464 : 0 : std::vector<CInv> vInv;
# 5465 : 345498 : {
# 5466 : 345498 : LOCK(peer->m_block_inv_mutex);
# 5467 : 345498 : vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_MAX));
# 5468 : :
# 5469 : : // Add blocks
# 5470 [ + + ]: 345498 : for (const uint256& hash : peer->m_blocks_for_inv_relay) {
# 5471 : 6887 : vInv.push_back(CInv(MSG_BLOCK, hash));
# 5472 [ - + ]: 6887 : if (vInv.size() == MAX_INV_SZ) {
# 5473 : 0 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
# 5474 : 0 : vInv.clear();
# 5475 : 0 : }
# 5476 : 6887 : }
# 5477 : 345498 : peer->m_blocks_for_inv_relay.clear();
# 5478 : 345498 : }
# 5479 : :
# 5480 [ + + ]: 345498 : if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
# 5481 : 344811 : LOCK(tx_relay->m_tx_inventory_mutex);
# 5482 : : // Check whether periodic sends should happen
# 5483 : 344811 : bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
# 5484 [ + + ]: 344811 : if (tx_relay->m_next_inv_send_time < current_time) {
# 5485 : 6359 : fSendTrickle = true;
# 5486 [ + + ]: 6359 : if (pto->IsInboundConn()) {
# 5487 : 3134 : tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL);
# 5488 : 3225 : } else {
# 5489 : 3225 : tx_relay->m_next_inv_send_time = GetExponentialRand(current_time, OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
# 5490 : 3225 : }
# 5491 : 6359 : }
# 5492 : :
# 5493 : : // Time to send but the peer has requested we not relay transactions.
# 5494 [ + + ]: 344811 : if (fSendTrickle) {
# 5495 : 86957 : LOCK(tx_relay->m_bloom_filter_mutex);
# 5496 [ + + ]: 86957 : if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear();
# 5497 : 86957 : }
# 5498 : :
# 5499 : : // Respond to BIP35 mempool requests
# 5500 [ + + ][ + + ]: 344811 : if (fSendTrickle && tx_relay->m_send_mempool) {
# 5501 : 1 : auto vtxinfo = m_mempool.infoAll();
# 5502 : 1 : tx_relay->m_send_mempool = false;
# 5503 : 1 : const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
# 5504 : :
# 5505 : 1 : LOCK(tx_relay->m_bloom_filter_mutex);
# 5506 : :
# 5507 [ + + ]: 1 : for (const auto& txinfo : vtxinfo) {
# 5508 [ + - ]: 1 : const uint256& hash = peer->m_wtxid_relay ? txinfo.tx->GetWitnessHash() : txinfo.tx->GetHash();
# 5509 [ + - ]: 1 : CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
# 5510 : 1 : tx_relay->m_tx_inventory_to_send.erase(hash);
# 5511 : : // Don't send transactions that peers will not put into their mempool
# 5512 [ - + ]: 1 : if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
# 5513 : 0 : continue;
# 5514 : 0 : }
# 5515 [ + - ]: 1 : if (tx_relay->m_bloom_filter) {
# 5516 [ - + ]: 1 : if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
# 5517 : 1 : }
# 5518 : 1 : tx_relay->m_tx_inventory_known_filter.insert(hash);
# 5519 : : // Responses to MEMPOOL requests bypass the m_recently_announced_invs filter.
# 5520 : 1 : vInv.push_back(inv);
# 5521 [ - + ]: 1 : if (vInv.size() == MAX_INV_SZ) {
# 5522 : 0 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
# 5523 : 0 : vInv.clear();
# 5524 : 0 : }
# 5525 : 1 : }
# 5526 : 1 : tx_relay->m_last_mempool_req = std::chrono::duration_cast<std::chrono::seconds>(current_time);
# 5527 : 1 : }
# 5528 : :
# 5529 : : // Determine transactions to relay
# 5530 [ + + ]: 344811 : if (fSendTrickle) {
# 5531 : : // Produce a vector with all candidates for sending
# 5532 : 86957 : std::vector<std::set<uint256>::iterator> vInvTx;
# 5533 : 86957 : vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
# 5534 [ + + ]: 112964 : for (std::set<uint256>::iterator it = tx_relay->m_tx_inventory_to_send.begin(); it != tx_relay->m_tx_inventory_to_send.end(); it++) {
# 5535 : 26007 : vInvTx.push_back(it);
# 5536 : 26007 : }
# 5537 : 86957 : const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
# 5538 : : // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
# 5539 : : // A heap is used so that not all items need sorting if only a few are being sent.
# 5540 : 86957 : CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, peer->m_wtxid_relay);
# 5541 : 86957 : std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
# 5542 : : // No reason to drain out at many times the network's capacity,
# 5543 : : // especially since we have many peers and some will draw much shorter delays.
# 5544 : 86957 : unsigned int nRelayedTransactions = 0;
# 5545 : 86957 : LOCK(tx_relay->m_bloom_filter_mutex);
# 5546 [ + + ][ + + ]: 111039 : while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
# 5547 : : // Fetch the top element from the heap
# 5548 : 24082 : std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
# 5549 : 24082 : std::set<uint256>::iterator it = vInvTx.back();
# 5550 : 24082 : vInvTx.pop_back();
# 5551 : 24082 : uint256 hash = *it;
# 5552 [ + + ]: 24082 : CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
# 5553 : : // Remove it from the to-be-sent set
# 5554 : 24082 : tx_relay->m_tx_inventory_to_send.erase(it);
# 5555 : : // Check if not in the filter already
# 5556 [ + + ]: 24082 : if (tx_relay->m_tx_inventory_known_filter.contains(hash)) {
# 5557 : 3709 : continue;
# 5558 : 3709 : }
# 5559 : : // Not in the mempool anymore? don't bother sending it.
# 5560 : 20373 : auto txinfo = m_mempool.info(ToGenTxid(inv));
# 5561 [ + + ]: 20373 : if (!txinfo.tx) {
# 5562 : 4232 : continue;
# 5563 : 4232 : }
# 5564 : 16141 : auto txid = txinfo.tx->GetHash();
# 5565 : 16141 : auto wtxid = txinfo.tx->GetWitnessHash();
# 5566 : : // Peer told you to not send transactions at that feerate? Don't bother sending it.
# 5567 [ + + ]: 16141 : if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
# 5568 : 3 : continue;
# 5569 : 3 : }
# 5570 [ + + ][ + + ]: 16138 : if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
# 5571 : : // Send
# 5572 : 16136 : State(pto->GetId())->m_recently_announced_invs.insert(hash);
# 5573 : 16136 : vInv.push_back(inv);
# 5574 : 16136 : nRelayedTransactions++;
# 5575 : 16136 : {
# 5576 : : // Expire old relay messages
# 5577 [ + + ][ + + ]: 16185 : while (!g_relay_expiration.empty() && g_relay_expiration.front().first < current_time)
# 5578 : 49 : {
# 5579 : 49 : mapRelay.erase(g_relay_expiration.front().second);
# 5580 : 49 : g_relay_expiration.pop_front();
# 5581 : 49 : }
# 5582 : :
# 5583 : 16136 : auto ret = mapRelay.emplace(txid, std::move(txinfo.tx));
# 5584 [ + + ]: 16136 : if (ret.second) {
# 5585 : 13565 : g_relay_expiration.emplace_back(current_time + RELAY_TX_CACHE_TIME, ret.first);
# 5586 : 13565 : }
# 5587 : : // Add wtxid-based lookup into mapRelay as well, so that peers can request by wtxid
# 5588 : 16136 : auto ret2 = mapRelay.emplace(wtxid, ret.first->second);
# 5589 [ + + ]: 16136 : if (ret2.second) {
# 5590 : 13001 : g_relay_expiration.emplace_back(current_time + RELAY_TX_CACHE_TIME, ret2.first);
# 5591 : 13001 : }
# 5592 : 16136 : }
# 5593 [ - + ]: 16136 : if (vInv.size() == MAX_INV_SZ) {
# 5594 : 0 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
# 5595 : 0 : vInv.clear();
# 5596 : 0 : }
# 5597 : 16136 : tx_relay->m_tx_inventory_known_filter.insert(hash);
# 5598 [ + + ]: 16136 : if (hash != txid) {
# 5599 : : // Insert txid into m_tx_inventory_known_filter, even for
# 5600 : : // wtxidrelay peers. This prevents re-adding of
# 5601 : : // unconfirmed parents to the recently_announced
# 5602 : : // filter, when a child tx is requested. See
# 5603 : : // ProcessGetData().
# 5604 : 14903 : tx_relay->m_tx_inventory_known_filter.insert(txid);
# 5605 : 14903 : }
# 5606 : 16136 : }
# 5607 : 86957 : }
# 5608 : 344811 : }
# 5609 [ + + ]: 345498 : if (!vInv.empty())
# 5610 : 16778 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
# 5611 : :
# 5612 : : // Detect whether we're stalling
# 5613 [ - + ][ - + ]: 345498 : if (state.m_stalling_since.count() && state.m_stalling_since < current_time - BLOCK_STALLING_TIMEOUT) {
# [ # # ]
# 5614 : : // Stalling only triggers when the block download window cannot move. During normal steady state,
# 5615 : : // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
# 5616 : : // should only happen during initial block download.
# 5617 : 0 : LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
# 5618 : 0 : pto->fDisconnect = true;
# 5619 : 0 : return true;
# 5620 : 0 : }
# 5621 : : // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N)
# 5622 : : // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
# 5623 : : // We compensate for other peers to prevent killing off peers due to our own downstream link
# 5624 : : // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
# 5625 : : // to unreasonably increase our timeout.
# 5626 [ + + ]: 345498 : if (state.vBlocksInFlight.size() > 0) {
# 5627 : 41104 : QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
# 5628 : 41104 : int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1;
# 5629 [ - + ]: 41104 : if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
# 5630 : 0 : LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->GetId());
# 5631 : 0 : pto->fDisconnect = true;
# 5632 : 0 : return true;
# 5633 : 0 : }
# 5634 : 41104 : }
# 5635 : : // Check for headers sync timeouts
# 5636 [ + + ][ + + ]: 345498 : if (state.fSyncStarted && state.m_headers_sync_timeout < std::chrono::microseconds::max()) {
# [ + + ]
# 5637 : : // Detect whether this is a stalling initial-headers-sync peer
# 5638 [ + + ]: 9537 : if (m_chainman.m_best_header->Time() <= GetAdjustedTime() - 24h) {
# 5639 [ + + ][ + - ]: 8476 : if (current_time > state.m_headers_sync_timeout && nSyncStarted == 1 && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)) {
# [ - + ]
# 5640 : : // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
# 5641 : : // and we have others we could be using instead.
# 5642 : : // Note: If all our peers are inbound, then we won't
# 5643 : : // disconnect our sync peer for stalling; we have bigger
# 5644 : : // problems if we can't get any outbound peers.
# 5645 [ # # ]: 0 : if (!pto->HasPermission(NetPermissionFlags::NoBan)) {
# 5646 : 0 : LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
# 5647 : 0 : pto->fDisconnect = true;
# 5648 : 0 : return true;
# 5649 : 0 : } else {
# 5650 : 0 : LogPrintf("Timeout downloading headers from noban peer=%d, not disconnecting\n", pto->GetId());
# 5651 : : // Reset the headers sync state so that we have a
# 5652 : : // chance to try downloading from a different peer.
# 5653 : : // Note: this will also result in at least one more
# 5654 : : // getheaders message to be sent to
# 5655 : : // this peer (eventually).
# 5656 : 0 : state.fSyncStarted = false;
# 5657 : 0 : nSyncStarted--;
# 5658 : 0 : state.m_headers_sync_timeout = 0us;
# 5659 : 0 : }
# 5660 : 0 : }
# 5661 : 8476 : } else {
# 5662 : : // After we've caught up once, reset the timeout so we can't trigger
# 5663 : : // disconnect later.
# 5664 : 1061 : state.m_headers_sync_timeout = std::chrono::microseconds::max();
# 5665 : 1061 : }
# 5666 : 9537 : }
# 5667 : :
# 5668 : : // Check that outbound peers have reasonable chains
# 5669 : : // GetTime() is used by this anti-DoS logic so we can test this using mocktime
# 5670 : 345498 : ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
# 5671 : :
# 5672 : : //
# 5673 : : // Message: getdata (blocks)
# 5674 : : //
# 5675 : 345498 : std::vector<CInv> vGetData;
# 5676 [ + + ][ + + ]: 345498 : if (CanServeBlocks(*peer) && ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) || !m_chainman.ActiveChainstate().IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
# [ + + ][ + + ]
# [ + + ]
# 5677 : 338464 : std::vector<const CBlockIndex*> vToDownload;
# 5678 : 338464 : NodeId staller = -1;
# 5679 : 338464 : FindNextBlocksToDownload(*peer, MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
# 5680 [ + + ]: 338464 : for (const CBlockIndex *pindex : vToDownload) {
# 5681 : 26628 : uint32_t nFetchFlags = GetFetchFlags(*peer);
# 5682 : 26628 : vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
# 5683 : 26628 : BlockRequested(pto->GetId(), *pindex);
# 5684 [ + - ]: 26628 : LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
# 5685 : 26628 : pindex->nHeight, pto->GetId());
# 5686 : 26628 : }
# 5687 [ + + ][ - + ]: 338464 : if (state.nBlocksInFlight == 0 && staller != -1) {
# 5688 [ # # ]: 0 : if (State(staller)->m_stalling_since == 0us) {
# 5689 : 0 : State(staller)->m_stalling_since = current_time;
# 5690 [ # # ]: 0 : LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
# 5691 : 0 : }
# 5692 : 0 : }
# 5693 : 338464 : }
# 5694 : :
# 5695 : : //
# 5696 : : // Message: getdata (transactions)
# 5697 : : //
# 5698 : 345498 : std::vector<std::pair<NodeId, GenTxid>> expired;
# 5699 : 345498 : auto requestable = m_txrequest.GetRequestable(pto->GetId(), current_time, &expired);
# 5700 [ + + ]: 345498 : for (const auto& entry : expired) {
# 5701 [ + - ][ + + ]: 11 : LogPrint(BCLog::NET, "timeout of inflight %s %s from peer=%d\n", entry.second.IsWtxid() ? "wtx" : "tx",
# 5702 : 11 : entry.second.GetHash().ToString(), entry.first);
# 5703 : 11 : }
# 5704 [ + + ]: 345498 : for (const GenTxid& gtxid : requestable) {
# 5705 [ + - ]: 21042 : if (!AlreadyHaveTx(gtxid)) {
# 5706 [ + - ][ + + ]: 21042 : LogPrint(BCLog::NET, "Requesting %s %s peer=%d\n", gtxid.IsWtxid() ? "wtx" : "tx",
# 5707 : 21042 : gtxid.GetHash().ToString(), pto->GetId());
# 5708 [ + + ]: 21042 : vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*peer)), gtxid.GetHash());
# 5709 [ + + ]: 21042 : if (vGetData.size() >= MAX_GETDATA_SZ) {
# 5710 : 10 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
# 5711 : 10 : vGetData.clear();
# 5712 : 10 : }
# 5713 : 21042 : m_txrequest.RequestedTx(pto->GetId(), gtxid.GetHash(), current_time + GETDATA_TX_INTERVAL);
# 5714 : 21042 : } else {
# 5715 : : // We have already seen this transaction, no need to download. This is just a belt-and-suspenders, as
# 5716 : : // this should already be called whenever a transaction becomes AlreadyHaveTx().
# 5717 : 0 : m_txrequest.ForgetTxHash(gtxid.GetHash());
# 5718 : 0 : }
# 5719 : 21042 : }
# 5720 : :
# 5721 : :
# 5722 [ + + ]: 345498 : if (!vGetData.empty())
# 5723 : 32776 : m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
# 5724 : 345498 : } // release cs_main
# 5725 : 0 : MaybeSendFeefilter(*pto, *peer, current_time);
# 5726 : 345498 : return true;
# 5727 : 345498 : }
|