LCOV - code coverage report
Current view: top level - src - net_processing.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 2485 2769 89.7 %
Date: 2020-10-08 11:22:10 Functions: 73 75 97.3 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 0 0 -

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

Generated by: LCOV version 1.14