LCOV - code coverage report
Current view: top level - src - net_processing.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 672 3784 17.8 %
Date: 2020-06-05 16:23:38 Functions: 28 77 36.4 %
Legend: Lines: hit, modifiedhit, not modified not hit, modifiednot hit, not modified

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

Generated by: LCOV version 1.14