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

Generated by: LCOV version 1.14