LCOV - code coverage report
Current view: top level - src - net_processing.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 3428 3774 90.8 %
Date: 2020-07-15 11:22:43 Functions: 75 77 97.4 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

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

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

Generated by: LCOV version 1.14