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