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