Bitcoin Core  27.99.0
P2P Digital Currency
net_processing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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/amount.h>
14 #include <consensus/validation.h>
15 #include <deploymentstatus.h>
16 #include <hash.h>
17 #include <headerssync.h>
18 #include <index/blockfilterindex.h>
19 #include <kernel/chain.h>
20 #include <kernel/mempool_entry.h>
21 #include <logging.h>
22 #include <merkleblock.h>
23 #include <netbase.h>
24 #include <netmessagemaker.h>
25 #include <node/blockstorage.h>
26 #include <node/txreconciliation.h>
27 #include <policy/fees.h>
28 #include <policy/policy.h>
29 #include <policy/settings.h>
30 #include <primitives/block.h>
31 #include <primitives/transaction.h>
32 #include <random.h>
33 #include <reverse_iterator.h>
34 #include <scheduler.h>
35 #include <streams.h>
36 #include <sync.h>
37 #include <timedata.h>
38 #include <tinyformat.h>
39 #include <txmempool.h>
40 #include <txorphanage.h>
41 #include <txrequest.h>
42 #include <util/check.h>
43 #include <util/strencodings.h>
44 #include <util/time.h>
45 #include <util/trace.h>
46 #include <validation.h>
47 
48 #include <algorithm>
49 #include <atomic>
50 #include <future>
51 #include <memory>
52 #include <optional>
53 #include <typeinfo>
54 #include <utility>
55 
58 static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min;
59 static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;
61 static constexpr auto HEADERS_RESPONSE_TIME{2min};
65 static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
67 static constexpr auto CHAIN_SYNC_TIMEOUT{20min};
69 static constexpr auto STALE_CHECK_INTERVAL{10min};
71 static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};
73 static constexpr auto MINIMUM_CONNECT_TIME{30s};
75 static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
78 static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
81 static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
83 static constexpr auto PING_INTERVAL{2min};
85 static const unsigned int MAX_LOCATOR_SZ = 101;
87 static const unsigned int MAX_INV_SZ = 50000;
90 static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT = 100;
95 static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 5000;
97 static constexpr auto TXID_RELAY_DELAY{2s};
99 static constexpr auto NONPREF_PEER_TX_DELAY{2s};
101 static constexpr auto OVERLOADED_PEER_TX_DELAY{2s};
103 static constexpr auto GETDATA_TX_INTERVAL{60s};
105 static const unsigned int MAX_GETDATA_SZ = 1000;
107 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
110 static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT{2s};
112 static constexpr auto BLOCK_STALLING_TIMEOUT_MAX{64s};
115 static const unsigned int MAX_HEADERS_RESULTS = 2000;
118 static const int MAX_CMPCTBLOCK_DEPTH = 5;
120 static const int MAX_BLOCKTXN_DEPTH = 10;
125 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
127 static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1;
129 static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5;
131 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
133 static const int MAX_NUM_UNCONNECTING_HEADERS_MSGS = 10;
135 static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
137 static const unsigned int NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS = 144;
139 static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h};
141 static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s};
143 static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h};
146 static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s};
150 static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s};
153 static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7;
157 static constexpr unsigned int INVENTORY_BROADCAST_MAX = 1000;
158 static_assert(INVENTORY_BROADCAST_MAX >= INVENTORY_BROADCAST_TARGET, "INVENTORY_BROADCAST_MAX too low");
159 static_assert(INVENTORY_BROADCAST_MAX <= MAX_PEER_TX_ANNOUNCEMENTS, "INVENTORY_BROADCAST_MAX too high");
161 static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min};
163 static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min};
165 static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
167 static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;
169 static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
171 static constexpr size_t MAX_ADDR_TO_SEND{1000};
174 static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
180 static constexpr uint64_t CMPCTBLOCKS_VERSION{2};
181 
182 // Internal stuff
183 namespace {
185 struct QueuedBlock {
187  const CBlockIndex* pindex;
189  std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
190 };
191 
204 struct Peer {
206  const NodeId m_id{0};
207 
221  const ServiceFlags m_our_services;
223  std::atomic<ServiceFlags> m_their_services{NODE_NONE};
224 
226  Mutex m_misbehavior_mutex;
228  int m_misbehavior_score GUARDED_BY(m_misbehavior_mutex){0};
230  bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false};
231 
233  Mutex m_block_inv_mutex;
237  std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex);
241  std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex);
246  uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {};
247 
249  std::atomic<int> m_starting_height{-1};
250 
252  std::atomic<uint64_t> m_ping_nonce_sent{0};
254  std::atomic<std::chrono::microseconds> m_ping_start{0us};
256  std::atomic<bool> m_ping_queued{false};
257 
259  std::atomic<bool> m_wtxid_relay{false};
266  std::chrono::microseconds m_next_send_feefilter GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0};
267 
268  struct TxRelay {
269  mutable RecursiveMutex m_bloom_filter_mutex;
271  bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false};
273  std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr};
274 
275  mutable RecursiveMutex m_tx_inventory_mutex;
279  CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
284  std::set<uint256> m_tx_inventory_to_send GUARDED_BY(m_tx_inventory_mutex);
288  bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};
291  std::chrono::microseconds m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){0};
294  uint64_t m_last_inv_sequence GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1};
295 
297  std::atomic<CAmount> m_fee_filter_received{0};
298  };
299 
300  /* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */
301  TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
302  {
303  LOCK(m_tx_relay_mutex);
304  Assume(!m_tx_relay);
305  m_tx_relay = std::make_unique<Peer::TxRelay>();
306  return m_tx_relay.get();
307  };
308 
309  TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)
310  {
311  return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get());
312  };
313 
315  std::vector<CAddress> m_addrs_to_send GUARDED_BY(NetEventsInterface::g_msgproc_mutex);
325  std::unique_ptr<CRollingBloomFilter> m_addr_known GUARDED_BY(NetEventsInterface::g_msgproc_mutex);
340  std::atomic_bool m_addr_relay_enabled{false};
342  bool m_getaddr_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
344  mutable Mutex m_addr_send_times_mutex;
346  std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
348  std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
351  std::atomic_bool m_wants_addrv2{false};
353  bool m_getaddr_recvd GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
356  double m_addr_token_bucket GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1.0};
358  std::chrono::microseconds m_addr_token_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){GetTime<std::chrono::microseconds>()};
360  std::atomic<uint64_t> m_addr_rate_limited{0};
362  std::atomic<uint64_t> m_addr_processed{0};
363 
365  bool m_inv_triggered_getheaders_before_sync GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
366 
368  Mutex m_getdata_requests_mutex;
370  std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);
371 
374 
376  Mutex m_headers_sync_mutex;
379  std::unique_ptr<HeadersSyncState> m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex) GUARDED_BY(m_headers_sync_mutex) {};
380 
382  std::atomic<bool> m_sent_sendheaders{false};
383 
385  int m_num_unconnecting_headers_msgs GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0};
386 
388  std::chrono::microseconds m_headers_sync_timeout GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0us};
389 
391  bool m_prefers_headers GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
392 
393  explicit Peer(NodeId id, ServiceFlags our_services)
394  : m_id{id}
395  , m_our_services{our_services}
396  {}
397 
398 private:
399  mutable Mutex m_tx_relay_mutex;
400 
402  std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex);
403 };
404 
405 using PeerRef = std::shared_ptr<Peer>;
406 
413 struct CNodeState {
415  const CBlockIndex* pindexBestKnownBlock{nullptr};
417  uint256 hashLastUnknownBlock{};
419  const CBlockIndex* pindexLastCommonBlock{nullptr};
421  const CBlockIndex* pindexBestHeaderSent{nullptr};
423  bool fSyncStarted{false};
425  std::chrono::microseconds m_stalling_since{0us};
426  std::list<QueuedBlock> vBlocksInFlight;
428  std::chrono::microseconds m_downloading_since{0us};
430  bool fPreferredDownload{false};
432  bool m_requested_hb_cmpctblocks{false};
434  bool m_provides_cmpctblocks{false};
435 
460  struct ChainSyncTimeoutState {
462  std::chrono::seconds m_timeout{0s};
464  const CBlockIndex* m_work_header{nullptr};
466  bool m_sent_getheaders{false};
468  bool m_protect{false};
469  };
470 
471  ChainSyncTimeoutState m_chain_sync;
472 
474  int64_t m_last_block_announcement{0};
475 
477  const bool m_is_inbound;
478 
479  CNodeState(bool is_inbound) : m_is_inbound(is_inbound) {}
480 };
481 
482 class PeerManagerImpl final : public PeerManager
483 {
484 public:
485  PeerManagerImpl(CConnman& connman, AddrMan& addrman,
486  BanMan* banman, ChainstateManager& chainman,
487  CTxMemPool& pool, Options opts);
488 
490  void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override
491  EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex);
492  void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override
493  EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex);
494  void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
495  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
496  void BlockChecked(const CBlock& block, const BlockValidationState& state) override
497  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
498  void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override
499  EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);
500 
502  void InitializeNode(CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
503  void FinalizeNode(const CNode& node) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex);
504  bool HasAllDesirableServiceFlags(ServiceFlags services) const override;
505  bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override
506  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
507  bool SendMessages(CNode* pto) override
508  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, g_msgproc_mutex);
509 
511  void StartScheduledTasks(CScheduler& scheduler) override;
512  void CheckForStaleTipAndEvictPeers() override;
513  std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) override
514  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
515  bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
516  bool IgnoresIncomingTxs() override { return m_opts.ignore_incoming_txs; }
517  void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
518  void RelayTransaction(const uint256& txid, const uint256& wtxid) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
519  void SetBestBlock(int height, std::chrono::seconds time) override
520  {
521  m_best_height = height;
522  m_best_block_time = time;
523  };
524  void UnitTestMisbehaving(NodeId peer_id, int howmuch) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), howmuch, ""); };
525  void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv,
526  const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override
527  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
528  void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override;
529  ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const override;
530 
531 private:
533  void ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_msgproc_mutex);
534 
536  void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
537 
539  void ReattemptInitialBroadcast(CScheduler& scheduler) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
540 
543  PeerRef GetPeerRef(NodeId id) const EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
544 
547  PeerRef RemovePeer(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
548 
553  void Misbehaving(Peer& peer, int howmuch, const std::string& message);
554 
565  bool MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
566  bool via_compact_block, const std::string& message = "")
567  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
568 
574  bool MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state)
575  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
576 
583  bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer);
584 
590  void ProcessInvalidTx(NodeId nodeid, const CTransactionRef& tx, const TxValidationState& result,
591  bool maybe_add_extra_compact_tx)
592  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main);
593 
596  void ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions)
597  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main);
598 
610  bool ProcessOrphanTx(Peer& peer)
611  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex);
612 
620  void ProcessHeadersMessage(CNode& pfrom, Peer& peer,
621  std::vector<CBlockHeader>&& headers,
622  bool via_compact_block)
623  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
626  bool CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer);
628  arith_uint256 GetAntiDoSWorkThreshold();
632  void HandleFewUnconnectingHeaders(CNode& pfrom, Peer& peer, const std::vector<CBlockHeader>& headers) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
634  bool CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const;
653  bool IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom,
654  std::vector<CBlockHeader>& headers)
655  EXCLUSIVE_LOCKS_REQUIRED(peer.m_headers_sync_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
667  bool TryLowWorkHeadersSync(Peer& peer, CNode& pfrom,
668  const CBlockIndex* chain_start_header,
669  std::vector<CBlockHeader>& headers)
670  EXCLUSIVE_LOCKS_REQUIRED(!peer.m_headers_sync_mutex, !m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
671 
674  bool IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
675 
680  bool MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
682  void HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header);
684  void UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers)
685  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
686 
687  void SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req);
688 
692  void AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
694 
696  void PushMessage(CNode& node, CSerializedNetMsg&& msg) const { m_connman.PushMessage(&node, std::move(msg)); }
697  template <typename... Args>
698  void MakeAndPushMessage(CNode& node, std::string msg_type, Args&&... args) const
699  {
700  m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...));
701  }
702 
704  void PushNodeVersion(CNode& pnode, const Peer& peer);
705 
710  void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now);
711 
713  void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
714 
716  void MaybeSendSendHeaders(CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
717 
725  void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex);
726 
728  void MaybeSendFeefilter(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
729 
731 
733 
734  const CChainParams& m_chainparams;
735  CConnman& m_connman;
736  AddrMan& m_addrman;
738  BanMan* const m_banman;
739  ChainstateManager& m_chainman;
740  CTxMemPool& m_mempool;
741  TxRequestTracker m_txrequest GUARDED_BY(::cs_main);
742  std::unique_ptr<TxReconciliationTracker> m_txreconciliation;
743 
745  std::atomic<int> m_best_height{-1};
747  std::atomic<std::chrono::seconds> m_best_block_time{0s};
748 
750  std::chrono::seconds m_stale_tip_check_time GUARDED_BY(cs_main){0s};
751 
752  const Options m_opts;
753 
754  bool RejectIncomingTxs(const CNode& peer) const;
755 
758  bool m_initial_sync_finished GUARDED_BY(cs_main){false};
759 
762  mutable Mutex m_peer_mutex;
769  std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex);
770 
772  std::map<NodeId, CNodeState> m_node_states GUARDED_BY(cs_main);
773 
775  const CNodeState* State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
777  CNodeState* State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
778 
779  uint32_t GetFetchFlags(const Peer& peer) const;
780 
781  std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us};
782 
784  int nSyncStarted GUARDED_BY(cs_main) = 0;
785 
787  uint256 m_last_block_inv_triggering_headers_sync GUARDED_BY(g_msgproc_mutex){};
788 
795  std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main);
796 
798  std::atomic<int> m_wtxid_relay_peers{0};
799 
801  int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
802 
804  int m_num_preferred_download_peers GUARDED_BY(cs_main){0};
805 
807  std::atomic<std::chrono::seconds> m_block_stalling_timeout{BLOCK_STALLING_TIMEOUT_DEFAULT};
808 
809  bool AlreadyHaveTx(const GenTxid& gtxid)
810  EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_recent_confirmed_transactions_mutex);
811 
846  CRollingBloomFilter m_recent_rejects GUARDED_BY(::cs_main){120'000, 0.000'001};
847  uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main);
848 
849  /*
850  * Filter for transactions that have been recently confirmed.
851  * We use this to avoid requesting transactions that have already been
852  * confirnmed.
853  *
854  * Blocks don't typically have more than 4000 transactions, so this should
855  * be at least six blocks (~1 hr) worth of transactions that we can store,
856  * inserting both a txid and wtxid for every observed transaction.
857  * If the number of transactions appearing in a block goes up, or if we are
858  * seeing getdata requests more than an hour after initial announcement, we
859  * can increase this number.
860  * The false positive rate of 1/1M should come out to less than 1
861  * transaction per day that would be inadvertently ignored (which is the
862  * same probability that we have in the reject filter).
863  */
864  Mutex m_recent_confirmed_transactions_mutex;
865  CRollingBloomFilter m_recent_confirmed_transactions GUARDED_BY(m_recent_confirmed_transactions_mutex){48'000, 0.000'001};
866 
873  std::chrono::microseconds NextInvToInbounds(std::chrono::microseconds now,
874  std::chrono::seconds average_interval);
875 
876 
877  // All of the following cache a recent block, and are protected by m_most_recent_block_mutex
878  Mutex m_most_recent_block_mutex;
879  std::shared_ptr<const CBlock> m_most_recent_block GUARDED_BY(m_most_recent_block_mutex);
880  std::shared_ptr<const CBlockHeaderAndShortTxIDs> m_most_recent_compact_block GUARDED_BY(m_most_recent_block_mutex);
881  uint256 m_most_recent_block_hash GUARDED_BY(m_most_recent_block_mutex);
882  std::unique_ptr<const std::map<uint256, CTransactionRef>> m_most_recent_block_txs GUARDED_BY(m_most_recent_block_mutex);
883 
884  // Data about the low-work headers synchronization, aggregated from all peers' HeadersSyncStates.
886  Mutex m_headers_presync_mutex;
894  using HeadersPresyncStats = std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>;
896  std::map<NodeId, HeadersPresyncStats> m_headers_presync_stats GUARDED_BY(m_headers_presync_mutex) {};
898  NodeId m_headers_presync_bestpeer GUARDED_BY(m_headers_presync_mutex) {-1};
900  std::atomic_bool m_headers_presync_should_signal{false};
901 
903  int m_highest_fast_announce GUARDED_BY(::cs_main){0};
904 
906  bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
907 
909  bool IsBlockRequestedFromOutbound(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
910 
918  void RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
919 
920  /* Mark a block as in flight
921  * Returns false, still setting pit, if the block was already in flight from the same peer
922  * pit will only be valid as long as the same cs_main lock is being held
923  */
924  bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
925 
926  bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
927 
931  void FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
932 
934  void TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex* from_tip, const CBlockIndex* target_block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
935 
963  void FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain=nullptr, NodeId* nodeStaller=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
964 
965  /* Multimap used to preserve insertion order */
966  typedef std::multimap<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator>> BlockDownloadMap;
967  BlockDownloadMap mapBlocksInFlight GUARDED_BY(cs_main);
968 
970  std::atomic<std::chrono::seconds> m_last_tip_update{0s};
971 
973  CTransactionRef FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid)
975 
976  void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
977  EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex, NetEventsInterface::g_msgproc_mutex)
979 
981  void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked);
982 
984  void ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions)
985  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex, !m_most_recent_block_mutex);
986 
993  void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
994 
996  std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
997 
999  int m_peers_downloading_from GUARDED_BY(cs_main) = 0;
1000 
1002  TxOrphanage m_orphanage;
1003 
1004  void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1005 
1009  std::vector<CTransactionRef> vExtraTxnForCompact GUARDED_BY(g_msgproc_mutex);
1011  size_t vExtraTxnForCompactIt GUARDED_BY(g_msgproc_mutex) = 0;
1012 
1014  void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1016  void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1017  bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1018 
1023  int64_t ApproximateBestBlockDepth() const;
1024 
1031  bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1032  bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1033  void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
1034  EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);
1035 
1051  bool PrepareBlockFilterRequest(CNode& node, Peer& peer,
1052  BlockFilterType filter_type, uint32_t start_height,
1053  const uint256& stop_hash, uint32_t max_height_diff,
1054  const CBlockIndex*& stop_index,
1055  BlockFilterIndex*& filter_index);
1056 
1066  void ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv);
1067 
1077  void ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv);
1078 
1088  void ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv);
1089 
1096  bool SetupAddressRelay(const CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1097 
1098  void AddAddressKnown(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1099  void PushAddress(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1100 };
1101 
1102 const CNodeState* PeerManagerImpl::State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1103 {
1104  std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
1105  if (it == m_node_states.end())
1106  return nullptr;
1107  return &it->second;
1108 }
1109 
1110 CNodeState* PeerManagerImpl::State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1111 {
1112  return const_cast<CNodeState*>(std::as_const(*this).State(pnode));
1113 }
1114 
1120 static bool IsAddrCompatible(const Peer& peer, const CAddress& addr)
1121 {
1122  return peer.m_wants_addrv2 || addr.IsAddrV1Compatible();
1123 }
1124 
1125 void PeerManagerImpl::AddAddressKnown(Peer& peer, const CAddress& addr)
1126 {
1127  assert(peer.m_addr_known);
1128  peer.m_addr_known->insert(addr.GetKey());
1129 }
1130 
1131 void PeerManagerImpl::PushAddress(Peer& peer, const CAddress& addr)
1132 {
1133  // Known checking here is only to save space from duplicates.
1134  // Before sending, we'll filter it again for known addresses that were
1135  // added after addresses were pushed.
1136  assert(peer.m_addr_known);
1137  if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) {
1138  if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) {
1139  peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] = addr;
1140  } else {
1141  peer.m_addrs_to_send.push_back(addr);
1142  }
1143  }
1144 }
1145 
1146 static void AddKnownTx(Peer& peer, const uint256& hash)
1147 {
1148  auto tx_relay = peer.GetTxRelay();
1149  if (!tx_relay) return;
1150 
1151  LOCK(tx_relay->m_tx_inventory_mutex);
1152  tx_relay->m_tx_inventory_known_filter.insert(hash);
1153 }
1154 
1156 static bool CanServeBlocks(const Peer& peer)
1157 {
1158  return peer.m_their_services & (NODE_NETWORK|NODE_NETWORK_LIMITED);
1159 }
1160 
1163 static bool IsLimitedPeer(const Peer& peer)
1164 {
1165  return (!(peer.m_their_services & NODE_NETWORK) &&
1166  (peer.m_their_services & NODE_NETWORK_LIMITED));
1167 }
1168 
1170 static bool CanServeWitnesses(const Peer& peer)
1171 {
1172  return peer.m_their_services & NODE_WITNESS;
1173 }
1174 
1175 std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
1176  std::chrono::seconds average_interval)
1177 {
1178  if (m_next_inv_to_inbounds.load() < now) {
1179  // If this function were called from multiple threads simultaneously
1180  // it would possible that both update the next send variable, and return a different result to their caller.
1181  // This is not possible in practice as only the net processing thread invokes this function.
1182  m_next_inv_to_inbounds = GetExponentialRand(now, average_interval);
1183  }
1184  return m_next_inv_to_inbounds;
1185 }
1186 
1187 bool PeerManagerImpl::IsBlockRequested(const uint256& hash)
1188 {
1189  return mapBlocksInFlight.count(hash);
1190 }
1191 
1192 bool PeerManagerImpl::IsBlockRequestedFromOutbound(const uint256& hash)
1193 {
1194  for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) {
1195  auto [nodeid, block_it] = range.first->second;
1196  CNodeState& nodestate = *Assert(State(nodeid));
1197  if (!nodestate.m_is_inbound) return true;
1198  }
1199 
1200  return false;
1201 }
1202 
1203 void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer)
1204 {
1205  auto range = mapBlocksInFlight.equal_range(hash);
1206  if (range.first == range.second) {
1207  // Block was not requested from any peer
1208  return;
1209  }
1210 
1211  // We should not have requested too many of this block
1212  Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK);
1213 
1214  while (range.first != range.second) {
1215  auto [node_id, list_it] = range.first->second;
1216 
1217  if (from_peer && *from_peer != node_id) {
1218  range.first++;
1219  continue;
1220  }
1221 
1222  CNodeState& state = *Assert(State(node_id));
1223 
1224  if (state.vBlocksInFlight.begin() == list_it) {
1225  // First block on the queue was received, update the start download time for the next one
1226  state.m_downloading_since = std::max(state.m_downloading_since, GetTime<std::chrono::microseconds>());
1227  }
1228  state.vBlocksInFlight.erase(list_it);
1229 
1230  if (state.vBlocksInFlight.empty()) {
1231  // Last validated block on the queue for this peer was received.
1232  m_peers_downloading_from--;
1233  }
1234  state.m_stalling_since = 0us;
1235 
1236  range.first = mapBlocksInFlight.erase(range.first);
1237  }
1238 }
1239 
1240 bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit)
1241 {
1242  const uint256& hash{block.GetBlockHash()};
1243 
1244  CNodeState *state = State(nodeid);
1245  assert(state != nullptr);
1246 
1247  Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK);
1248 
1249  // Short-circuit most stuff in case it is from the same node
1250  for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) {
1251  if (range.first->second.first == nodeid) {
1252  if (pit) {
1253  *pit = &range.first->second.second;
1254  }
1255  return false;
1256  }
1257  }
1258 
1259  // Make sure it's not being fetched already from same peer.
1260  RemoveBlockRequest(hash, nodeid);
1261 
1262  std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
1263  {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool) : nullptr)});
1264  if (state->vBlocksInFlight.size() == 1) {
1265  // We're starting a block download (batch) from this peer.
1266  state->m_downloading_since = GetTime<std::chrono::microseconds>();
1267  m_peers_downloading_from++;
1268  }
1269  auto itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it)));
1270  if (pit) {
1271  *pit = &itInFlight->second.second;
1272  }
1273  return true;
1274 }
1275 
1276 void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid)
1277 {
1279 
1280  // When in -blocksonly mode, never request high-bandwidth mode from peers. Our
1281  // mempool will not contain the transactions necessary to reconstruct the
1282  // compact block.
1283  if (m_opts.ignore_incoming_txs) return;
1284 
1285  CNodeState* nodestate = State(nodeid);
1286  if (!nodestate || !nodestate->m_provides_cmpctblocks) {
1287  // Don't request compact blocks if the peer has not signalled support
1288  return;
1289  }
1290 
1291  int num_outbound_hb_peers = 0;
1292  for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
1293  if (*it == nodeid) {
1294  lNodesAnnouncingHeaderAndIDs.erase(it);
1295  lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
1296  return;
1297  }
1298  CNodeState *state = State(*it);
1299  if (state != nullptr && !state->m_is_inbound) ++num_outbound_hb_peers;
1300  }
1301  if (nodestate->m_is_inbound) {
1302  // If we're adding an inbound HB peer, make sure we're not removing
1303  // our last outbound HB peer in the process.
1304  if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 1) {
1305  CNodeState *remove_node = State(lNodesAnnouncingHeaderAndIDs.front());
1306  if (remove_node != nullptr && !remove_node->m_is_inbound) {
1307  // Put the HB outbound peer in the second slot, so that it
1308  // doesn't get removed.
1309  std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
1310  }
1311  }
1312  }
1313  m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1315  if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
1316  // As per BIP152, we only get 3 of our peers to announce
1317  // blocks using compact encodings.
1318  m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this](CNode* pnodeStop){
1319  MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION);
1320  // save BIP152 bandwidth state: we select peer to be low-bandwidth
1321  pnodeStop->m_bip152_highbandwidth_to = false;
1322  return true;
1323  });
1324  lNodesAnnouncingHeaderAndIDs.pop_front();
1325  }
1326  MakeAndPushMessage(*pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/true, /*version=*/CMPCTBLOCKS_VERSION);
1327  // save BIP152 bandwidth state: we select peer to be high-bandwidth
1328  pfrom->m_bip152_highbandwidth_to = true;
1329  lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
1330  return true;
1331  });
1332 }
1333 
1334 bool PeerManagerImpl::TipMayBeStale()
1335 {
1337  const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
1338  if (m_last_tip_update.load() == 0s) {
1339  m_last_tip_update = GetTime<std::chrono::seconds>();
1340  }
1341  return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty();
1342 }
1343 
1344 int64_t PeerManagerImpl::ApproximateBestBlockDepth() const
1345 {
1346  return (GetTime<std::chrono::seconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing;
1347 }
1348 
1349 bool PeerManagerImpl::CanDirectFetch()
1350 {
1351  return m_chainman.ActiveChain().Tip()->Time() > NodeClock::now() - m_chainparams.GetConsensus().PowTargetSpacing() * 20;
1352 }
1353 
1354 static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1355 {
1356  if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
1357  return true;
1358  if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
1359  return true;
1360  return false;
1361 }
1362 
1363 void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) {
1364  CNodeState *state = State(nodeid);
1365  assert(state != nullptr);
1366 
1367  if (!state->hashLastUnknownBlock.IsNull()) {
1368  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
1369  if (pindex && pindex->nChainWork > 0) {
1370  if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1371  state->pindexBestKnownBlock = pindex;
1372  }
1373  state->hashLastUnknownBlock.SetNull();
1374  }
1375  }
1376 }
1377 
1378 void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
1379  CNodeState *state = State(nodeid);
1380  assert(state != nullptr);
1381 
1382  ProcessBlockAvailability(nodeid);
1383 
1384  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
1385  if (pindex && pindex->nChainWork > 0) {
1386  // An actually better block was announced.
1387  if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1388  state->pindexBestKnownBlock = pindex;
1389  }
1390  } else {
1391  // An unknown block was announced; just assume that the latest one is the best one.
1392  state->hashLastUnknownBlock = hash;
1393  }
1394 }
1395 
1396 // Logic for calculating which blocks to download from a given peer, given our current tip.
1397 void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller)
1398 {
1399  if (count == 0)
1400  return;
1401 
1402  vBlocks.reserve(vBlocks.size() + count);
1403  CNodeState *state = State(peer.m_id);
1404  assert(state != nullptr);
1405 
1406  // Make sure pindexBestKnownBlock is up to date, we'll need it.
1407  ProcessBlockAvailability(peer.m_id);
1408 
1409  if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) {
1410  // This peer has nothing interesting.
1411  return;
1412  }
1413 
1414  if (state->pindexLastCommonBlock == nullptr) {
1415  // Bootstrap quickly by guessing a parent of our best tip is the forking point.
1416  // Guessing wrong in either direction is not a problem.
1417  state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())];
1418  }
1419 
1420  // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
1421  // of its current tip anymore. Go back enough to fix that.
1422  state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
1423  if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
1424  return;
1425 
1426  const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
1427  // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
1428  // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
1429  // download that next block if the window were 1 larger.
1430  int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1431 
1432  FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);
1433 }
1434 
1435 void PeerManagerImpl::TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex *from_tip, const CBlockIndex* target_block)
1436 {
1437  Assert(from_tip);
1438  Assert(target_block);
1439 
1440  if (vBlocks.size() >= count) {
1441  return;
1442  }
1443 
1444  vBlocks.reserve(count);
1445  CNodeState *state = Assert(State(peer.m_id));
1446 
1447  if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->GetAncestor(target_block->nHeight) != target_block) {
1448  // This peer can't provide us the complete series of blocks leading up to the
1449  // assumeutxo snapshot base.
1450  //
1451  // Presumably this peer's chain has less work than our ActiveChain()'s tip, or else we
1452  // will eventually crash when we try to reorg to it. Let other logic
1453  // deal with whether we disconnect this peer.
1454  //
1455  // TODO at some point in the future, we might choose to request what blocks
1456  // this peer does have from the historical chain, despite it not having a
1457  // complete history beneath the snapshot base.
1458  return;
1459  }
1460 
1461  FindNextBlocks(vBlocks, peer, state, from_tip, count, std::min<int>(from_tip->nHeight + BLOCK_DOWNLOAD_WINDOW, target_block->nHeight));
1462 }
1463 
1464 void PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain, NodeId* nodeStaller)
1465 {
1466  std::vector<const CBlockIndex*> vToFetch;
1467  int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1468  bool is_limited_peer = IsLimitedPeer(peer);
1469  NodeId waitingfor = -1;
1470  while (pindexWalk->nHeight < nMaxHeight) {
1471  // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
1472  // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
1473  // as iterating over ~100 CBlockIndex* entries anyway.
1474  int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
1475  vToFetch.resize(nToFetch);
1476  pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
1477  vToFetch[nToFetch - 1] = pindexWalk;
1478  for (unsigned int i = nToFetch - 1; i > 0; i--) {
1479  vToFetch[i - 1] = vToFetch[i]->pprev;
1480  }
1481 
1482  // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
1483  // are not yet downloaded and not in flight to vBlocks. In the meantime, update
1484  // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
1485  // already part of our chain (and therefore don't need it even if pruned).
1486  for (const CBlockIndex* pindex : vToFetch) {
1487  if (!pindex->IsValid(BLOCK_VALID_TREE)) {
1488  // We consider the chain that this peer is on invalid.
1489  return;
1490  }
1491 
1492  if (!CanServeWitnesses(peer) && DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {
1493  // We wouldn't download this block or its descendants from this peer.
1494  return;
1495  }
1496 
1497  if (pindex->nStatus & BLOCK_HAVE_DATA || (activeChain && activeChain->Contains(pindex))) {
1498  if (activeChain && pindex->HaveNumChainTxs()) {
1499  state->pindexLastCommonBlock = pindex;
1500  }
1501  continue;
1502  }
1503 
1504  // Is block in-flight?
1505  if (IsBlockRequested(pindex->GetBlockHash())) {
1506  if (waitingfor == -1) {
1507  // This is the first already-in-flight block.
1508  waitingfor = mapBlocksInFlight.lower_bound(pindex->GetBlockHash())->second.first;
1509  }
1510  continue;
1511  }
1512 
1513  // The block is not already downloaded, and not yet in flight.
1514  if (pindex->nHeight > nWindowEnd) {
1515  // We reached the end of the window.
1516  if (vBlocks.size() == 0 && waitingfor != peer.m_id) {
1517  // We aren't able to fetch anything, but we would be if the download window was one larger.
1518  if (nodeStaller) *nodeStaller = waitingfor;
1519  }
1520  return;
1521  }
1522 
1523  // Don't request blocks that go further than what limited peers can provide
1524  if (is_limited_peer && (state->pindexBestKnownBlock->nHeight - pindex->nHeight >= static_cast<int>(NODE_NETWORK_LIMITED_MIN_BLOCKS) - 2 /* two blocks buffer for possible races */)) {
1525  continue;
1526  }
1527 
1528  vBlocks.push_back(pindex);
1529  if (vBlocks.size() == count) {
1530  return;
1531  }
1532  }
1533  }
1534 }
1535 
1536 } // namespace
1537 
1538 void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer)
1539 {
1540  uint64_t my_services{peer.m_our_services};
1541  const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())};
1542  uint64_t nonce = pnode.GetLocalNonce();
1543  const int nNodeStartingHeight{m_best_height};
1544  NodeId nodeid = pnode.GetId();
1545  CAddress addr = pnode.addr;
1546 
1547  CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService();
1548  uint64_t your_services{addr.nServices};
1549 
1550  const bool tx_relay{!RejectIncomingTxs(pnode)};
1551  MakeAndPushMessage(pnode, NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime,
1552  your_services, CNetAddr::V1(addr_you), // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime)
1553  my_services, CNetAddr::V1(CService{}), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime)
1554  nonce, strSubVersion, nNodeStartingHeight, tx_relay);
1555 
1556  if (fLogIPs) {
1557  LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, them=%s, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addr_you.ToStringAddrPort(), tx_relay, nodeid);
1558  } else {
1559  LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid);
1560  }
1561 }
1562 
1563 void PeerManagerImpl::AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
1564 {
1565  AssertLockHeld(::cs_main); // For m_txrequest
1566  NodeId nodeid = node.GetId();
1567  if (!node.HasPermission(NetPermissionFlags::Relay) && m_txrequest.Count(nodeid) >= MAX_PEER_TX_ANNOUNCEMENTS) {
1568  // Too many queued announcements from this peer
1569  return;
1570  }
1571  const CNodeState* state = State(nodeid);
1572 
1573  // Decide the TxRequestTracker parameters for this announcement:
1574  // - "preferred": if fPreferredDownload is set (= outbound, or NetPermissionFlags::NoBan permission)
1575  // - "reqtime": current time plus delays for:
1576  // - NONPREF_PEER_TX_DELAY for announcements from non-preferred connections
1577  // - TXID_RELAY_DELAY for txid announcements while wtxid peers are available
1578  // - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least
1579  // MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay).
1580  auto delay{0us};
1581  const bool preferred = state->fPreferredDownload;
1582  if (!preferred) delay += NONPREF_PEER_TX_DELAY;
1583  if (!gtxid.IsWtxid() && m_wtxid_relay_peers > 0) delay += TXID_RELAY_DELAY;
1584  const bool overloaded = !node.HasPermission(NetPermissionFlags::Relay) &&
1585  m_txrequest.CountInFlight(nodeid) >= MAX_PEER_TX_REQUEST_IN_FLIGHT;
1586  if (overloaded) delay += OVERLOADED_PEER_TX_DELAY;
1587  m_txrequest.ReceivedInv(nodeid, gtxid, preferred, current_time + delay);
1588 }
1589 
1590 void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
1591 {
1592  LOCK(cs_main);
1593  CNodeState *state = State(node);
1594  if (state) state->m_last_block_announcement = time_in_seconds;
1595 }
1596 
1597 void PeerManagerImpl::InitializeNode(CNode& node, ServiceFlags our_services)
1598 {
1599  NodeId nodeid = node.GetId();
1600  {
1601  LOCK(cs_main);
1602  m_node_states.emplace_hint(m_node_states.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(node.IsInboundConn()));
1603  assert(m_txrequest.Count(nodeid) == 0);
1604  }
1605 
1607  our_services = static_cast<ServiceFlags>(our_services | NODE_BLOOM);
1608  }
1609 
1610  PeerRef peer = std::make_shared<Peer>(nodeid, our_services);
1611  {
1612  LOCK(m_peer_mutex);
1613  m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
1614  }
1615  if (!node.IsInboundConn()) {
1616  PushNodeVersion(node, *peer);
1617  }
1618 }
1619 
1620 void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler)
1621 {
1622  std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs();
1623 
1624  for (const auto& txid : unbroadcast_txids) {
1625  CTransactionRef tx = m_mempool.get(txid);
1626 
1627  if (tx != nullptr) {
1628  RelayTransaction(txid, tx->GetWitnessHash());
1629  } else {
1630  m_mempool.RemoveUnbroadcastTx(txid, true);
1631  }
1632  }
1633 
1634  // Schedule next run for 10-15 minutes in the future.
1635  // We add randomness on every cycle to avoid the possibility of P2P fingerprinting.
1636  const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
1637  scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1638 }
1639 
1640 void PeerManagerImpl::FinalizeNode(const CNode& node)
1641 {
1642  NodeId nodeid = node.GetId();
1643  int misbehavior{0};
1644  {
1645  LOCK(cs_main);
1646  {
1647  // We remove the PeerRef from g_peer_map here, but we don't always
1648  // destruct the Peer. Sometimes another thread is still holding a
1649  // PeerRef, so the refcount is >= 1. Be careful not to do any
1650  // processing here that assumes Peer won't be changed before it's
1651  // destructed.
1652  PeerRef peer = RemovePeer(nodeid);
1653  assert(peer != nullptr);
1654  misbehavior = WITH_LOCK(peer->m_misbehavior_mutex, return peer->m_misbehavior_score);
1655  m_wtxid_relay_peers -= peer->m_wtxid_relay;
1656  assert(m_wtxid_relay_peers >= 0);
1657  }
1658  CNodeState *state = State(nodeid);
1659  assert(state != nullptr);
1660 
1661  if (state->fSyncStarted)
1662  nSyncStarted--;
1663 
1664  for (const QueuedBlock& entry : state->vBlocksInFlight) {
1665  auto range = mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash());
1666  while (range.first != range.second) {
1667  auto [node_id, list_it] = range.first->second;
1668  if (node_id != nodeid) {
1669  range.first++;
1670  } else {
1671  range.first = mapBlocksInFlight.erase(range.first);
1672  }
1673  }
1674  }
1675  m_orphanage.EraseForPeer(nodeid);
1676  m_txrequest.DisconnectedPeer(nodeid);
1677  if (m_txreconciliation) m_txreconciliation->ForgetPeer(nodeid);
1678  m_num_preferred_download_peers -= state->fPreferredDownload;
1679  m_peers_downloading_from -= (!state->vBlocksInFlight.empty());
1680  assert(m_peers_downloading_from >= 0);
1681  m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
1682  assert(m_outbound_peers_with_protect_from_disconnect >= 0);
1683 
1684  m_node_states.erase(nodeid);
1685 
1686  if (m_node_states.empty()) {
1687  // Do a consistency check after the last peer is removed.
1688  assert(mapBlocksInFlight.empty());
1689  assert(m_num_preferred_download_peers == 0);
1690  assert(m_peers_downloading_from == 0);
1691  assert(m_outbound_peers_with_protect_from_disconnect == 0);
1692  assert(m_wtxid_relay_peers == 0);
1693  assert(m_txrequest.Size() == 0);
1694  assert(m_orphanage.Size() == 0);
1695  }
1696  } // cs_main
1697  if (node.fSuccessfullyConnected && misbehavior == 0 &&
1698  !node.IsBlockOnlyConn() && !node.IsInboundConn()) {
1699  // Only change visible addrman state for full outbound peers. We don't
1700  // call Connected() for feeler connections since they don't have
1701  // fSuccessfullyConnected set.
1702  m_addrman.Connected(node.addr);
1703  }
1704  {
1705  LOCK(m_headers_presync_mutex);
1706  m_headers_presync_stats.erase(nodeid);
1707  }
1708  LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
1709 }
1710 
1711 bool PeerManagerImpl::HasAllDesirableServiceFlags(ServiceFlags services) const
1712 {
1713  // Shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services)
1714  return !(GetDesirableServiceFlags(services) & (~services));
1715 }
1716 
1717 ServiceFlags PeerManagerImpl::GetDesirableServiceFlags(ServiceFlags services) const
1718 {
1719  if (services & NODE_NETWORK_LIMITED) {
1720  // Limited peers are desirable when we are close to the tip.
1721  if (ApproximateBestBlockDepth() < NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS) {
1723  }
1724  }
1726 }
1727 
1728 PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const
1729 {
1730  LOCK(m_peer_mutex);
1731  auto it = m_peer_map.find(id);
1732  return it != m_peer_map.end() ? it->second : nullptr;
1733 }
1734 
1735 PeerRef PeerManagerImpl::RemovePeer(NodeId id)
1736 {
1737  PeerRef ret;
1738  LOCK(m_peer_mutex);
1739  auto it = m_peer_map.find(id);
1740  if (it != m_peer_map.end()) {
1741  ret = std::move(it->second);
1742  m_peer_map.erase(it);
1743  }
1744  return ret;
1745 }
1746 
1747 bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const
1748 {
1749  {
1750  LOCK(cs_main);
1751  const CNodeState* state = State(nodeid);
1752  if (state == nullptr)
1753  return false;
1754  stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
1755  stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
1756  for (const QueuedBlock& queue : state->vBlocksInFlight) {
1757  if (queue.pindex)
1758  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
1759  }
1760  }
1761 
1762  PeerRef peer = GetPeerRef(nodeid);
1763  if (peer == nullptr) return false;
1764  stats.their_services = peer->m_their_services;
1765  stats.m_starting_height = peer->m_starting_height;
1766  // It is common for nodes with good ping times to suddenly become lagged,
1767  // due to a new block arriving or other large transfer.
1768  // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
1769  // since pingtime does not update until the ping is complete, which might take a while.
1770  // So, if a ping is taking an unusually long time in flight,
1771  // the caller can immediately detect that this is happening.
1772  auto ping_wait{0us};
1773  if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) {
1774  ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
1775  }
1776 
1777  if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
1778  stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs);
1779  stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load();
1780  } else {
1781  stats.m_relay_txs = false;
1782  stats.m_fee_filter_received = 0;
1783  }
1784 
1785  stats.m_ping_wait = ping_wait;
1786  stats.m_addr_processed = peer->m_addr_processed.load();
1787  stats.m_addr_rate_limited = peer->m_addr_rate_limited.load();
1788  stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load();
1789  {
1790  LOCK(peer->m_headers_sync_mutex);
1791  if (peer->m_headers_sync) {
1792  stats.presync_height = peer->m_headers_sync->GetPresyncHeight();
1793  }
1794  }
1795 
1796  return true;
1797 }
1798 
1799 void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx)
1800 {
1801  if (m_opts.max_extra_txs <= 0)
1802  return;
1803  if (!vExtraTxnForCompact.size())
1804  vExtraTxnForCompact.resize(m_opts.max_extra_txs);
1805  vExtraTxnForCompact[vExtraTxnForCompactIt] = tx;
1806  vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs;
1807 }
1808 
1809 void PeerManagerImpl::Misbehaving(Peer& peer, int howmuch, const std::string& message)
1810 {
1811  assert(howmuch > 0);
1812 
1813  LOCK(peer.m_misbehavior_mutex);
1814  const int score_before{peer.m_misbehavior_score};
1815  peer.m_misbehavior_score += howmuch;
1816  const int score_now{peer.m_misbehavior_score};
1817 
1818  const std::string message_prefixed = message.empty() ? "" : (": " + message);
1819  std::string warning;
1820 
1821  if (score_now >= DISCOURAGEMENT_THRESHOLD && score_before < DISCOURAGEMENT_THRESHOLD) {
1822  warning = " DISCOURAGE THRESHOLD EXCEEDED";
1823  peer.m_should_discourage = true;
1824  }
1825 
1826  LogPrint(BCLog::NET, "Misbehaving: peer=%d (%d -> %d)%s%s\n",
1827  peer.m_id, score_before, score_now, warning, message_prefixed);
1828 }
1829 
1830 bool PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
1831  bool via_compact_block, const std::string& message)
1832 {
1833  PeerRef peer{GetPeerRef(nodeid)};
1834  switch (state.GetResult()) {
1836  break;
1838  // We didn't try to process the block because the header chain may have
1839  // too little work.
1840  break;
1841  // The node is providing invalid data:
1844  if (!via_compact_block) {
1845  if (peer) Misbehaving(*peer, 100, message);
1846  return true;
1847  }
1848  break;
1850  {
1851  LOCK(cs_main);
1852  CNodeState *node_state = State(nodeid);
1853  if (node_state == nullptr) {
1854  break;
1855  }
1856 
1857  // Discourage outbound (but not inbound) peers if on an invalid chain.
1858  // Exempt HB compact block peers. Manual connections are always protected from discouragement.
1859  if (!via_compact_block && !node_state->m_is_inbound) {
1860  if (peer) Misbehaving(*peer, 100, message);
1861  return true;
1862  }
1863  break;
1864  }
1868  if (peer) Misbehaving(*peer, 100, message);
1869  return true;
1870  // Conflicting (but not necessarily invalid) data or different policy:
1872  // TODO: Handle this much more gracefully (10 DoS points is super arbitrary)
1873  if (peer) Misbehaving(*peer, 10, message);
1874  return true;
1877  break;
1878  }
1879  if (message != "") {
1880  LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
1881  }
1882  return false;
1883 }
1884 
1885 bool PeerManagerImpl::MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state)
1886 {
1887  PeerRef peer{GetPeerRef(nodeid)};
1888  switch (state.GetResult()) {
1890  break;
1891  // The node is providing invalid data:
1893  if (peer) Misbehaving(*peer, 100, "");
1894  return true;
1895  // Conflicting (but not necessarily invalid) data or different policy:
1908  break;
1909  }
1910  return false;
1911 }
1912 
1913 bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
1914 {
1916  if (m_chainman.ActiveChain().Contains(pindex)) return true;
1917  return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (m_chainman.m_best_header != nullptr) &&
1918  (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
1919  (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
1920 }
1921 
1922 std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index)
1923 {
1924  if (m_chainman.m_blockman.LoadingBlocks()) return "Loading blocks ...";
1925 
1926  // Ensure this peer exists and hasn't been disconnected
1927  PeerRef peer = GetPeerRef(peer_id);
1928  if (peer == nullptr) return "Peer does not exist";
1929 
1930  // Ignore pre-segwit peers
1931  if (!CanServeWitnesses(*peer)) return "Pre-SegWit peer";
1932 
1933  LOCK(cs_main);
1934 
1935  // Forget about all prior requests
1936  RemoveBlockRequest(block_index.GetBlockHash(), std::nullopt);
1937 
1938  // Mark block as in-flight
1939  if (!BlockRequested(peer_id, block_index)) return "Already requested from this peer";
1940 
1941  // Construct message to request the block
1942  const uint256& hash{block_index.GetBlockHash()};
1943  std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)};
1944 
1945  // Send block request message to the peer
1946  bool success = m_connman.ForNode(peer_id, [this, &invs](CNode* node) {
1947  this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs);
1948  return true;
1949  });
1950 
1951  if (!success) return "Peer not fully connected";
1952 
1953  LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1954  hash.ToString(), peer_id);
1955  return std::nullopt;
1956 }
1957 
1958 std::unique_ptr<PeerManager> PeerManager::make(CConnman& connman, AddrMan& addrman,
1959  BanMan* banman, ChainstateManager& chainman,
1960  CTxMemPool& pool, Options opts)
1961 {
1962  return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman, pool, opts);
1963 }
1964 
1965 PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman,
1966  BanMan* banman, ChainstateManager& chainman,
1967  CTxMemPool& pool, Options opts)
1968  : m_rng{opts.deterministic_rng},
1969  m_fee_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}, m_rng},
1970  m_chainparams(chainman.GetParams()),
1971  m_connman(connman),
1972  m_addrman(addrman),
1973  m_banman(banman),
1974  m_chainman(chainman),
1975  m_mempool(pool),
1976  m_opts{opts}
1977 {
1978  // While Erlay support is incomplete, it must be enabled explicitly via -txreconciliation.
1979  // This argument can go away after Erlay support is complete.
1980  if (opts.reconcile_txs) {
1981  m_txreconciliation = std::make_unique<TxReconciliationTracker>(TXRECONCILIATION_VERSION);
1982  }
1983 }
1984 
1985 void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler)
1986 {
1987  // Stale tip checking and peer eviction are on two different timers, but we
1988  // don't want them to get out of sync due to drift in the scheduler, so we
1989  // combine them in one function and schedule at the quicker (peer-eviction)
1990  // timer.
1991  static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
1992  scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL});
1993 
1994  // schedule next run for 10-15 minutes in the future
1995  const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
1996  scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1997 }
1998 
2005 void PeerManagerImpl::BlockConnected(
2006  ChainstateRole role,
2007  const std::shared_ptr<const CBlock>& pblock,
2008  const CBlockIndex* pindex)
2009 {
2010  // Update this for all chainstate roles so that we don't mistakenly see peers
2011  // helping us do background IBD as having a stale tip.
2012  m_last_tip_update = GetTime<std::chrono::seconds>();
2013 
2014  // In case the dynamic timeout was doubled once or more, reduce it slowly back to its default value
2015  auto stalling_timeout = m_block_stalling_timeout.load();
2016  Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT);
2017  if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) {
2018  const auto new_timeout = std::max(std::chrono::duration_cast<std::chrono::seconds>(stalling_timeout * 0.85), BLOCK_STALLING_TIMEOUT_DEFAULT);
2019  if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) {
2020  LogPrint(BCLog::NET, "Decreased stalling timeout to %d seconds\n", count_seconds(new_timeout));
2021  }
2022  }
2023 
2024  // The following task can be skipped since we don't maintain a mempool for
2025  // the ibd/background chainstate.
2026  if (role == ChainstateRole::BACKGROUND) {
2027  return;
2028  }
2029  m_orphanage.EraseForBlock(*pblock);
2030 
2031  {
2032  LOCK(m_recent_confirmed_transactions_mutex);
2033  for (const auto& ptx : pblock->vtx) {
2034  m_recent_confirmed_transactions.insert(ptx->GetHash().ToUint256());
2035  if (ptx->HasWitness()) {
2036  m_recent_confirmed_transactions.insert(ptx->GetWitnessHash().ToUint256());
2037  }
2038  }
2039  }
2040  {
2041  LOCK(cs_main);
2042  for (const auto& ptx : pblock->vtx) {
2043  m_txrequest.ForgetTxHash(ptx->GetHash());
2044  m_txrequest.ForgetTxHash(ptx->GetWitnessHash());
2045  }
2046  }
2047 }
2048 
2049 void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex)
2050 {
2051  // To avoid relay problems with transactions that were previously
2052  // confirmed, clear our filter of recently confirmed transactions whenever
2053  // there's a reorg.
2054  // This means that in a 1-block reorg (where 1 block is disconnected and
2055  // then another block reconnected), our filter will drop to having only one
2056  // block's worth of transactions in it, but that should be fine, since
2057  // presumably the most common case of relaying a confirmed transaction
2058  // should be just after a new block containing it is found.
2059  LOCK(m_recent_confirmed_transactions_mutex);
2060  m_recent_confirmed_transactions.reset();
2061 }
2062 
2067 void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)
2068 {
2069  auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock);
2070 
2071  LOCK(cs_main);
2072 
2073  if (pindex->nHeight <= m_highest_fast_announce)
2074  return;
2075  m_highest_fast_announce = pindex->nHeight;
2076 
2077  if (!DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) return;
2078 
2079  uint256 hashBlock(pblock->GetHash());
2080  const std::shared_future<CSerializedNetMsg> lazy_ser{
2081  std::async(std::launch::deferred, [&] { return NetMsg::Make(NetMsgType::CMPCTBLOCK, *pcmpctblock); })};
2082 
2083  {
2084  auto most_recent_block_txs = std::make_unique<std::map<uint256, CTransactionRef>>();
2085  for (const auto& tx : pblock->vtx) {
2086  most_recent_block_txs->emplace(tx->GetHash(), tx);
2087  most_recent_block_txs->emplace(tx->GetWitnessHash(), tx);
2088  }
2089 
2090  LOCK(m_most_recent_block_mutex);
2091  m_most_recent_block_hash = hashBlock;
2092  m_most_recent_block = pblock;
2093  m_most_recent_compact_block = pcmpctblock;
2094  m_most_recent_block_txs = std::move(most_recent_block_txs);
2095  }
2096 
2097  m_connman.ForEachNode([this, pindex, &lazy_ser, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
2099 
2100  if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
2101  return;
2102  ProcessBlockAvailability(pnode->GetId());
2103  CNodeState &state = *State(pnode->GetId());
2104  // If the peer has, or we announced to them the previous block already,
2105  // but we don't think they have this one, go ahead and announce it
2106  if (state.m_requested_hb_cmpctblocks && !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
2107 
2108  LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock",
2109  hashBlock.ToString(), pnode->GetId());
2110 
2111  const CSerializedNetMsg& ser_cmpctblock{lazy_ser.get()};
2112  PushMessage(*pnode, ser_cmpctblock.Copy());
2113  state.pindexBestHeaderSent = pindex;
2114  }
2115  });
2116 }
2117 
2122 void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
2123 {
2124  SetBestBlock(pindexNew->nHeight, std::chrono::seconds{pindexNew->GetBlockTime()});
2125 
2126  // Don't relay inventory during initial block download.
2127  if (fInitialDownload) return;
2128 
2129  // Find the hashes of all blocks that weren't previously in the best chain.
2130  std::vector<uint256> vHashes;
2131  const CBlockIndex *pindexToAnnounce = pindexNew;
2132  while (pindexToAnnounce != pindexFork) {
2133  vHashes.push_back(pindexToAnnounce->GetBlockHash());
2134  pindexToAnnounce = pindexToAnnounce->pprev;
2135  if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
2136  // Limit announcements in case of a huge reorganization.
2137  // Rely on the peer's synchronization mechanism in that case.
2138  break;
2139  }
2140  }
2141 
2142  {
2143  LOCK(m_peer_mutex);
2144  for (auto& it : m_peer_map) {
2145  Peer& peer = *it.second;
2146  LOCK(peer.m_block_inv_mutex);
2147  for (const uint256& hash : reverse_iterate(vHashes)) {
2148  peer.m_blocks_for_headers_relay.push_back(hash);
2149  }
2150  }
2151  }
2152 
2153  m_connman.WakeMessageHandler();
2154 }
2155 
2160 void PeerManagerImpl::BlockChecked(const CBlock& block, const BlockValidationState& state)
2161 {
2162  LOCK(cs_main);
2163 
2164  const uint256 hash(block.GetHash());
2165  std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
2166 
2167  // If the block failed validation, we know where it came from and we're still connected
2168  // to that peer, maybe punish.
2169  if (state.IsInvalid() &&
2170  it != mapBlockSource.end() &&
2171  State(it->second.first)) {
2172  MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second);
2173  }
2174  // Check that:
2175  // 1. The block is valid
2176  // 2. We're not in initial block download
2177  // 3. This is currently the best block we're aware of. We haven't updated
2178  // the tip yet so we have no way to check this directly here. Instead we
2179  // just check that there are currently no other blocks in flight.
2180  else if (state.IsValid() &&
2181  !m_chainman.IsInitialBlockDownload() &&
2182  mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
2183  if (it != mapBlockSource.end()) {
2184  MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
2185  }
2186  }
2187  if (it != mapBlockSource.end())
2188  mapBlockSource.erase(it);
2189 }
2190 
2192 //
2193 // Messages
2194 //
2195 
2196 
2197 bool PeerManagerImpl::AlreadyHaveTx(const GenTxid& gtxid)
2198 {
2199  if (m_chainman.ActiveChain().Tip()->GetBlockHash() != hashRecentRejectsChainTip) {
2200  // If the chain tip has changed previously rejected transactions
2201  // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
2202  // or a double-spend. Reset the rejects filter and give those
2203  // txs a second chance.
2204  hashRecentRejectsChainTip = m_chainman.ActiveChain().Tip()->GetBlockHash();
2205  m_recent_rejects.reset();
2206  }
2207 
2208  const uint256& hash = gtxid.GetHash();
2209 
2210  if (m_orphanage.HaveTx(gtxid)) return true;
2211 
2212  {
2213  LOCK(m_recent_confirmed_transactions_mutex);
2214  if (m_recent_confirmed_transactions.contains(hash)) return true;
2215  }
2216 
2217  return m_recent_rejects.contains(hash) || m_mempool.exists(gtxid);
2218 }
2219 
2220 bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash)
2221 {
2222  return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
2223 }
2224 
2225 void PeerManagerImpl::SendPings()
2226 {
2227  LOCK(m_peer_mutex);
2228  for(auto& it : m_peer_map) it.second->m_ping_queued = true;
2229 }
2230 
2231 void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid)
2232 {
2233  LOCK(m_peer_mutex);
2234  for(auto& it : m_peer_map) {
2235  Peer& peer = *it.second;
2236  auto tx_relay = peer.GetTxRelay();
2237  if (!tx_relay) continue;
2238 
2239  LOCK(tx_relay->m_tx_inventory_mutex);
2240  // Only queue transactions for announcement once the version handshake
2241  // is completed. The time of arrival for these transactions is
2242  // otherwise at risk of leaking to a spy, if the spy is able to
2243  // distinguish transactions received during the handshake from the rest
2244  // in the announcement.
2245  if (tx_relay->m_next_inv_send_time == 0s) continue;
2246 
2247  const uint256& hash{peer.m_wtxid_relay ? wtxid : txid};
2248  if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) {
2249  tx_relay->m_tx_inventory_to_send.insert(hash);
2250  }
2251  };
2252 }
2253 
2254 void PeerManagerImpl::RelayAddress(NodeId originator,
2255  const CAddress& addr,
2256  bool fReachable)
2257 {
2258  // We choose the same nodes within a given 24h window (if the list of connected
2259  // nodes does not change) and we don't relay to nodes that already know an
2260  // address. So within 24h we will likely relay a given address once. This is to
2261  // prevent a peer from unjustly giving their address better propagation by sending
2262  // it to us repeatedly.
2263 
2264  if (!fReachable && !addr.IsRelayable()) return;
2265 
2266  // Relay to a limited number of other nodes
2267  // Use deterministic randomness to send to the same nodes for 24 hours
2268  // at a time so the m_addr_knowns of the chosen nodes prevent repeats
2269  const uint64_t hash_addr{CServiceHash(0, 0)(addr)};
2270  const auto current_time{GetTime<std::chrono::seconds>()};
2271  // Adding address hash makes exact rotation time different per address, while preserving periodicity.
2272  const uint64_t time_addr{(static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) / count_seconds(ROTATE_ADDR_RELAY_DEST_INTERVAL)};
2274  .Write(hash_addr)
2275  .Write(time_addr)};
2276 
2277  // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers.
2278  unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
2279 
2280  std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}};
2281  assert(nRelayNodes <= best.size());
2282 
2283  LOCK(m_peer_mutex);
2284 
2285  for (auto& [id, peer] : m_peer_map) {
2286  if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) {
2287  uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
2288  for (unsigned int i = 0; i < nRelayNodes; i++) {
2289  if (hashKey > best[i].first) {
2290  std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
2291  best[i] = std::make_pair(hashKey, peer.get());
2292  break;
2293  }
2294  }
2295  }
2296  };
2297 
2298  for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
2299  PushAddress(*best[i].second, addr);
2300  }
2301 }
2302 
2303 void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
2304 {
2305  std::shared_ptr<const CBlock> a_recent_block;
2306  std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
2307  {
2308  LOCK(m_most_recent_block_mutex);
2309  a_recent_block = m_most_recent_block;
2310  a_recent_compact_block = m_most_recent_compact_block;
2311  }
2312 
2313  bool need_activate_chain = false;
2314  {
2315  LOCK(cs_main);
2316  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
2317  if (pindex) {
2318  if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
2319  pindex->IsValid(BLOCK_VALID_TREE)) {
2320  // If we have the block and all of its parents, but have not yet validated it,
2321  // we might be in the middle of connecting it (ie in the unlock of cs_main
2322  // before ActivateBestChain but after AcceptBlock).
2323  // In this case, we need to run ActivateBestChain prior to checking the relay
2324  // conditions below.
2325  need_activate_chain = true;
2326  }
2327  }
2328  } // release cs_main before calling ActivateBestChain
2329  if (need_activate_chain) {
2330  BlockValidationState state;
2331  if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
2332  LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
2333  }
2334  }
2335 
2336  LOCK(cs_main);
2337  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
2338  if (!pindex) {
2339  return;
2340  }
2341  if (!BlockRequestAllowed(pindex)) {
2342  LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId());
2343  return;
2344  }
2345  // disconnect node in case we have reached the outbound limit for serving historical blocks
2346  if (m_connman.OutboundTargetReached(true) &&
2347  (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&
2348  !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target
2349  ) {
2350  LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom.GetId());
2351  pfrom.fDisconnect = true;
2352  return;
2353  }
2354  // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
2355  if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && (
2356  (((peer.m_our_services & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) && (m_chainman.ActiveChain().Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
2357  )) {
2358  LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, disconnect peer=%d\n", pfrom.GetId());
2359  //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
2360  pfrom.fDisconnect = true;
2361  return;
2362  }
2363  // Pruned nodes may have deleted the block, so check whether
2364  // it's available before trying to send.
2365  if (!(pindex->nStatus & BLOCK_HAVE_DATA)) {
2366  return;
2367  }
2368  std::shared_ptr<const CBlock> pblock;
2369  if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
2370  pblock = a_recent_block;
2371  } else if (inv.IsMsgWitnessBlk()) {
2372  // Fast-path: in this case it is possible to serve the block directly from disk,
2373  // as the network format matches the format on disk
2374  std::vector<uint8_t> block_data;
2375  if (!m_chainman.m_blockman.ReadRawBlockFromDisk(block_data, pindex->GetBlockPos())) {
2376  assert(!"cannot load block from disk");
2377  }
2378  MakeAndPushMessage(pfrom, NetMsgType::BLOCK, Span{block_data});
2379  // Don't set pblock as we've sent the block
2380  } else {
2381  // Send block from disk
2382  std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
2383  if (!m_chainman.m_blockman.ReadBlockFromDisk(*pblockRead, *pindex)) {
2384  assert(!"cannot load block from disk");
2385  }
2386  pblock = pblockRead;
2387  }
2388  if (pblock) {
2389  if (inv.IsMsgBlk()) {
2390  MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_NO_WITNESS(*pblock));
2391  } else if (inv.IsMsgWitnessBlk()) {
2392  MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock));
2393  } else if (inv.IsMsgFilteredBlk()) {
2394  bool sendMerkleBlock = false;
2395  CMerkleBlock merkleBlock;
2396  if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
2397  LOCK(tx_relay->m_bloom_filter_mutex);
2398  if (tx_relay->m_bloom_filter) {
2399  sendMerkleBlock = true;
2400  merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
2401  }
2402  }
2403  if (sendMerkleBlock) {
2404  MakeAndPushMessage(pfrom, NetMsgType::MERKLEBLOCK, merkleBlock);
2405  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
2406  // This avoids hurting performance by pointlessly requiring a round-trip
2407  // Note that there is currently no way for a node to request any single transactions we didn't send here -
2408  // they must either disconnect and retry or request the full block.
2409  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
2410  // however we MUST always provide at least what the remote peer needs
2411  typedef std::pair<unsigned int, uint256> PairType;
2412  for (PairType& pair : merkleBlock.vMatchedTxn)
2413  MakeAndPushMessage(pfrom, NetMsgType::TX, TX_NO_WITNESS(*pblock->vtx[pair.first]));
2414  }
2415  // else
2416  // no response
2417  } else if (inv.IsMsgCmpctBlk()) {
2418  // If a peer is asking for old blocks, we're almost guaranteed
2419  // they won't have a useful mempool to match against a compact block,
2420  // and we don't feel like constructing the object for them, so
2421  // instead we respond with the full, non-compact block.
2422  if (CanDirectFetch() && pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_CMPCTBLOCK_DEPTH) {
2423  if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
2424  MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, *a_recent_compact_block);
2425  } else {
2426  CBlockHeaderAndShortTxIDs cmpctblock{*pblock};
2427  MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, cmpctblock);
2428  }
2429  } else {
2430  MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock));
2431  }
2432  }
2433  }
2434 
2435  {
2436  LOCK(peer.m_block_inv_mutex);
2437  // Trigger the peer node to send a getblocks request for the next batch of inventory
2438  if (inv.hash == peer.m_continuation_block) {
2439  // Send immediately. This must send even if redundant,
2440  // and we want it right after the last block so they don't
2441  // wait for other stuff first.
2442  std::vector<CInv> vInv;
2443  vInv.emplace_back(MSG_BLOCK, m_chainman.ActiveChain().Tip()->GetBlockHash());
2444  MakeAndPushMessage(pfrom, NetMsgType::INV, vInv);
2445  peer.m_continuation_block.SetNull();
2446  }
2447  }
2448 }
2449 
2450 CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid)
2451 {
2452  // If a tx was in the mempool prior to the last INV for this peer, permit the request.
2453  auto txinfo = m_mempool.info_for_relay(gtxid, tx_relay.m_last_inv_sequence);
2454  if (txinfo.tx) {
2455  return std::move(txinfo.tx);
2456  }
2457 
2458  // Or it might be from the most recent block
2459  {
2460  LOCK(m_most_recent_block_mutex);
2461  if (m_most_recent_block_txs != nullptr) {
2462  auto it = m_most_recent_block_txs->find(gtxid.GetHash());
2463  if (it != m_most_recent_block_txs->end()) return it->second;
2464  }
2465  }
2466 
2467  return {};
2468 }
2469 
2470 void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
2471 {
2473 
2474  auto tx_relay = peer.GetTxRelay();
2475 
2476  std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
2477  std::vector<CInv> vNotFound;
2478 
2479  // Process as many TX items from the front of the getdata queue as
2480  // possible, since they're common and it's efficient to batch process
2481  // them.
2482  while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) {
2483  if (interruptMsgProc) return;
2484  // The send buffer provides backpressure. If there's no space in
2485  // the buffer, pause processing until the next call.
2486  if (pfrom.fPauseSend) break;
2487 
2488  const CInv &inv = *it++;
2489 
2490  if (tx_relay == nullptr) {
2491  // Ignore GETDATA requests for transactions from block-relay-only
2492  // peers and peers that asked us not to announce transactions.
2493  continue;
2494  }
2495 
2496  CTransactionRef tx = FindTxForGetData(*tx_relay, ToGenTxid(inv));
2497  if (tx) {
2498  // WTX and WITNESS_TX imply we serialize with witness
2499  const auto maybe_with_witness = (inv.IsMsgTx() ? TX_NO_WITNESS : TX_WITH_WITNESS);
2500  MakeAndPushMessage(pfrom, NetMsgType::TX, maybe_with_witness(*tx));
2501  m_mempool.RemoveUnbroadcastTx(tx->GetHash());
2502  } else {
2503  vNotFound.push_back(inv);
2504  }
2505  }
2506 
2507  // Only process one BLOCK item per call, since they're uncommon and can be
2508  // expensive to process.
2509  if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
2510  const CInv &inv = *it++;
2511  if (inv.IsGenBlkMsg()) {
2512  ProcessGetBlockData(pfrom, peer, inv);
2513  }
2514  // else: If the first item on the queue is an unknown type, we erase it
2515  // and continue processing the queue on the next call.
2516  }
2517 
2518  peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
2519 
2520  if (!vNotFound.empty()) {
2521  // Let the peer know that we didn't find what it asked for, so it doesn't
2522  // have to wait around forever.
2523  // SPV clients care about this message: it's needed when they are
2524  // recursively walking the dependencies of relevant unconfirmed
2525  // transactions. SPV clients want to do that because they want to know
2526  // about (and store and rebroadcast and risk analyze) the dependencies
2527  // of transactions relevant to them, without having to download the
2528  // entire memory pool.
2529  // Also, other nodes can use these messages to automatically request a
2530  // transaction from some other peer that announced it, and stop
2531  // waiting for us to respond.
2532  // In normal operation, we often send NOTFOUND messages for parents of
2533  // transactions that we relay; if a peer is missing a parent, they may
2534  // assume we have them and request the parents from us.
2535  MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound);
2536  }
2537 }
2538 
2539 uint32_t PeerManagerImpl::GetFetchFlags(const Peer& peer) const
2540 {
2541  uint32_t nFetchFlags = 0;
2542  if (CanServeWitnesses(peer)) {
2543  nFetchFlags |= MSG_WITNESS_FLAG;
2544  }
2545  return nFetchFlags;
2546 }
2547 
2548 void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req)
2549 {
2550  BlockTransactions resp(req);
2551  for (size_t i = 0; i < req.indexes.size(); i++) {
2552  if (req.indexes[i] >= block.vtx.size()) {
2553  Misbehaving(peer, 100, "getblocktxn with out-of-bounds tx indices");
2554  return;
2555  }
2556  resp.txn[i] = block.vtx[req.indexes[i]];
2557  }
2558 
2559  MakeAndPushMessage(pfrom, NetMsgType::BLOCKTXN, resp);
2560 }
2561 
2562 bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer)
2563 {
2564  // Do these headers have proof-of-work matching what's claimed?
2565  if (!HasValidProofOfWork(headers, consensusParams)) {
2566  Misbehaving(peer, 100, "header with invalid proof of work");
2567  return false;
2568  }
2569 
2570  // Are these headers connected to each other?
2571  if (!CheckHeadersAreContinuous(headers)) {
2572  Misbehaving(peer, 20, "non-continuous headers sequence");
2573  return false;
2574  }
2575  return true;
2576 }
2577 
2578 arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold()
2579 {
2580  arith_uint256 near_chaintip_work = 0;
2581  LOCK(cs_main);
2582  if (m_chainman.ActiveChain().Tip() != nullptr) {
2583  const CBlockIndex *tip = m_chainman.ActiveChain().Tip();
2584  // Use a 144 block buffer, so that we'll accept headers that fork from
2585  // near our tip.
2586  near_chaintip_work = tip->nChainWork - std::min<arith_uint256>(144*GetBlockProof(*tip), tip->nChainWork);
2587  }
2588  return std::max(near_chaintip_work, m_chainman.MinimumChainWork());
2589 }
2590 
2603 void PeerManagerImpl::HandleFewUnconnectingHeaders(CNode& pfrom, Peer& peer,
2604  const std::vector<CBlockHeader>& headers)
2605 {
2606  peer.m_num_unconnecting_headers_msgs++;
2607  // Try to fill in the missing headers.
2608  const CBlockIndex* best_header{WITH_LOCK(cs_main, return m_chainman.m_best_header)};
2609  if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) {
2610  LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, m_num_unconnecting_headers_msgs=%d)\n",
2611  headers[0].GetHash().ToString(),
2612  headers[0].hashPrevBlock.ToString(),
2613  best_header->nHeight,
2614  pfrom.GetId(), peer.m_num_unconnecting_headers_msgs);
2615  }
2616 
2617  // Set hashLastUnknownBlock for this peer, so that if we
2618  // eventually get the headers - even from a different peer -
2619  // we can use this peer to download.
2620  WITH_LOCK(cs_main, UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash()));
2621 
2622  // The peer may just be broken, so periodically assign DoS points if this
2623  // condition persists.
2624  if (peer.m_num_unconnecting_headers_msgs % MAX_NUM_UNCONNECTING_HEADERS_MSGS == 0) {
2625  Misbehaving(peer, 20, strprintf("%d non-connecting headers", peer.m_num_unconnecting_headers_msgs));
2626  }
2627 }
2628 
2629 bool PeerManagerImpl::CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const
2630 {
2631  uint256 hashLastBlock;
2632  for (const CBlockHeader& header : headers) {
2633  if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2634  return false;
2635  }
2636  hashLastBlock = header.GetHash();
2637  }
2638  return true;
2639 }
2640 
2641 bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers)
2642 {
2643  if (peer.m_headers_sync) {
2644  auto result = peer.m_headers_sync->ProcessNextHeaders(headers, headers.size() == MAX_HEADERS_RESULTS);
2645  if (result.request_more) {
2646  auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
2647  // If we were instructed to ask for a locator, it should not be empty.
2648  Assume(!locator.vHave.empty());
2649  if (!locator.vHave.empty()) {
2650  // It should be impossible for the getheaders request to fail,
2651  // because we should have cleared the last getheaders timestamp
2652  // when processing the headers that triggered this call. But
2653  // it may be possible to bypass this via compactblock
2654  // processing, so check the result before logging just to be
2655  // safe.
2656  bool sent_getheaders = MaybeSendGetHeaders(pfrom, locator, peer);
2657  if (sent_getheaders) {
2658  LogPrint(BCLog::NET, "more getheaders (from %s) to peer=%d\n",
2659  locator.vHave.front().ToString(), pfrom.GetId());
2660  } else {
2661  LogPrint(BCLog::NET, "error sending next getheaders (from %s) to continue sync with peer=%d\n",
2662  locator.vHave.front().ToString(), pfrom.GetId());
2663  }
2664  }
2665  }
2666 
2667  if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) {
2668  peer.m_headers_sync.reset(nullptr);
2669 
2670  // Delete this peer's entry in m_headers_presync_stats.
2671  // If this is m_headers_presync_bestpeer, it will be replaced later
2672  // by the next peer that triggers the else{} branch below.
2673  LOCK(m_headers_presync_mutex);
2674  m_headers_presync_stats.erase(pfrom.GetId());
2675  } else {
2676  // Build statistics for this peer's sync.
2677  HeadersPresyncStats stats;
2678  stats.first = peer.m_headers_sync->GetPresyncWork();
2679  if (peer.m_headers_sync->GetState() == HeadersSyncState::State::PRESYNC) {
2680  stats.second = {peer.m_headers_sync->GetPresyncHeight(),
2681  peer.m_headers_sync->GetPresyncTime()};
2682  }
2683 
2684  // Update statistics in stats.
2685  LOCK(m_headers_presync_mutex);
2686  m_headers_presync_stats[pfrom.GetId()] = stats;
2687  auto best_it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
2688  bool best_updated = false;
2689  if (best_it == m_headers_presync_stats.end()) {
2690  // If the cached best peer is outdated, iterate over all remaining ones (including
2691  // newly updated one) to find the best one.
2692  NodeId peer_best{-1};
2693  const HeadersPresyncStats* stat_best{nullptr};
2694  for (const auto& [peer, stat] : m_headers_presync_stats) {
2695  if (!stat_best || stat > *stat_best) {
2696  peer_best = peer;
2697  stat_best = &stat;
2698  }
2699  }
2700  m_headers_presync_bestpeer = peer_best;
2701  best_updated = (peer_best == pfrom.GetId());
2702  } else if (best_it->first == pfrom.GetId() || stats > best_it->second) {
2703  // pfrom was and remains the best peer, or pfrom just became best.
2704  m_headers_presync_bestpeer = pfrom.GetId();
2705  best_updated = true;
2706  }
2707  if (best_updated && stats.second.has_value()) {
2708  // If the best peer updated, and it is in its first phase, signal.
2709  m_headers_presync_should_signal = true;
2710  }
2711  }
2712 
2713  if (result.success) {
2714  // We only overwrite the headers passed in if processing was
2715  // successful.
2716  headers.swap(result.pow_validated_headers);
2717  }
2718 
2719  return result.success;
2720  }
2721  // Either we didn't have a sync in progress, or something went wrong
2722  // processing these headers, or we are returning headers to the caller to
2723  // process.
2724  return false;
2725 }
2726 
2727 bool PeerManagerImpl::TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex* chain_start_header, std::vector<CBlockHeader>& headers)
2728 {
2729  // Calculate the claimed total work on this chain.
2730  arith_uint256 total_work = chain_start_header->nChainWork + CalculateClaimedHeadersWork(headers);
2731 
2732  // Our dynamic anti-DoS threshold (minimum work required on a headers chain
2733  // before we'll store it)
2734  arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
2735 
2736  // Avoid DoS via low-difficulty-headers by only processing if the headers
2737  // are part of a chain with sufficient work.
2738  if (total_work < minimum_chain_work) {
2739  // Only try to sync with this peer if their headers message was full;
2740  // otherwise they don't have more headers after this so no point in
2741  // trying to sync their too-little-work chain.
2742  if (headers.size() == MAX_HEADERS_RESULTS) {
2743  // Note: we could advance to the last header in this set that is
2744  // known to us, rather than starting at the first header (which we
2745  // may already have); however this is unlikely to matter much since
2746  // ProcessHeadersMessage() already handles the case where all
2747  // headers in a received message are already known and are
2748  // ancestors of m_best_header or chainActive.Tip(), by skipping
2749  // this logic in that case. So even if the first header in this set
2750  // of headers is known, some header in this set must be new, so
2751  // advancing to the first unknown header would be a small effect.
2752  LOCK(peer.m_headers_sync_mutex);
2753  peer.m_headers_sync.reset(new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(),
2754  chain_start_header, minimum_chain_work));
2755 
2756  // Now a HeadersSyncState object for tracking this synchronization
2757  // is created, process the headers using it as normal. Failures are
2758  // handled inside of IsContinuationOfLowWorkHeadersSync.
2759  (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
2760  } else {
2761  LogPrint(BCLog::NET, "Ignoring low-work chain (height=%u) from peer=%d\n", chain_start_header->nHeight + headers.size(), pfrom.GetId());
2762  }
2763 
2764  // The peer has not yet given us a chain that meets our work threshold,
2765  // so we want to prevent further processing of the headers in any case.
2766  headers = {};
2767  return true;
2768  }
2769 
2770  return false;
2771 }
2772 
2773 bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex* header)
2774 {
2775  if (header == nullptr) {
2776  return false;
2777  } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) {
2778  return true;
2779  } else if (m_chainman.ActiveChain().Contains(header)) {
2780  return true;
2781  }
2782  return false;
2783 }
2784 
2785 bool PeerManagerImpl::MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer)
2786 {
2787  const auto current_time = NodeClock::now();
2788 
2789  // Only allow a new getheaders message to go out if we don't have a recent
2790  // one already in-flight
2791  if (current_time - peer.m_last_getheaders_timestamp > HEADERS_RESPONSE_TIME) {
2792  MakeAndPushMessage(pfrom, NetMsgType::GETHEADERS, locator, uint256());
2793  peer.m_last_getheaders_timestamp = current_time;
2794  return true;
2795  }
2796  return false;
2797 }
2798 
2799 /*
2800  * Given a new headers tip ending in last_header, potentially request blocks towards that tip.
2801  * We require that the given tip have at least as much work as our tip, and for
2802  * our current tip to be "close to synced" (see CanDirectFetch()).
2803  */
2804 void PeerManagerImpl::HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header)
2805 {
2806  LOCK(cs_main);
2807  CNodeState *nodestate = State(pfrom.GetId());
2808 
2809  if (CanDirectFetch() && last_header.IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork) {
2810  std::vector<const CBlockIndex*> vToFetch;
2811  const CBlockIndex* pindexWalk{&last_header};
2812  // Calculate all the blocks we'd need to switch to last_header, up to a limit.
2813  while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2814  if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
2815  !IsBlockRequested(pindexWalk->GetBlockHash()) &&
2816  (!DeploymentActiveAt(*pindexWalk, m_chainman, Consensus::DEPLOYMENT_SEGWIT) || CanServeWitnesses(peer))) {
2817  // We don't have this block, and it's not yet in flight.
2818  vToFetch.push_back(pindexWalk);
2819  }
2820  pindexWalk = pindexWalk->pprev;
2821  }
2822  // If pindexWalk still isn't on our main chain, we're looking at a
2823  // very large reorg at a time we think we're close to caught up to
2824  // the main chain -- this shouldn't really happen. Bail out on the
2825  // direct fetch and rely on parallel download instead.
2826  if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
2827  LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
2828  last_header.GetBlockHash().ToString(),
2829  last_header.nHeight);
2830  } else {
2831  std::vector<CInv> vGetData;
2832  // Download as much as possible, from earliest to latest.
2833  for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
2834  if (nodestate->vBlocksInFlight.size() >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2835  // Can't download any more from this peer
2836  break;
2837  }
2838  uint32_t nFetchFlags = GetFetchFlags(peer);
2839  vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash());
2840  BlockRequested(pfrom.GetId(), *pindex);
2841  LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
2842  pindex->GetBlockHash().ToString(), pfrom.GetId());
2843  }
2844  if (vGetData.size() > 1) {
2845  LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2846  last_header.GetBlockHash().ToString(),
2847  last_header.nHeight);
2848  }
2849  if (vGetData.size() > 0) {
2850  if (!m_opts.ignore_incoming_txs &&
2851  nodestate->m_provides_cmpctblocks &&
2852  vGetData.size() == 1 &&
2853  mapBlocksInFlight.size() == 1 &&
2854  last_header.pprev->IsValid(BLOCK_VALID_CHAIN)) {
2855  // In any case, we want to download using a compact block, not a regular one
2856  vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
2857  }
2858  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vGetData);
2859  }
2860  }
2861  }
2862 }
2863 
2869 void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer,
2870  const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers)
2871 {
2872  if (peer.m_num_unconnecting_headers_msgs > 0) {
2873  LogPrint(BCLog::NET, "peer=%d: resetting m_num_unconnecting_headers_msgs (%d -> 0)\n", pfrom.GetId(), peer.m_num_unconnecting_headers_msgs);
2874  }
2875  peer.m_num_unconnecting_headers_msgs = 0;
2876 
2877  LOCK(cs_main);
2878  CNodeState *nodestate = State(pfrom.GetId());
2879 
2880  UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash());
2881 
2882  // From here, pindexBestKnownBlock should be guaranteed to be non-null,
2883  // because it is set in UpdateBlockAvailability. Some nullptr checks
2884  // are still present, however, as belt-and-suspenders.
2885 
2886  if (received_new_header && last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
2887  nodestate->m_last_block_announcement = GetTime();
2888  }
2889 
2890  // If we're in IBD, we want outbound peers that will serve us a useful
2891  // chain. Disconnect peers that are on chains with insufficient work.
2892  if (m_chainman.IsInitialBlockDownload() && !may_have_more_headers) {
2893  // If the peer has no more headers to give us, then we know we have
2894  // their tip.
2895  if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) {
2896  // This peer has too little work on their headers chain to help
2897  // us sync -- disconnect if it is an outbound disconnection
2898  // candidate.
2899  // Note: We compare their tip to the minimum chain work (rather than
2900  // m_chainman.ActiveChain().Tip()) because we won't start block download
2901  // until we have a headers chain that has at least
2902  // the minimum chain work, even if a peer has a chain past our tip,
2903  // as an anti-DoS measure.
2904  if (pfrom.IsOutboundOrBlockRelayConn()) {
2905  LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom.GetId());
2906  pfrom.fDisconnect = true;
2907  }
2908  }
2909  }
2910 
2911  // If this is an outbound full-relay peer, check to see if we should protect
2912  // it from the bad/lagging chain logic.
2913  // Note that outbound block-relay peers are excluded from this protection, and
2914  // thus always subject to eviction under the bad/lagging chain logic.
2915  // See ChainSyncTimeoutState.
2916  if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) {
2917  if (m_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) {
2918  LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId());
2919  nodestate->m_chain_sync.m_protect = true;
2920  ++m_outbound_peers_with_protect_from_disconnect;
2921  }
2922  }
2923 }
2924 
2925 void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, Peer& peer,
2926  std::vector<CBlockHeader>&& headers,
2927  bool via_compact_block)
2928 {
2929  size_t nCount = headers.size();
2930 
2931  if (nCount == 0) {
2932  // Nothing interesting. Stop asking this peers for more headers.
2933  // If we were in the middle of headers sync, receiving an empty headers
2934  // message suggests that the peer suddenly has nothing to give us
2935  // (perhaps it reorged to our chain). Clear download state for this peer.
2936  LOCK(peer.m_headers_sync_mutex);
2937  if (peer.m_headers_sync) {
2938  peer.m_headers_sync.reset(nullptr);
2939  LOCK(m_headers_presync_mutex);
2940  m_headers_presync_stats.erase(pfrom.GetId());
2941  }
2942  return;
2943  }
2944 
2945  // Before we do any processing, make sure these pass basic sanity checks.
2946  // We'll rely on headers having valid proof-of-work further down, as an
2947  // anti-DoS criteria (note: this check is required before passing any
2948  // headers into HeadersSyncState).
2949  if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) {
2950  // Misbehaving() calls are handled within CheckHeadersPoW(), so we can
2951  // just return. (Note that even if a header is announced via compact
2952  // block, the header itself should be valid, so this type of error can
2953  // always be punished.)
2954  return;
2955  }
2956 
2957  const CBlockIndex *pindexLast = nullptr;
2958 
2959  // We'll set already_validated_work to true if these headers are
2960  // successfully processed as part of a low-work headers sync in progress
2961  // (either in PRESYNC or REDOWNLOAD phase).
2962  // If true, this will mean that any headers returned to us (ie during
2963  // REDOWNLOAD) can be validated without further anti-DoS checks.
2964  bool already_validated_work = false;
2965 
2966  // If we're in the middle of headers sync, let it do its magic.
2967  bool have_headers_sync = false;
2968  {
2969  LOCK(peer.m_headers_sync_mutex);
2970 
2971  already_validated_work = IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
2972 
2973  // The headers we passed in may have been:
2974  // - untouched, perhaps if no headers-sync was in progress, or some
2975  // failure occurred
2976  // - erased, such as if the headers were successfully processed and no
2977  // additional headers processing needs to take place (such as if we
2978  // are still in PRESYNC)
2979  // - replaced with headers that are now ready for validation, such as
2980  // during the REDOWNLOAD phase of a low-work headers sync.
2981  // So just check whether we still have headers that we need to process,
2982  // or not.
2983  if (headers.empty()) {
2984  return;
2985  }
2986 
2987  have_headers_sync = !!peer.m_headers_sync;
2988  }
2989 
2990  // Do these headers connect to something in our block index?
2991  const CBlockIndex *chain_start_header{WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock))};
2992  bool headers_connect_blockindex{chain_start_header != nullptr};
2993 
2994  if (!headers_connect_blockindex) {
2995  if (nCount <= MAX_BLOCKS_TO_ANNOUNCE) {
2996  // If this looks like it could be a BIP 130 block announcement, use
2997  // special logic for handling headers that don't connect, as this
2998  // could be benign.
2999  HandleFewUnconnectingHeaders(pfrom, peer, headers);
3000  } else {
3001  Misbehaving(peer, 10, "invalid header received");
3002  }
3003  return;
3004  }
3005 
3006  // If the headers we received are already in memory and an ancestor of
3007  // m_best_header or our tip, skip anti-DoS checks. These headers will not
3008  // use any more memory (and we are not leaking information that could be
3009  // used to fingerprint us).
3010  const CBlockIndex *last_received_header{nullptr};
3011  {
3012  LOCK(cs_main);
3013  last_received_header = m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash());
3014  if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
3015  already_validated_work = true;
3016  }
3017  }
3018 
3019  // If our peer has NetPermissionFlags::NoBan privileges, then bypass our
3020  // anti-DoS logic (this saves bandwidth when we connect to a trusted peer
3021  // on startup).
3023  already_validated_work = true;
3024  }
3025 
3026  // At this point, the headers connect to something in our block index.
3027  // Do anti-DoS checks to determine if we should process or store for later
3028  // processing.
3029  if (!already_validated_work && TryLowWorkHeadersSync(peer, pfrom,
3030  chain_start_header, headers)) {
3031  // If we successfully started a low-work headers sync, then there
3032  // should be no headers to process any further.
3033  Assume(headers.empty());
3034  return;
3035  }
3036 
3037  // At this point, we have a set of headers with sufficient work on them
3038  // which can be processed.
3039 
3040  // If we don't have the last header, then this peer will have given us
3041  // something new (if these headers are valid).
3042  bool received_new_header{last_received_header == nullptr};
3043 
3044  // Now process all the headers.
3045  BlockValidationState state;
3046  if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true, state, &pindexLast)) {
3047  if (state.IsInvalid()) {
3048  MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received");
3049  return;
3050  }
3051  }
3052  assert(pindexLast);
3053 
3054  // Consider fetching more headers if we are not using our headers-sync mechanism.
3055  if (nCount == MAX_HEADERS_RESULTS && !have_headers_sync) {
3056  // Headers message had its maximum size; the peer may have more headers.
3057  if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) {
3058  LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
3059  pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
3060  }
3061  }
3062 
3063  UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast, received_new_header, nCount == MAX_HEADERS_RESULTS);
3064 
3065  // Consider immediately downloading blocks.
3066  HeadersDirectFetchBlocks(pfrom, peer, *pindexLast);
3067 
3068  return;
3069 }
3070 
3071 void PeerManagerImpl::ProcessInvalidTx(NodeId nodeid, const CTransactionRef& ptx, const TxValidationState& state,
3072  bool maybe_add_extra_compact_tx)
3073 {
3074  AssertLockNotHeld(m_peer_mutex);
3075  AssertLockHeld(g_msgproc_mutex);
3077 
3078  LogDebug(BCLog::MEMPOOLREJ, "%s (wtxid=%s) from peer=%d was not accepted: %s\n",
3079  ptx->GetHash().ToString(),
3080  ptx->GetWitnessHash().ToString(),
3081  nodeid,
3082  state.ToString());
3083 
3085  return;
3086  } else if (state.GetResult() != TxValidationResult::TX_WITNESS_STRIPPED) {
3087  // We can add the wtxid of this transaction to our reject filter.
3088  // Do not add txids of witness transactions or witness-stripped
3089  // transactions to the filter, as they can have been malleated;
3090  // adding such txids to the reject filter would potentially
3091  // interfere with relay of valid transactions from peers that
3092  // do not support wtxid-based relay. See
3093  // https://github.com/bitcoin/bitcoin/issues/8279 for details.
3094  // We can remove this restriction (and always add wtxids to
3095  // the filter even for witness stripped transactions) once
3096  // wtxid-based relay is broadly deployed.
3097  // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
3098  // for concerns around weakening security of unupgraded nodes
3099  // if we start doing this too early.
3100  m_recent_rejects.insert(ptx->GetWitnessHash().ToUint256());
3101  m_txrequest.ForgetTxHash(ptx->GetWitnessHash());
3102  // If the transaction failed for TX_INPUTS_NOT_STANDARD,
3103  // then we know that the witness was irrelevant to the policy
3104  // failure, since this check depends only on the txid
3105  // (the scriptPubKey being spent is covered by the txid).
3106  // Add the txid to the reject filter to prevent repeated
3107  // processing of this transaction in the event that child
3108  // transactions are later received (resulting in
3109  // parent-fetching by txid via the orphan-handling logic).
3110  if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && ptx->HasWitness()) {
3111  m_recent_rejects.insert(ptx->GetHash().ToUint256());
3112  m_txrequest.ForgetTxHash(ptx->GetHash());
3113  }
3114  if (maybe_add_extra_compact_tx && RecursiveDynamicUsage(*ptx) < 100000) {
3115  AddToCompactExtraTransactions(ptx);
3116  }
3117  }
3118 
3119  MaybePunishNodeForTx(nodeid, state);
3120 
3121  // If the tx failed in ProcessOrphanTx, it should be removed from the orphanage unless the
3122  // tx was still missing inputs. If the tx was not in the orphanage, EraseTx does nothing and returns 0.
3123  if (Assume(state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) && m_orphanage.EraseTx(ptx->GetHash()) > 0) {
3124  LogDebug(BCLog::TXPACKAGES, " removed orphan tx %s (wtxid=%s)\n", ptx->GetHash().ToString(), ptx->GetWitnessHash().ToString());
3125  }
3126 }
3127 
3128 void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef& tx, const std::list<CTransactionRef>& replaced_transactions)
3129 {
3130  AssertLockNotHeld(m_peer_mutex);
3131  AssertLockHeld(g_msgproc_mutex);
3133 
3134  // As this version of the transaction was acceptable, we can forget about any requests for it.
3135  // No-op if the tx is not in txrequest.
3136  m_txrequest.ForgetTxHash(tx->GetHash());
3137  m_txrequest.ForgetTxHash(tx->GetWitnessHash());
3138 
3139  m_orphanage.AddChildrenToWorkSet(*tx);
3140  // If it came from the orphanage, remove it. No-op if the tx is not in txorphanage.
3141  m_orphanage.EraseTx(tx->GetHash());
3142 
3143  LogDebug(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (wtxid=%s) (poolsz %u txn, %u kB)\n",
3144  nodeid,
3145  tx->GetHash().ToString(),
3146  tx->GetWitnessHash().ToString(),
3147  m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000);
3148 
3149  RelayTransaction(tx->GetHash(), tx->GetWitnessHash());
3150 
3151  for (const CTransactionRef& removedTx : replaced_transactions) {
3152  AddToCompactExtraTransactions(removedTx);
3153  }
3154 }
3155 
3156 bool PeerManagerImpl::ProcessOrphanTx(Peer& peer)
3157 {
3158  AssertLockHeld(g_msgproc_mutex);
3159  LOCK(cs_main);
3160 
3161  CTransactionRef porphanTx = nullptr;
3162 
3163  while (CTransactionRef porphanTx = m_orphanage.GetTxToReconsider(peer.m_id)) {
3164  const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx);
3165  const TxValidationState& state = result.m_state;
3166  const Txid& orphanHash = porphanTx->GetHash();
3167  const Wtxid& orphan_wtxid = porphanTx->GetWitnessHash();
3168 
3170  LogPrint(BCLog::TXPACKAGES, " accepted orphan tx %s (wtxid=%s)\n", orphanHash.ToString(), orphan_wtxid.ToString());
3171  Assume(result.m_replaced_transactions.has_value());
3172  std::list<CTransactionRef> empty_replacement_list;
3173  ProcessValidTx(peer.m_id, porphanTx, result.m_replaced_transactions.value_or(empty_replacement_list));
3174  return true;
3175  } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) {
3176  LogPrint(BCLog::TXPACKAGES, " invalid orphan tx %s (wtxid=%s) from peer=%d. %s\n",
3177  orphanHash.ToString(),
3178  orphan_wtxid.ToString(),
3179  peer.m_id,
3180  state.ToString());
3181 
3182  if (Assume(state.IsInvalid() &&
3186  ProcessInvalidTx(peer.m_id, porphanTx, state, /*maybe_add_extra_compact_tx=*/false);
3187  }
3188  return true;
3189  }
3190  }
3191 
3192  return false;
3193 }
3194 
3195 bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& node, Peer& peer,
3196  BlockFilterType filter_type, uint32_t start_height,
3197  const uint256& stop_hash, uint32_t max_height_diff,
3198  const CBlockIndex*& stop_index,
3199  BlockFilterIndex*& filter_index)
3200 {
3201  const bool supported_filter_type =
3202  (filter_type == BlockFilterType::BASIC &&
3203  (peer.m_our_services & NODE_COMPACT_FILTERS));
3204  if (!supported_filter_type) {
3205  LogPrint(BCLog::NET, "peer %d requested unsupported block filter type: %d\n",
3206  node.GetId(), static_cast<uint8_t>(filter_type));
3207  node.fDisconnect = true;
3208  return false;
3209  }
3210 
3211  {
3212  LOCK(cs_main);
3213  stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
3214 
3215  // Check that the stop block exists and the peer would be allowed to fetch it.
3216  if (!stop_index || !BlockRequestAllowed(stop_index)) {
3217  LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
3218  node.GetId(), stop_hash.ToString());
3219  node.fDisconnect = true;
3220  return false;
3221  }
3222  }
3223 
3224  uint32_t stop_height = stop_index->nHeight;
3225  if (start_height > stop_height) {
3226  LogPrint(BCLog::NET, "peer %d sent invalid getcfilters/getcfheaders with "
3227  "start height %d and stop height %d\n",
3228  node.GetId(), start_height, stop_height);
3229  node.fDisconnect = true;
3230  return false;
3231  }
3232  if (stop_height - start_height >= max_height_diff) {
3233  LogPrint(BCLog::NET, "peer %d requested too many cfilters/cfheaders: %d / %d\n",
3234  node.GetId(), stop_height - start_height + 1, max_height_diff);
3235  node.fDisconnect = true;
3236  return false;
3237  }
3238 
3239  filter_index = GetBlockFilterIndex(filter_type);
3240  if (!filter_index) {
3241  LogPrint(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type));
3242  return false;
3243  }
3244 
3245  return true;
3246 }
3247 
3248 void PeerManagerImpl::ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv)
3249 {
3250  uint8_t filter_type_ser;
3251  uint32_t start_height;
3252  uint256 stop_hash;
3253 
3254  vRecv >> filter_type_ser >> start_height >> stop_hash;
3255 
3256  const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3257 
3258  const CBlockIndex* stop_index;
3259  BlockFilterIndex* filter_index;
3260  if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
3261  MAX_GETCFILTERS_SIZE, stop_index, filter_index)) {
3262  return;
3263  }
3264 
3265  std::vector<BlockFilter> filters;
3266  if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
3267  LogPrint(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
3268  BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
3269  return;
3270  }
3271 
3272  for (const auto& filter : filters) {
3273  MakeAndPushMessage(node, NetMsgType::CFILTER, filter);
3274  }
3275 }
3276 
3277 void PeerManagerImpl::ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv)
3278 {
3279  uint8_t filter_type_ser;
3280  uint32_t start_height;
3281  uint256 stop_hash;
3282 
3283  vRecv >> filter_type_ser >> start_height >> stop_hash;
3284 
3285  const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3286 
3287  const CBlockIndex* stop_index;
3288  BlockFilterIndex* filter_index;
3289  if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash,
3290  MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) {
3291  return;
3292  }
3293 
3294  uint256 prev_header;
3295  if (start_height > 0) {
3296  const CBlockIndex* const prev_block =
3297  stop_index->GetAncestor(static_cast<int>(start_height - 1));
3298  if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
3299  LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
3300  BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString());
3301  return;
3302  }
3303  }
3304 
3305  std::vector<uint256> filter_hashes;
3306  if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) {
3307  LogPrint(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
3308  BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
3309  return;
3310  }
3311 
3312  MakeAndPushMessage(node, NetMsgType::CFHEADERS,
3313  filter_type_ser,
3314  stop_index->GetBlockHash(),
3315  prev_header,
3316  filter_hashes);
3317 }
3318 
3319 void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv)
3320 {
3321  uint8_t filter_type_ser;
3322  uint256 stop_hash;
3323 
3324  vRecv >> filter_type_ser >> stop_hash;
3325 
3326  const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
3327 
3328  const CBlockIndex* stop_index;
3329  BlockFilterIndex* filter_index;
3330  if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash,
3331  /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
3332  stop_index, filter_index)) {
3333  return;
3334  }
3335 
3336  std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
3337 
3338  // Populate headers.
3339  const CBlockIndex* block_index = stop_index;
3340  for (int i = headers.size() - 1; i >= 0; i--) {
3341  int height = (i + 1) * CFCHECKPT_INTERVAL;
3342  block_index = block_index->GetAncestor(height);
3343 
3344  if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
3345  LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
3346  BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());
3347  return;
3348  }
3349  }
3350 
3351  MakeAndPushMessage(node, NetMsgType::CFCHECKPT,
3352  filter_type_ser,
3353  stop_index->GetBlockHash(),
3354  headers);
3355 }
3356 
3357 void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)
3358 {
3359  bool new_block{false};
3360  m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block);
3361  if (new_block) {
3362  node.m_last_block_time = GetTime<std::chrono::seconds>();
3363  // In case this block came from a different peer than we requested
3364  // from, we can erase the block request now anyway (as we just stored
3365  // this block to disk).
3366  LOCK(cs_main);
3367  RemoveBlockRequest(block->GetHash(), std::nullopt);
3368  } else {
3369  LOCK(cs_main);
3370  mapBlockSource.erase(block->GetHash());
3371  }
3372 }
3373 
3374 void PeerManagerImpl::ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions)
3375 {
3376  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3377  bool fBlockRead{false};
3378  {
3379  LOCK(cs_main);
3380 
3381  auto range_flight = mapBlocksInFlight.equal_range(block_transactions.blockhash);
3382  size_t already_in_flight = std::distance(range_flight.first, range_flight.second);
3383  bool requested_block_from_this_peer{false};
3384 
3385  // Multimap ensures ordering of outstanding requests. It's either empty or first in line.
3386  bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId());
3387 
3388  while (range_flight.first != range_flight.second) {
3389  auto [node_id, block_it] = range_flight.first->second;
3390  if (node_id == pfrom.GetId() && block_it->partialBlock) {
3391  requested_block_from_this_peer = true;
3392  break;
3393  }
3394  range_flight.first++;
3395  }
3396 
3397  if (!requested_block_from_this_peer) {
3398  LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId());
3399  return;
3400  }
3401 
3402  PartiallyDownloadedBlock& partialBlock = *range_flight.first->second.second->partialBlock;
3403  ReadStatus status = partialBlock.FillBlock(*pblock, block_transactions.txn);
3404  if (status == READ_STATUS_INVALID) {
3405  RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect
3406  Misbehaving(peer, 100, "invalid compact block/non-matching block transactions");
3407  return;
3408  } else if (status == READ_STATUS_FAILED) {
3409  if (first_in_flight) {
3410  // Might have collided, fall back to getdata now :(
3411  std::vector<CInv> invs;
3412  invs.emplace_back(MSG_BLOCK | GetFetchFlags(peer), block_transactions.blockhash);
3413  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, invs);
3414  } else {
3415  RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId());
3416  LogPrint(BCLog::NET, "Peer %d sent us a compact block but it failed to reconstruct, waiting on first download to complete\n", pfrom.GetId());
3417  return;
3418  }
3419  } else {
3420  // Block is either okay, or possibly we received
3421  // READ_STATUS_CHECKBLOCK_FAILED.
3422  // Note that CheckBlock can only fail for one of a few reasons:
3423  // 1. bad-proof-of-work (impossible here, because we've already
3424  // accepted the header)
3425  // 2. merkleroot doesn't match the transactions given (already
3426  // caught in FillBlock with READ_STATUS_FAILED, so
3427  // impossible here)
3428  // 3. the block is otherwise invalid (eg invalid coinbase,
3429  // block is too big, too many legacy sigops, etc).
3430  // So if CheckBlock failed, #3 is the only possibility.
3431  // Under BIP 152, we don't discourage the peer unless proof of work is
3432  // invalid (we don't require all the stateless checks to have
3433  // been run). This is handled below, so just treat this as
3434  // though the block was successfully read, and rely on the
3435  // handling in ProcessNewBlock to ensure the block index is
3436  // updated, etc.
3437  RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // it is now an empty pointer
3438  fBlockRead = true;
3439  // mapBlockSource is used for potentially punishing peers and
3440  // updating which peers send us compact blocks, so the race
3441  // between here and cs_main in ProcessNewBlock is fine.
3442  // BIP 152 permits peers to relay compact blocks after validating
3443  // the header only; we should not punish peers if the block turns
3444  // out to be invalid.
3445  mapBlockSource.emplace(block_transactions.blockhash, std::make_pair(pfrom.GetId(), false));
3446  }
3447  } // Don't hold cs_main when we call into ProcessNewBlock
3448  if (fBlockRead) {
3449  // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
3450  // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
3451  // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
3452  // disk-space attacks), but this should be safe due to the
3453  // protections in the compact block handler -- see related comment
3454  // in compact block optimistic reconstruction handling.
3455  ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
3456  }
3457  return;
3458 }
3459 
3460 void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv,
3461  const std::chrono::microseconds time_received,
3462  const std::atomic<bool>& interruptMsgProc)
3463 {
3464  AssertLockHeld(g_msgproc_mutex);
3465 
3466  LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
3467 
3468  PeerRef peer = GetPeerRef(pfrom.GetId());
3469  if (peer == nullptr) return;
3470 
3471  if (msg_type == NetMsgType::VERSION) {
3472  if (pfrom.nVersion != 0) {
3473  LogPrint(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId());
3474  return;
3475  }
3476 
3477  int64_t nTime;
3478  CService addrMe;
3479  uint64_t nNonce = 1;
3480  ServiceFlags nServices;
3481  int nVersion;
3482  std::string cleanSubVer;
3483  int starting_height = -1;
3484  bool fRelay = true;
3485 
3486  vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
3487  if (nTime < 0) {
3488  nTime = 0;
3489  }
3490  vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer
3491  vRecv >> CNetAddr::V1(addrMe);
3492  if (!pfrom.IsInboundConn())
3493  {
3494  // Overwrites potentially existing services. In contrast to this,
3495  // unvalidated services received via gossip relay in ADDR/ADDRV2
3496  // messages are only ever added but cannot replace existing ones.
3497  m_addrman.SetServices(pfrom.addr, nServices);
3498  }
3499  if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices))
3500  {
3501  LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom.GetId(), nServices, GetDesirableServiceFlags(nServices));
3502  pfrom.fDisconnect = true;
3503  return;
3504  }
3505 
3506  if (nVersion < MIN_PEER_PROTO_VERSION) {
3507  // disconnect from peers older than this proto version
3508  LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom.GetId(), nVersion);
3509  pfrom.fDisconnect = true;
3510  return;
3511  }
3512 
3513  if (!vRecv.empty()) {
3514  // The version message includes information about the sending node which we don't use:
3515  // - 8 bytes (service bits)
3516  // - 16 bytes (ipv6 address)
3517  // - 2 bytes (port)
3518  vRecv.ignore(26);
3519  vRecv >> nNonce;
3520  }
3521  if (!vRecv.empty()) {
3522  std::string strSubVer;
3523  vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
3524  cleanSubVer = SanitizeString(strSubVer);
3525  }
3526  if (!vRecv.empty()) {
3527  vRecv >> starting_height;
3528  }
3529  if (!vRecv.empty())
3530  vRecv >> fRelay;
3531  // Disconnect if we connected to ourself
3532  if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce))
3533  {
3534  LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToStringAddrPort());
3535  pfrom.fDisconnect = true;
3536  return;
3537  }
3538 
3539  if (pfrom.IsInboundConn() && addrMe.IsRoutable())
3540  {
3541  SeenLocal(addrMe);
3542  }
3543 
3544  // Inbound peers send us their version message when they connect.
3545  // We send our version message in response.
3546  if (pfrom.IsInboundConn()) {
3547  PushNodeVersion(pfrom, *peer);
3548  }
3549 
3550  // Change version
3551  const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION);
3552  pfrom.SetCommonVersion(greatest_common_version);
3553  pfrom.nVersion = nVersion;
3554 
3555  if (greatest_common_version >= WTXID_RELAY_VERSION) {
3556  MakeAndPushMessage(pfrom, NetMsgType::WTXIDRELAY);
3557  }
3558 
3559  // Signal ADDRv2 support (BIP155).
3560  if (greatest_common_version >= 70016) {
3561  // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some
3562  // implementations reject messages they don't know. As a courtesy, don't send
3563  // it to nodes with a version before 70016, as no software is known to support
3564  // BIP155 that doesn't announce at least that protocol version number.
3565  MakeAndPushMessage(pfrom, NetMsgType::SENDADDRV2);
3566  }
3567 
3568  pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices);
3569  peer->m_their_services = nServices;
3570  pfrom.SetAddrLocal(addrMe);
3571  {
3572  LOCK(pfrom.m_subver_mutex);
3573  pfrom.cleanSubVer = cleanSubVer;
3574  }
3575  peer->m_starting_height = starting_height;
3576 
3577  // Only initialize the Peer::TxRelay m_relay_txs data structure if:
3578  // - this isn't an outbound block-relay-only connection, and
3579  // - this isn't an outbound feeler connection, and
3580  // - fRelay=true (the peer wishes to receive transaction announcements)
3581  // or we're offering NODE_BLOOM to this peer. NODE_BLOOM means that
3582  // the peer may turn on transaction relay later.
3583  if (!pfrom.IsBlockOnlyConn() &&
3584  !pfrom.IsFeelerConn() &&
3585  (fRelay || (peer->m_our_services & NODE_BLOOM))) {
3586  auto* const tx_relay = peer->SetTxRelay();
3587  {
3588  LOCK(tx_relay->m_bloom_filter_mutex);
3589  tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message
3590  }
3591  if (fRelay) pfrom.m_relays_txs = true;
3592  }
3593 
3594  if (greatest_common_version >= WTXID_RELAY_VERSION && m_txreconciliation) {
3595  // Per BIP-330, we announce txreconciliation support if:
3596  // - protocol version per the peer's VERSION message supports WTXID_RELAY;
3597  // - transaction relay is supported per the peer's VERSION message
3598  // - this is not a block-relay-only connection and not a feeler
3599  // - this is not an addr fetch connection;
3600  // - we are not in -blocksonly mode.
3601  const auto* tx_relay = peer->GetTxRelay();
3602  if (tx_relay && WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs) &&
3603  !pfrom.IsAddrFetchConn() && !m_opts.ignore_incoming_txs) {
3604  const uint64_t recon_salt = m_txreconciliation->PreRegisterPeer(pfrom.GetId());
3605  MakeAndPushMessage(pfrom, NetMsgType::SENDTXRCNCL,
3606  TXRECONCILIATION_VERSION, recon_salt);
3607  }
3608  }
3609 
3610  MakeAndPushMessage(pfrom, NetMsgType::VERACK);
3611 
3612  // Potentially mark this peer as a preferred download peer.
3613  {
3614  LOCK(cs_main);
3615  CNodeState* state = State(pfrom.GetId());
3616  state->fPreferredDownload = (!pfrom.IsInboundConn() || pfrom.HasPermission(NetPermissionFlags::NoBan)) && !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer);
3617  m_num_preferred_download_peers += state->fPreferredDownload;
3618  }
3619 
3620  // Attempt to initialize address relay for outbound peers and use result
3621  // to decide whether to send GETADDR, so that we don't send it to
3622  // inbound or outbound block-relay-only peers.
3623  bool send_getaddr{false};
3624  if (!pfrom.IsInboundConn()) {
3625  send_getaddr = SetupAddressRelay(pfrom, *peer);
3626  }
3627  if (send_getaddr) {
3628  // Do a one-time address fetch to help populate/update our addrman.
3629  // If we're starting up for the first time, our addrman may be pretty
3630  // empty, so this mechanism is important to help us connect to the network.
3631  // We skip this for block-relay-only peers. We want to avoid
3632  // potentially leaking addr information and we do not want to
3633  // indicate to the peer that we will participate in addr relay.
3634  MakeAndPushMessage(pfrom, NetMsgType::GETADDR);
3635  peer->m_getaddr_sent = true;
3636  // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response
3637  // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
3638  peer->m_addr_token_bucket += MAX_ADDR_TO_SEND;
3639  }
3640 
3641  if (!pfrom.IsInboundConn()) {
3642  // For non-inbound connections, we update the addrman to record
3643  // connection success so that addrman will have an up-to-date
3644  // notion of which peers are online and available.
3645  //
3646  // While we strive to not leak information about block-relay-only
3647  // connections via the addrman, not moving an address to the tried
3648  // table is also potentially detrimental because new-table entries
3649  // are subject to eviction in the event of addrman collisions. We
3650  // mitigate the information-leak by never calling
3651  // AddrMan::Connected() on block-relay-only peers; see
3652  // FinalizeNode().
3653  //
3654  // This moves an address from New to Tried table in Addrman,
3655  // resolves tried-table collisions, etc.
3656  m_addrman.Good(pfrom.addr);
3657  }
3658 
3659  std::string remoteAddr;
3660  if (fLogIPs)
3661  remoteAddr = ", peeraddr=" + pfrom.addr.ToStringAddrPort();
3662 
3663  const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)};
3664  LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s%s\n",
3665  cleanSubVer, pfrom.nVersion,
3666  peer->m_starting_height, addrMe.ToStringAddrPort(), fRelay, pfrom.GetId(),
3667  remoteAddr, (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : ""));
3668 
3669  int64_t nTimeOffset = nTime - GetTime();
3670  pfrom.nTimeOffset = nTimeOffset;
3671  if (!pfrom.IsInboundConn()) {
3672  // Don't use timedata samples from inbound peers to make it
3673  // harder for others to tamper with our adjusted time.
3674  AddTimeData(pfrom.addr, nTimeOffset);
3675  }
3676 
3677  // If the peer is old enough to have the old alert system, send it the final alert.
3678  if (greatest_common_version <= 70012) {
3679  const auto finalAlert{ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50")};
3680  MakeAndPushMessage(pfrom, "alert", Span{finalAlert});
3681  }
3682 
3683  // Feeler connections exist only to verify if address is online.
3684  if (pfrom.IsFeelerConn()) {
3685  LogPrint(BCLog::NET, "feeler connection completed peer=%d; disconnecting\n", pfrom.GetId());
3686  pfrom.fDisconnect = true;
3687  }
3688  return;
3689  }
3690 
3691  if (pfrom.nVersion == 0) {
3692  // Must have a version message before anything else
3693  LogPrint(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
3694  return;
3695  }
3696 
3697  if (msg_type == NetMsgType::VERACK) {
3698  if (pfrom.fSuccessfullyConnected) {
3699  LogPrint(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId());
3700  return;
3701  }
3702 
3703  // Log successful connections unconditionally for outbound, but not for inbound as those
3704  // can be triggered by an attacker at high rate.
3706  const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)};
3707  LogPrintf("New %s %s peer connected: version: %d, blocks=%d, peer=%d%s%s\n",
3708  pfrom.ConnectionTypeAsString(),
3709  TransportTypeAsString(pfrom.m_transport->GetInfo().transport_type),
3710  pfrom.nVersion.load(), peer->m_starting_height,
3711  pfrom.GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToStringAddrPort()) : ""),
3712  (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : ""));
3713  }
3714 
3715  if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) {
3716  // Tell our peer we are willing to provide version 2 cmpctblocks.
3717  // However, we do not request new block announcements using
3718  // cmpctblock messages.
3719  // We send this to non-NODE NETWORK peers as well, because
3720  // they may wish to request compact blocks from us
3721  MakeAndPushMessage(pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION);
3722  }
3723 
3724  if (m_txreconciliation) {
3725  if (!peer->m_wtxid_relay || !m_txreconciliation->IsPeerRegistered(pfrom.GetId())) {
3726  // We could have optimistically pre-registered/registered the peer. In that case,
3727  // we should forget about the reconciliation state here if this wasn't followed
3728  // by WTXIDRELAY (since WTXIDRELAY can't be announced later).
3729  m_txreconciliation->ForgetPeer(pfrom.GetId());
3730  }
3731  }
3732 
3733  if (auto tx_relay = peer->GetTxRelay()) {
3734  // `TxRelay::m_tx_inventory_to_send` must be empty before the
3735  // version handshake is completed as
3736  // `TxRelay::m_next_inv_send_time` is first initialised in
3737  // `SendMessages` after the verack is received. Any transactions
3738  // received during the version handshake would otherwise
3739  // immediately be advertised without random delay, potentially
3740  // leaking the time of arrival to a spy.
3741  Assume(WITH_LOCK(
3742  tx_relay->m_tx_inventory_mutex,
3743  return tx_relay->m_tx_inventory_to_send.empty() &&
3744  tx_relay->m_next_inv_send_time == 0s));
3745  }
3746 
3747  pfrom.fSuccessfullyConnected = true;
3748  return;
3749  }
3750 
3751  if (msg_type == NetMsgType::SENDHEADERS) {
3752  peer->m_prefers_headers = true;
3753  return;
3754  }
3755 
3756  if (msg_type == NetMsgType::SENDCMPCT) {
3757  bool sendcmpct_hb{false};
3758  uint64_t sendcmpct_version{0};
3759  vRecv >> sendcmpct_hb >> sendcmpct_version;
3760 
3761  // Only support compact block relay with witnesses
3762  if (sendcmpct_version != CMPCTBLOCKS_VERSION) return;
3763 
3764  LOCK(cs_main);
3765  CNodeState* nodestate = State(pfrom.GetId());
3766  nodestate->m_provides_cmpctblocks = true;
3767  nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
3768  // save whether peer selects us as BIP152 high-bandwidth peer
3769  // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth)
3770  pfrom.m_bip152_highbandwidth_from = sendcmpct_hb;
3771  return;
3772  }
3773 
3774  // BIP339 defines feature negotiation of wtxidrelay, which must happen between
3775  // VERSION and VERACK to avoid relay problems from switching after a connection is up.
3776  if (msg_type == NetMsgType::WTXIDRELAY) {
3777  if (pfrom.fSuccessfullyConnected) {
3778  // Disconnect peers that send a wtxidrelay message after VERACK.
3779  LogPrint(BCLog::NET, "wtxidrelay received after verack from peer=%d; disconnecting\n", pfrom.GetId());
3780  pfrom.fDisconnect = true;
3781  return;
3782  }
3783  if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) {
3784  if (!peer->m_wtxid_relay) {
3785  peer->m_wtxid_relay = true;
3786  m_wtxid_relay_peers++;
3787  } else {
3788  LogPrint(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId());
3789  }
3790  } else {
3791  LogPrint(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId());
3792  }
3793  return;
3794  }
3795 
3796  // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen
3797  // between VERSION and VERACK.
3798  if (msg_type == NetMsgType::SENDADDRV2) {
3799  if (pfrom.fSuccessfullyConnected) {
3800  // Disconnect peers that send a SENDADDRV2 message after VERACK.
3801  LogPrint(BCLog::NET, "sendaddrv2 received after verack from peer=%d; disconnecting\n", pfrom.GetId());
3802  pfrom.fDisconnect = true;
3803  return;
3804  }
3805  peer->m_wants_addrv2 = true;
3806  return;
3807  }
3808 
3809  // Received from a peer demonstrating readiness to announce transactions via reconciliations.
3810  // This feature negotiation must happen between VERSION and VERACK to avoid relay problems
3811  // from switching announcement protocols after the connection is up.
3812  if (msg_type == NetMsgType::SENDTXRCNCL) {
3813  if (!m_txreconciliation) {
3814  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl from peer=%d ignored, as our node does not have txreconciliation enabled\n", pfrom.GetId());
3815  return;
3816  }
3817 
3818  if (pfrom.fSuccessfullyConnected) {
3819  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received after verack from peer=%d; disconnecting\n", pfrom.GetId());
3820  pfrom.fDisconnect = true;
3821  return;
3822  }
3823 
3824  // Peer must not offer us reconciliations if we specified no tx relay support in VERSION.
3825  if (RejectIncomingTxs(pfrom)) {
3826  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received from peer=%d to which we indicated no tx relay; disconnecting\n", pfrom.GetId());
3827  pfrom.fDisconnect = true;
3828  return;
3829  }
3830 
3831  // Peer must not offer us reconciliations if they specified no tx relay support in VERSION.
3832  // This flag might also be false in other cases, but the RejectIncomingTxs check above
3833  // eliminates them, so that this flag fully represents what we are looking for.
3834  const auto* tx_relay = peer->GetTxRelay();
3835  if (!tx_relay || !WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs)) {
3836  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received from peer=%d which indicated no tx relay to us; disconnecting\n", pfrom.GetId());
3837  pfrom.fDisconnect = true;
3838  return;
3839  }
3840 
3841  uint32_t peer_txreconcl_version;
3842  uint64_t remote_salt;
3843  vRecv >> peer_txreconcl_version >> remote_salt;
3844 
3845  const ReconciliationRegisterResult result = m_txreconciliation->RegisterPeer(pfrom.GetId(), pfrom.IsInboundConn(),
3846  peer_txreconcl_version, remote_salt);
3847  switch (result) {
3849  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "Ignore unexpected txreconciliation signal from peer=%d\n", pfrom.GetId());
3850  break;
3852  break;
3854  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "txreconciliation protocol violation from peer=%d (sendtxrcncl received from already registered peer); disconnecting\n", pfrom.GetId());
3855  pfrom.fDisconnect = true;
3856  return;
3858  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "txreconciliation protocol violation from peer=%d; disconnecting\n", pfrom.GetId());
3859  pfrom.fDisconnect = true;
3860  return;
3861  }
3862  return;
3863  }
3864 
3865  if (!pfrom.fSuccessfullyConnected) {
3866  LogPrint(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
3867  return;
3868  }
3869 
3870  if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
3871  const auto ser_params{
3872  msg_type == NetMsgType::ADDRV2 ?
3873  // Set V2 param so that the CNetAddr and CAddress
3874  // unserialize methods know that an address in v2 format is coming.
3877  };
3878 
3879  std::vector<CAddress> vAddr;
3880 
3881  vRecv >> ser_params(vAddr);
3882 
3883  if (!SetupAddressRelay(pfrom, *peer)) {
3884  LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
3885  return;
3886  }
3887 
3888  if (vAddr.size() > MAX_ADDR_TO_SEND)
3889  {
3890  Misbehaving(*peer, 20, strprintf("%s message size = %u", msg_type, vAddr.size()));
3891  return;
3892  }
3893 
3894  // Store the new addresses
3895  std::vector<CAddress> vAddrOk;
3896  const auto current_a_time{Now<NodeSeconds>()};
3897 
3898  // Update/increment addr rate limiting bucket.
3899  const auto current_time{GetTime<std::chrono::microseconds>()};
3900  if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
3901  // Don't increment bucket if it's already full
3902  const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us);
3903  const double increment = Ticks<SecondsDouble>(time_diff) * MAX_ADDR_RATE_PER_SECOND;
3904  peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET);
3905  }
3906  peer->m_addr_token_timestamp = current_time;
3907 
3908  const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr);
3909  uint64_t num_proc = 0;
3910  uint64_t num_rate_limit = 0;
3911  Shuffle(vAddr.begin(), vAddr.end(), m_rng);
3912  for (CAddress& addr : vAddr)
3913  {
3914  if (interruptMsgProc)
3915  return;
3916 
3917  // Apply rate limiting.
3918  if (peer->m_addr_token_bucket < 1.0) {
3919  if (rate_limited) {
3920  ++num_rate_limit;
3921  continue;
3922  }
3923  } else {
3924  peer->m_addr_token_bucket -= 1.0;
3925  }
3926  // We only bother storing full nodes, though this may include
3927  // things which we would not make an outbound connection to, in
3928  // part because we may make feeler connections to them.
3929  if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices))
3930  continue;
3931 
3932  if (addr.nTime <= NodeSeconds{100000000s} || addr.nTime > current_a_time + 10min) {
3933  addr.nTime = current_a_time - 5 * 24h;
3934  }
3935  AddAddressKnown(*peer, addr);
3936  if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
3937  // Do not process banned/discouraged addresses beyond remembering we received them
3938  continue;
3939  }
3940  ++num_proc;
3941  const bool reachable{g_reachable_nets.Contains(addr)};
3942  if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) {
3943  // Relay to a limited number of other nodes
3944  RelayAddress(pfrom.GetId(), addr, reachable);
3945  }
3946  // Do not store addresses outside our network
3947  if (reachable) {
3948  vAddrOk.push_back(addr);
3949  }
3950  }
3951  peer->m_addr_processed += num_proc;
3952  peer->m_addr_rate_limited += num_rate_limit;
3953  LogPrint(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n",
3954  vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
3955 
3956  m_addrman.Add(vAddrOk, pfrom.addr, 2h);
3957  if (vAddr.size() < 1000) peer->m_getaddr_sent = false;
3958 
3959  // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements
3960  if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
3961  LogPrint(BCLog::NET, "addrfetch connection completed peer=%d; disconnecting\n", pfrom.GetId());
3962  pfrom.fDisconnect = true;
3963  }
3964  return;
3965  }
3966 
3967  if (msg_type == NetMsgType::INV) {
3968  std::vector<CInv> vInv;
3969  vRecv >> vInv;
3970  if (vInv.size() > MAX_INV_SZ)
3971  {
3972  Misbehaving(*peer, 20, strprintf("inv message size = %u", vInv.size()));
3973  return;
3974  }
3975 
3976  const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
3977 
3978  LOCK(cs_main);
3979 
3980  const auto current_time{GetTime<std::chrono::microseconds>()};
3981  uint256* best_block{nullptr};
3982 
3983  for (CInv& inv : vInv) {
3984  if (interruptMsgProc) return;
3985 
3986  // Ignore INVs that don't match wtxidrelay setting.
3987  // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting.
3988  // This is fine as no INV messages are involved in that process.
3989  if (peer->m_wtxid_relay) {
3990  if (inv.IsMsgTx()) continue;
3991  } else {
3992  if (inv.IsMsgWtx()) continue;
3993  }
3994 
3995  if (inv.IsMsgBlk()) {
3996  const bool fAlreadyHave = AlreadyHaveBlock(inv.hash);
3997  LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
3998 
3999  UpdateBlockAvailability(pfrom.GetId(), inv.hash);
4000  if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() && !IsBlockRequested(inv.hash)) {
4001  // Headers-first is the primary method of announcement on
4002  // the network. If a node fell back to sending blocks by
4003  // inv, it may be for a re-org, or because we haven't
4004  // completed initial headers sync. The final block hash
4005  // provided should be the highest, so send a getheaders and
4006  // then fetch the blocks we need to catch up.
4007  best_block = &inv.hash;
4008  }
4009  } else if (inv.IsGenTxMsg()) {
4010  if (reject_tx_invs) {
4011  LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId());
4012  pfrom.fDisconnect = true;
4013  return;
4014  }
4015  const GenTxid gtxid = ToGenTxid(inv);
4016  const bool fAlreadyHave = AlreadyHaveTx(gtxid);
4017  LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
4018 
4019  AddKnownTx(*peer, inv.hash);
4020  if (!fAlreadyHave && !m_chainman.IsInitialBlockDownload()) {
4021  AddTxAnnouncement(pfrom, gtxid, current_time);
4022  }
4023  } else {
4024  LogPrint(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId());
4025  }
4026  }
4027 
4028  if (best_block != nullptr) {
4029  // If we haven't started initial headers-sync with this peer, then
4030  // consider sending a getheaders now. On initial startup, there's a
4031  // reliability vs bandwidth tradeoff, where we are only trying to do
4032  // initial headers sync with one peer at a time, with a long
4033  // timeout (at which point, if the sync hasn't completed, we will
4034  // disconnect the peer and then choose another). In the meantime,
4035  // as new blocks are found, we are willing to add one new peer per
4036  // block to sync with as well, to sync quicker in the case where
4037  // our initial peer is unresponsive (but less bandwidth than we'd
4038  // use if we turned on sync with all peers).
4039  CNodeState& state{*Assert(State(pfrom.GetId()))};
4040  if (state.fSyncStarted || (!peer->m_inv_triggered_getheaders_before_sync && *best_block != m_last_block_inv_triggering_headers_sync)) {
4041  if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer)) {
4042  LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n",
4043  m_chainman.m_best_header->nHeight, best_block->ToString(),
4044  pfrom.GetId());
4045  }
4046  if (!state.fSyncStarted) {
4047  peer->m_inv_triggered_getheaders_before_sync = true;
4048  // Update the last block hash that triggered a new headers
4049  // sync, so that we don't turn on headers sync with more
4050  // than 1 new peer every new block.
4051  m_last_block_inv_triggering_headers_sync = *best_block;
4052  }
4053  }
4054  }
4055 
4056  return;
4057  }
4058 
4059  if (msg_type == NetMsgType::GETDATA) {
4060  std::vector<CInv> vInv;
4061  vRecv >> vInv;
4062  if (vInv.size() > MAX_INV_SZ)
4063  {
4064  Misbehaving(*peer, 20, strprintf("getdata message size = %u", vInv.size()));
4065  return;
4066  }
4067 
4068  LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId());
4069 
4070  if (vInv.size() > 0) {
4071  LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
4072  }
4073 
4074  {
4075  LOCK(peer->m_getdata_requests_mutex);
4076  peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end());
4077  ProcessGetData(pfrom, *peer, interruptMsgProc);
4078  }
4079 
4080  return;
4081  }
4082 
4083  if (msg_type == NetMsgType::GETBLOCKS) {
4084  CBlockLocator locator;
4085  uint256 hashStop;
4086  vRecv >> locator >> hashStop;
4087 
4088  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
4089  LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
4090  pfrom.fDisconnect = true;
4091  return;
4092  }
4093 
4094  // We might have announced the currently-being-connected tip using a
4095  // compact block, which resulted in the peer sending a getblocks
4096  // request, which we would otherwise respond to without the new block.
4097  // To avoid this situation we simply verify that we are on our best
4098  // known chain now. This is super overkill, but we handle it better
4099  // for getheaders requests, and there are no known nodes which support
4100  // compact blocks but still use getblocks to request blocks.
4101  {
4102  std::shared_ptr<const CBlock> a_recent_block;
4103  {
4104  LOCK(m_most_recent_block_mutex);
4105  a_recent_block = m_most_recent_block;
4106  }
4107  BlockValidationState state;
4108  if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
4109  LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
4110  }
4111  }
4112 
4113  LOCK(cs_main);
4114 
4115  // Find the last block the caller has in the main chain
4116  const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
4117 
4118  // Send the rest of the chain
4119  if (pindex)
4120  pindex = m_chainman.ActiveChain().Next(pindex);
4121  int nLimit = 500;
4122  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());
4123  for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
4124  {
4125  if (pindex->GetBlockHash() == hashStop)
4126  {
4127  LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4128  break;
4129  }
4130  // If pruning, don't inv blocks unless we have on disk and are likely to still have
4131  // for some reasonable time window (1 hour) that block relay might require.
4132  const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
4133  if (m_chainman.m_blockman.IsPruneMode() && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave)) {
4134  LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4135  break;
4136  }
4137  WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
4138  if (--nLimit <= 0) {
4139  // When this block is requested, we'll send an inv that'll
4140  // trigger the peer to getblocks the next batch of inventory.
4141  LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4142  WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();});
4143  break;
4144  }
4145  }
4146  return;
4147  }
4148 
4149  if (msg_type == NetMsgType::GETBLOCKTXN) {
4151  vRecv >> req;
4152 
4153  std::shared_ptr<const CBlock> recent_block;
4154  {
4155  LOCK(m_most_recent_block_mutex);
4156  if (m_most_recent_block_hash == req.blockhash)
4157  recent_block = m_most_recent_block;
4158  // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion
4159  }
4160  if (recent_block) {
4161  SendBlockTransactions(pfrom, *peer, *recent_block, req);
4162  return;
4163  }
4164 
4165  {
4166  LOCK(cs_main);
4167 
4168  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
4169  if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4170  LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId());
4171  return;
4172  }
4173 
4174  if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
4175  CBlock block;
4176  const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(block, *pindex)};
4177  assert(ret);
4178 
4179  SendBlockTransactions(pfrom, *peer, block, req);
4180  return;
4181  }
4182  }
4183 
4184  // If an older block is requested (should never happen in practice,
4185  // but can happen in tests) send a block response instead of a
4186  // blocktxn response. Sending a full block response instead of a
4187  // small blocktxn response is preferable in the case where a peer
4188  // might maliciously send lots of getblocktxn requests to trigger
4189  // expensive disk reads, because it will require the peer to
4190  // actually receive all the data read from disk over the network.
4191  LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
4192  CInv inv{MSG_WITNESS_BLOCK, req.blockhash};
4193  WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv));
4194  // The message processing loop will go around again (without pausing) and we'll respond then
4195  return;
4196  }
4197 
4198  if (msg_type == NetMsgType::GETHEADERS) {
4199  CBlockLocator locator;
4200  uint256 hashStop;
4201  vRecv >> locator >> hashStop;
4202 
4203  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
4204  LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
4205  pfrom.fDisconnect = true;
4206  return;
4207  }
4208 
4209  if (m_chainman.m_blockman.LoadingBlocks()) {
4210  LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId());
4211  return;
4212  }
4213 
4214  LOCK(cs_main);
4215 
4216  // Note that if we were to be on a chain that forks from the checkpointed
4217  // chain, then serving those headers to a peer that has seen the
4218  // checkpointed chain would cause that peer to disconnect us. Requiring
4219  // that our chainwork exceed the minimum chain work is a protection against
4220  // being fed a bogus chain when we started up for the first time and
4221  // getting partitioned off the honest network for serving that chain to
4222  // others.
4223  if (m_chainman.ActiveTip() == nullptr ||
4224  (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && !pfrom.HasPermission(NetPermissionFlags::Download))) {
4225  LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId());
4226  // Just respond with an empty headers message, to tell the peer to
4227  // go away but not treat us as unresponsive.
4228  MakeAndPushMessage(pfrom, NetMsgType::HEADERS, std::vector<CBlockHeader>());
4229  return;
4230  }
4231 
4232  CNodeState *nodestate = State(pfrom.GetId());
4233  const CBlockIndex* pindex = nullptr;
4234  if (locator.IsNull())
4235  {
4236  // If locator is null, return the hashStop block
4237  pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
4238  if (!pindex) {
4239  return;
4240  }
4241 
4242  if (!BlockRequestAllowed(pindex)) {
4243  LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId());
4244  return;
4245  }
4246  }
4247  else
4248  {
4249  // Find the last block the caller has in the main chain
4250  pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
4251  if (pindex)
4252  pindex = m_chainman.ActiveChain().Next(pindex);
4253  }
4254 
4255  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4256  std::vector<CBlock> vHeaders;
4257  int nLimit = MAX_HEADERS_RESULTS;
4258  LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId());
4259  for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
4260  {
4261  vHeaders.emplace_back(pindex->GetBlockHeader());
4262  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4263  break;
4264  }
4265  // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR
4266  // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty
4267  // headers message). In both cases it's safe to update
4268  // pindexBestHeaderSent to be our tip.
4269  //
4270  // It is important that we simply reset the BestHeaderSent value here,
4271  // and not max(BestHeaderSent, newHeaderSent). We might have announced
4272  // the currently-being-connected tip using a compact block, which
4273  // resulted in the peer sending a headers request, which we respond to
4274  // without the new block. By resetting the BestHeaderSent, we ensure we
4275  // will re-announce the new block via headers (or compact blocks again)
4276  // in the SendMessages logic.
4277  nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip();
4278  MakeAndPushMessage(pfrom, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders));
4279  return;
4280  }
4281 
4282  if (msg_type == NetMsgType::TX) {
4283  if (RejectIncomingTxs(pfrom)) {
4284  LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom.GetId());
4285  pfrom.fDisconnect = true;
4286  return;
4287  }
4288 
4289  // Stop processing the transaction early if we are still in IBD since we don't
4290  // have enough information to validate it yet. Sending unsolicited transactions
4291  // is not considered a protocol violation, so don't punish the peer.
4292  if (m_chainman.IsInitialBlockDownload()) return;
4293 
4294  CTransactionRef ptx;
4295  vRecv >> TX_WITH_WITNESS(ptx);
4296  const CTransaction& tx = *ptx;
4297 
4298  const uint256& txid = ptx->GetHash();
4299  const uint256& wtxid = ptx->GetWitnessHash();
4300 
4301  const uint256& hash = peer->m_wtxid_relay ? wtxid : txid;
4302  AddKnownTx(*peer, hash);
4303 
4304  LOCK(cs_main);
4305 
4306  m_txrequest.ReceivedResponse(pfrom.GetId(), txid);
4307  if (tx.HasWitness()) m_txrequest.ReceivedResponse(pfrom.GetId(), wtxid);
4308 
4309  // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the
4310  // absence of witness malleation, this is strictly better, because the
4311  // recent rejects filter may contain the wtxid but rarely contains
4312  // the txid of a segwit transaction that has been rejected.
4313  // In the presence of witness malleation, it's possible that by only
4314  // doing the check with wtxid, we could overlook a transaction which
4315  // was confirmed with a different witness, or exists in our mempool
4316  // with a different witness, but this has limited downside:
4317  // mempool validation does its own lookup of whether we have the txid
4318  // already; and an adversary can already relay us old transactions
4319  // (older than our recency filter) if trying to DoS us, without any need
4320  // for witness malleation.
4321  if (AlreadyHaveTx(GenTxid::Wtxid(wtxid))) {
4323  // Always relay transactions received from peers with forcerelay
4324  // permission, even if they were already in the mempool, allowing
4325  // the node to function as a gateway for nodes hidden behind it.
4326  if (!m_mempool.exists(GenTxid::Txid(tx.GetHash()))) {
4327  LogPrintf("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n",
4328  tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId());
4329  } else {
4330  LogPrintf("Force relaying tx %s (wtxid=%s) from peer=%d\n",
4331  tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId());
4332  RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
4333  }
4334  }
4335  // If a tx is detected by m_recent_rejects it is ignored. Because we haven't
4336  // submitted the tx to our mempool, we won't have computed a DoS
4337  // score for it or determined exactly why we consider it invalid.
4338  //
4339  // This means we won't penalize any peer subsequently relaying a DoSy
4340  // tx (even if we penalized the first peer who gave it to us) because
4341  // we have to account for m_recent_rejects showing false positives. In
4342  // other words, we shouldn't penalize a peer if we aren't *sure* they
4343  // submitted a DoSy tx.
4344  //
4345  // Note that m_recent_rejects doesn't just record DoSy or invalid
4346  // transactions, but any tx not accepted by the mempool, which may be
4347  // due to node policy (vs. consensus). So we can't blanket penalize a
4348  // peer simply for relaying a tx that our m_recent_rejects has caught,
4349  // regardless of false positives.
4350  return;
4351  }
4352 
4353  const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx);
4354  const TxValidationState& state = result.m_state;
4355 
4357  ProcessValidTx(pfrom.GetId(), ptx, result.m_replaced_transactions.value());
4358  pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
4359  }
4361  {
4362  bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
4363 
4364  // Deduplicate parent txids, so that we don't have to loop over
4365  // the same parent txid more than once down below.
4366  std::vector<uint256> unique_parents;
4367  unique_parents.reserve(tx.vin.size());
4368  for (const CTxIn& txin : tx.vin) {
4369  // We start with all parents, and then remove duplicates below.
4370  unique_parents.push_back(txin.prevout.hash);
4371  }
4372  std::sort(unique_parents.begin(), unique_parents.end());
4373  unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end());
4374  for (const uint256& parent_txid : unique_parents) {
4375  if (m_recent_rejects.contains(parent_txid)) {
4376  fRejectedParents = true;
4377  break;
4378  }
4379  }
4380  if (!fRejectedParents) {
4381  const auto current_time{GetTime<std::chrono::microseconds>()};
4382 
4383  for (const uint256& parent_txid : unique_parents) {
4384  // Here, we only have the txid (and not wtxid) of the
4385  // inputs, so we only request in txid mode, even for
4386  // wtxidrelay peers.
4387  // Eventually we should replace this with an improved
4388  // protocol for getting all unconfirmed parents.
4389  const auto gtxid{GenTxid::Txid(parent_txid)};
4390  AddKnownTx(*peer, parent_txid);
4391  if (!AlreadyHaveTx(gtxid)) AddTxAnnouncement(pfrom, gtxid, current_time);
4392  }
4393 
4394  if (m_orphanage.AddTx(ptx, pfrom.GetId())) {
4395  AddToCompactExtraTransactions(ptx);
4396  }
4397 
4398  // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore.
4399  m_txrequest.ForgetTxHash(tx.GetHash());
4400  m_txrequest.ForgetTxHash(tx.GetWitnessHash());
4401 
4402  // DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789)
4403  m_orphanage.LimitOrphans(m_opts.max_orphan_txs, m_rng);
4404  } else {
4405  LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s (wtxid=%s)\n",
4406  tx.GetHash().ToString(),
4407  tx.GetWitnessHash().ToString());
4408  // We will continue to reject this tx since it has rejected
4409  // parents so avoid re-requesting it from other peers.
4410  // Here we add both the txid and the wtxid, as we know that
4411  // regardless of what witness is provided, we will not accept
4412  // this, so we don't need to allow for redownload of this txid
4413  // from any of our non-wtxidrelay peers.
4414  m_recent_rejects.insert(tx.GetHash().ToUint256());
4415  m_recent_rejects.insert(tx.GetWitnessHash().ToUint256());
4416  m_txrequest.ForgetTxHash(tx.GetHash());
4417  m_txrequest.ForgetTxHash(tx.GetWitnessHash());
4418  }
4419  }
4420  if (state.IsInvalid()) {
4421  ProcessInvalidTx(pfrom.GetId(), ptx, state, /*maybe_add_extra_compact_tx=*/true);
4422  }
4423  return;
4424  }
4425 
4426  if (msg_type == NetMsgType::CMPCTBLOCK)
4427  {
4428  // Ignore cmpctblock received while importing
4429  if (m_chainman.m_blockman.LoadingBlocks()) {
4430  LogPrint(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId());
4431  return;
4432  }
4433 
4434  CBlockHeaderAndShortTxIDs cmpctblock;
4435  vRecv >> cmpctblock;
4436 
4437  bool received_new_header = false;
4438  const auto blockhash = cmpctblock.header.GetHash();
4439 
4440  {
4441  LOCK(cs_main);
4442 
4443  const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock);
4444  if (!prev_block) {
4445  // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
4446  if (!m_chainman.IsInitialBlockDownload()) {
4447  MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer);
4448  }
4449  return;
4450  } else if (prev_block->nChainWork + CalculateClaimedHeadersWork({cmpctblock.header}) < GetAntiDoSWorkThreshold()) {
4451  // If we get a low-work header in a compact block, we can ignore it.
4452  LogPrint(BCLog::NET, "Ignoring low-work compact block from peer %d\n", pfrom.GetId());
4453  return;
4454  }
4455 
4456  if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) {
4457  received_new_header = true;
4458  }
4459  }
4460 
4461  const CBlockIndex *pindex = nullptr;
4462  BlockValidationState state;
4463  if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header}, /*min_pow_checked=*/true, state, &pindex)) {
4464  if (state.IsInvalid()) {
4465  MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block=*/true, "invalid header via cmpctblock");
4466  return;
4467  }
4468  }
4469 
4470  if (received_new_header) {
4471  LogInfo("Saw new cmpctblock header hash=%s peer=%d\n",
4472  blockhash.ToString(), pfrom.GetId());
4473  }
4474 
4475  bool fProcessBLOCKTXN = false;
4476 
4477  // If we end up treating this as a plain headers message, call that as well
4478  // without cs_main.
4479  bool fRevertToHeaderProcessing = false;
4480 
4481  // Keep a CBlock for "optimistic" compactblock reconstructions (see
4482  // below)
4483  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4484  bool fBlockReconstructed = false;
4485 
4486  {
4487  LOCK(cs_main);
4488  // If AcceptBlockHeader returned true, it set pindex
4489  assert(pindex);
4490  UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
4491 
4492  CNodeState *nodestate = State(pfrom.GetId());
4493 
4494  // If this was a new header with more work than our tip, update the
4495  // peer's last block announcement time
4496  if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
4497  nodestate->m_last_block_announcement = GetTime();
4498  }
4499 
4500  if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
4501  return;
4502 
4503  auto range_flight = mapBlocksInFlight.equal_range(pindex->GetBlockHash());
4504  size_t already_in_flight = std::distance(range_flight.first, range_flight.second);
4505  bool requested_block_from_this_peer{false};
4506 
4507  // Multimap ensures ordering of outstanding requests. It's either empty or first in line.
4508  bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId());
4509 
4510  while (range_flight.first != range_flight.second) {
4511  if (range_flight.first->second.first == pfrom.GetId()) {
4512  requested_block_from_this_peer = true;
4513  break;
4514  }
4515  range_flight.first++;
4516  }
4517 
4518  if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better
4519  pindex->nTx != 0) { // We had this block at some point, but pruned it
4520  if (requested_block_from_this_peer) {
4521  // We requested this block for some reason, but our mempool will probably be useless
4522  // so we just grab the block via normal getdata
4523  std::vector<CInv> vInv(1);
4524  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash);
4525  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4526  }
4527  return;
4528  }
4529 
4530  // If we're not close to tip yet, give up and let parallel block fetch work its magic
4531  if (!already_in_flight && !CanDirectFetch()) {
4532  return;
4533  }
4534 
4535  // We want to be a bit conservative just to be extra careful about DoS
4536  // possibilities in compact block processing...
4537  if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
4538  if ((already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK && nodestate->vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
4539  requested_block_from_this_peer) {
4540  std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
4541  if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) {
4542  if (!(*queuedBlockIt)->partialBlock)
4543  (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool));
4544  else {
4545  // The block was already in flight using compact blocks from the same peer
4546  LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
4547  return;
4548  }
4549  }
4550 
4551  PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
4552  ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
4553  if (status == READ_STATUS_INVALID) {
4554  RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect
4555  Misbehaving(*peer, 100, "invalid compact block");
4556  return;
4557  } else if (status == READ_STATUS_FAILED) {
4558  if (first_in_flight) {
4559  // Duplicate txindexes, the block is now in-flight, so just request it
4560  std::vector<CInv> vInv(1);
4561  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash);
4562  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4563  } else {
4564  // Give up for this peer and wait for other peer(s)
4565  RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId());
4566  }
4567  return;
4568  }
4569 
4571  for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
4572  if (!partialBlock.IsTxAvailable(i))
4573  req.indexes.push_back(i);
4574  }
4575  if (req.indexes.empty()) {
4576  fProcessBLOCKTXN = true;
4577  } else if (first_in_flight) {
4578  // We will try to round-trip any compact blocks we get on failure,
4579  // as long as it's first...
4580  req.blockhash = pindex->GetBlockHash();
4581  MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
4582  } else if (pfrom.m_bip152_highbandwidth_to &&
4583  (!pfrom.IsInboundConn() ||
4584  IsBlockRequestedFromOutbound(blockhash) ||
4585  already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK - 1)) {
4586  // ... or it's a hb relay peer and:
4587  // - peer is outbound, or
4588  // - we already have an outbound attempt in flight(so we'll take what we can get), or
4589  // - it's not the final parallel download slot (which we may reserve for first outbound)
4590  req.blockhash = pindex->GetBlockHash();
4591  MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
4592  } else {
4593  // Give up for this peer and wait for other peer(s)
4594  RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId());
4595  }
4596  } else {
4597  // This block is either already in flight from a different
4598  // peer, or this peer has too many blocks outstanding to
4599  // download from.
4600  // Optimistically try to reconstruct anyway since we might be
4601  // able to without any round trips.
4602  PartiallyDownloadedBlock tempBlock(&m_mempool);
4603  ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
4604  if (status != READ_STATUS_OK) {
4605  // TODO: don't ignore failures
4606  return;
4607  }
4608  std::vector<CTransactionRef> dummy;
4609  status = tempBlock.FillBlock(*pblock, dummy);
4610  if (status == READ_STATUS_OK) {
4611  fBlockReconstructed = true;
4612  }
4613  }
4614  } else {
4615  if (requested_block_from_this_peer) {
4616  // We requested this block, but its far into the future, so our
4617  // mempool will probably be useless - request the block normally
4618  std::vector<CInv> vInv(1);
4619  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash);
4620  MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
4621  return;
4622  } else {
4623  // If this was an announce-cmpctblock, we want the same treatment as a header message
4624  fRevertToHeaderProcessing = true;
4625  }
4626  }
4627  } // cs_main
4628 
4629  if (fProcessBLOCKTXN) {
4630  BlockTransactions txn;
4631  txn.blockhash = blockhash;
4632  return ProcessCompactBlockTxns(pfrom, *peer, txn);
4633  }
4634 
4635  if (fRevertToHeaderProcessing) {
4636  // Headers received from HB compact block peers are permitted to be
4637  // relayed before full validation (see BIP 152), so we don't want to disconnect
4638  // the peer if the header turns out to be for an invalid block.
4639  // Note that if a peer tries to build on an invalid chain, that
4640  // will be detected and the peer will be disconnected/discouraged.
4641  return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true);
4642  }
4643 
4644  if (fBlockReconstructed) {
4645  // If we got here, we were able to optimistically reconstruct a
4646  // block that is in flight from some other peer.
4647  {
4648  LOCK(cs_main);
4649  mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false));
4650  }
4651  // Setting force_processing to true means that we bypass some of
4652  // our anti-DoS protections in AcceptBlock, which filters
4653  // unrequested blocks that might be trying to waste our resources
4654  // (eg disk space). Because we only try to reconstruct blocks when
4655  // we're close to caught up (via the CanDirectFetch() requirement
4656  // above, combined with the behavior of not requesting blocks until
4657  // we have a chain with at least the minimum chain work), and we ignore
4658  // compact blocks with less work than our tip, it is safe to treat
4659  // reconstructed compact blocks as having been requested.
4660  ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true);
4661  LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
4662  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
4663  // Clear download state for this block, which is in
4664  // process from some other peer. We do this after calling
4665  // ProcessNewBlock so that a malleated cmpctblock announcement
4666  // can't be used to interfere with block relay.
4667  RemoveBlockRequest(pblock->GetHash(), std::nullopt);
4668  }
4669  }
4670  return;
4671  }
4672 
4673  if (msg_type == NetMsgType::BLOCKTXN)
4674  {
4675  // Ignore blocktxn received while importing
4676  if (m_chainman.m_blockman.LoadingBlocks()) {
4677  LogPrint(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId());
4678  return;
4679  }
4680 
4681  BlockTransactions resp;
4682  vRecv >> resp;
4683 
4684  return ProcessCompactBlockTxns(pfrom, *peer, resp);
4685  }
4686 
4687  if (msg_type == NetMsgType::HEADERS)
4688  {
4689  // Ignore headers received while importing
4690  if (m_chainman.m_blockman.LoadingBlocks()) {
4691  LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
4692  return;
4693  }
4694 
4695  // Assume that this is in response to any outstanding getheaders
4696  // request we may have sent, and clear out the time of our last request
4697  peer->m_last_getheaders_timestamp = {};
4698 
4699  std::vector<CBlockHeader> headers;
4700 
4701  // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4702  unsigned int nCount = ReadCompactSize(vRecv);
4703  if (nCount > MAX_HEADERS_RESULTS) {
4704  Misbehaving(*peer, 20, strprintf("headers message size = %u", nCount));
4705  return;
4706  }
4707  headers.resize(nCount);
4708  for (unsigned int n = 0; n < nCount; n++) {
4709  vRecv >> headers[n];
4710  ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4711  }
4712 
4713  ProcessHeadersMessage(pfrom, *peer, std::move(headers), /*via_compact_block=*/false);
4714 
4715  // Check if the headers presync progress needs to be reported to validation.
4716  // This needs to be done without holding the m_headers_presync_mutex lock.
4717  if (m_headers_presync_should_signal.exchange(false)) {
4718  HeadersPresyncStats stats;
4719  {
4720  LOCK(m_headers_presync_mutex);
4721  auto it = m_headers_presync_stats.find(m_headers_presync_bestpeer);
4722  if (it != m_headers_presync_stats.end()) stats = it->second;
4723  }
4724  if (stats.second) {
4725  m_chainman.ReportHeadersPresync(stats.first, stats.second->first, stats.second->second);
4726  }
4727  }
4728 
4729  return;
4730  }
4731 
4732  if (msg_type == NetMsgType::BLOCK)
4733  {
4734  // Ignore block received while importing
4735  if (m_chainman.m_blockman.LoadingBlocks()) {
4736  LogPrint(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId());
4737  return;
4738  }
4739 
4740  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4741  vRecv >> TX_WITH_WITNESS(*pblock);
4742 
4743  LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId());
4744 
4745  const CBlockIndex* prev_block{WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};
4746 
4747  // Check for possible mutation if it connects to something we know so we can check for DEPLOYMENT_SEGWIT being active
4748  if (prev_block && IsBlockMutated(/*block=*/*pblock,
4749  /*check_witness_root=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT))) {
4750  LogDebug(BCLog::NET, "Received mutated block from peer=%d\n", peer->m_id);
4751  Misbehaving(*peer, 100, "mutated block");
4752  WITH_LOCK(cs_main, RemoveBlockRequest(pblock->GetHash(), peer->m_id));
4753  return;
4754  }
4755 
4756  bool forceProcessing = false;
4757  const uint256 hash(pblock->GetHash());
4758  bool min_pow_checked = false;
4759  {
4760  LOCK(cs_main);
4761  // Always process the block if we requested it, since we may
4762  // need it even when it's not a candidate for a new best tip.
4763  forceProcessing = IsBlockRequested(hash);
4764  RemoveBlockRequest(hash, pfrom.GetId());
4765  // mapBlockSource is only used for punishing peers and setting
4766  // which peers send us compact blocks, so the race between here and
4767  // cs_main in ProcessNewBlock is fine.
4768  mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
4769 
4770  // Check claimed work on this block against our anti-dos thresholds.
4771  if (prev_block && prev_block->nChainWork + CalculateClaimedHeadersWork({pblock->GetBlockHeader()}) >= GetAntiDoSWorkThreshold()) {
4772  min_pow_checked = true;
4773  }
4774  }
4775  ProcessBlock(pfrom, pblock, forceProcessing, min_pow_checked);
4776  return;
4777  }
4778 
4779  if (msg_type == NetMsgType::GETADDR) {
4780  // This asymmetric behavior for inbound and outbound connections was introduced
4781  // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4782  // to users' AddrMan and later request them by sending getaddr messages.
4783  // Making nodes which are behind NAT and can only make outgoing connections ignore
4784  // the getaddr message mitigates the attack.
4785  if (!pfrom.IsInboundConn()) {
4786  LogPrint(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId());
4787  return;
4788  }
4789 
4790  // Since this must be an inbound connection, SetupAddressRelay will
4791  // never fail.
4792  Assume(SetupAddressRelay(pfrom, *peer));
4793 
4794  // Only send one GetAddr response per connection to reduce resource waste
4795  // and discourage addr stamping of INV announcements.
4796  if (peer->m_getaddr_recvd) {
4797  LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId());
4798  return;
4799  }
4800  peer->m_getaddr_recvd = true;
4801 
4802  peer->m_addrs_to_send.clear();
4803  std::vector<CAddress> vAddr;
4805  vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /*network=*/std::nullopt);
4806  } else {
4807  vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
4808  }
4809  for (const CAddress &addr : vAddr) {
4810  PushAddress(*peer, addr);
4811  }
4812  return;
4813  }
4814 
4815  if (msg_type == NetMsgType::MEMPOOL) {
4816  // Only process received mempool messages if we advertise NODE_BLOOM
4817  // or if the peer has mempool permissions.
4818  if (!(peer->m_our_services & NODE_BLOOM) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
4819  {
4821  {
4822  LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom.GetId());
4823  pfrom.fDisconnect = true;
4824  }
4825  return;
4826  }
4827 
4828  if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
4829  {
4831  {
4832  LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom.GetId());
4833  pfrom.fDisconnect = true;
4834  }
4835  return;
4836  }
4837 
4838  if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4839  LOCK(tx_relay->m_tx_inventory_mutex);
4840  tx_relay->m_send_mempool = true;
4841  }
4842  return;
4843  }
4844 
4845  if (msg_type == NetMsgType::PING) {
4846  if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
4847  uint64_t nonce = 0;
4848  vRecv >> nonce;
4849  // Echo the message back with the nonce. This allows for two useful features:
4850  //
4851  // 1) A remote node can quickly check if the connection is operational
4852  // 2) Remote nodes can measure the latency of the network thread. If this node
4853  // is overloaded it won't respond to pings quickly and the remote node can
4854  // avoid sending us more work, like chain download requests.
4855  //
4856  // The nonce stops the remote getting confused between different pings: without
4857  // it, if the remote node sends a ping once per second and this node takes 5
4858  // seconds to respond to each, the 5th ping the remote sends would appear to
4859  // return very quickly.
4860  MakeAndPushMessage(pfrom, NetMsgType::PONG, nonce);
4861  }
4862  return;
4863  }
4864 
4865  if (msg_type == NetMsgType::PONG) {
4866  const auto ping_end = time_received;
4867  uint64_t nonce = 0;
4868  size_t nAvail = vRecv.in_avail();
4869  bool bPingFinished = false;
4870  std::string sProblem;
4871 
4872  if (nAvail >= sizeof(nonce)) {
4873  vRecv >> nonce;
4874 
4875  // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4876  if (peer->m_ping_nonce_sent != 0) {
4877  if (nonce == peer->m_ping_nonce_sent) {
4878  // Matching pong received, this ping is no longer outstanding
4879  bPingFinished = true;
4880  const auto ping_time = ping_end - peer->m_ping_start.load();
4881  if (ping_time.count() >= 0) {
4882  // Let connman know about this successful ping-pong
4883  pfrom.PongReceived(ping_time);
4884  } else {
4885  // This should never happen
4886  sProblem = "Timing mishap";
4887  }
4888  } else {
4889  // Nonce mismatches are normal when pings are overlapping
4890  sProblem = "Nonce mismatch";
4891  if (nonce == 0) {
4892  // This is most likely a bug in another implementation somewhere; cancel this ping
4893  bPingFinished = true;
4894  sProblem = "Nonce zero";
4895  }
4896  }
4897  } else {
4898  sProblem = "Unsolicited pong without ping";
4899  }
4900  } else {
4901  // This is most likely a bug in another implementation somewhere; cancel this ping
4902  bPingFinished = true;
4903  sProblem = "Short payload";
4904  }
4905 
4906  if (!(sProblem.empty())) {
4907  LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
4908  pfrom.GetId(),
4909  sProblem,
4910  peer->m_ping_nonce_sent,
4911  nonce,
4912  nAvail);
4913  }
4914  if (bPingFinished) {
4915  peer->m_ping_nonce_sent = 0;
4916  }
4917  return;
4918  }
4919 
4920  if (msg_type == NetMsgType::FILTERLOAD) {
4921  if (!(peer->m_our_services & NODE_BLOOM)) {
4922  LogPrint(BCLog::NET, "filterload received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
4923  pfrom.fDisconnect = true;
4924  return;
4925  }
4926  CBloomFilter filter;
4927  vRecv >> filter;
4928 
4929  if (!filter.IsWithinSizeConstraints())
4930  {
4931  // There is no excuse for sending a too-large filter
4932  Misbehaving(*peer, 100, "too-large bloom filter");
4933  } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4934  {
4935  LOCK(tx_relay->m_bloom_filter_mutex);
4936  tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
4937  tx_relay->m_relay_txs = true;
4938  }
4939  pfrom.m_bloom_filter_loaded = true;
4940  pfrom.m_relays_txs = true;
4941  }
4942  return;
4943  }
4944 
4945  if (msg_type == NetMsgType::FILTERADD) {
4946  if (!(peer->m_our_services & NODE_BLOOM)) {
4947  LogPrint(BCLog::NET, "filteradd received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
4948  pfrom.fDisconnect = true;
4949  return;
4950  }
4951  std::vector<unsigned char> vData;
4952  vRecv >> vData;
4953 
4954  // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4955  // and thus, the maximum size any matched object can have) in a filteradd message
4956  bool bad = false;
4957  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
4958  bad = true;
4959  } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4960  LOCK(tx_relay->m_bloom_filter_mutex);
4961  if (tx_relay->m_bloom_filter) {
4962  tx_relay->m_bloom_filter->insert(vData);
4963  } else {
4964  bad = true;
4965  }
4966  }
4967  if (bad) {
4968  Misbehaving(*peer, 100, "bad filteradd message");
4969  }
4970  return;
4971  }
4972 
4973  if (msg_type == NetMsgType::FILTERCLEAR) {
4974  if (!(peer->m_our_services & NODE_BLOOM)) {
4975  LogPrint(BCLog::NET, "filterclear received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
4976  pfrom.fDisconnect = true;
4977  return;
4978  }
4979  auto tx_relay = peer->GetTxRelay();
4980  if (!tx_relay) return;
4981 
4982  {
4983  LOCK(tx_relay->m_bloom_filter_mutex);
4984  tx_relay->m_bloom_filter = nullptr;
4985  tx_relay->m_relay_txs = true;
4986  }
4987  pfrom.m_bloom_filter_loaded = false;
4988  pfrom.m_relays_txs = true;
4989  return;
4990  }
4991 
4992  if (msg_type == NetMsgType::FEEFILTER) {
4993  CAmount newFeeFilter = 0;
4994  vRecv >> newFeeFilter;
4995  if (MoneyRange(newFeeFilter)) {
4996  if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
4997  tx_relay->m_fee_filter_received = newFeeFilter;
4998  }
4999  LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
5000  }
5001  return;
5002  }
5003 
5004  if (msg_type == NetMsgType::GETCFILTERS) {
5005  ProcessGetCFilters(pfrom, *peer, vRecv);
5006  return;
5007  }
5008 
5009  if (msg_type == NetMsgType::GETCFHEADERS) {
5010  ProcessGetCFHeaders(pfrom, *peer, vRecv);
5011  return;
5012  }
5013 
5014  if (msg_type == NetMsgType::GETCFCHECKPT) {
5015  ProcessGetCFCheckPt(pfrom, *peer, vRecv);
5016  return;
5017  }
5018 
5019  if (msg_type == NetMsgType::NOTFOUND) {
5020  std::vector<CInv> vInv;
5021  vRecv >> vInv;
5023  LOCK(::cs_main);
5024  for (CInv &inv : vInv) {
5025  if (inv.IsGenTxMsg()) {
5026  // If we receive a NOTFOUND message for a tx we requested, mark the announcement for it as
5027  // completed in TxRequestTracker.
5028  m_txrequest.ReceivedResponse(pfrom.GetId(), inv.hash);
5029  }
5030  }
5031  }
5032  return;
5033  }
5034 
5035  // Ignore unknown commands for extensibility
5036  LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
5037  return;
5038 }
5039 
5040 bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer)
5041 {
5042  {
5043  LOCK(peer.m_misbehavior_mutex);
5044 
5045  // There's nothing to do if the m_should_discourage flag isn't set
5046  if (!peer.m_should_discourage) return false;
5047 
5048  peer.m_should_discourage = false;
5049  } // peer.m_misbehavior_mutex
5050 
5052  // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission
5053  LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id);
5054  return false;
5055  }
5056 
5057  if (pnode.IsManualConn()) {
5058  // We never disconnect or discourage manual peers for bad behavior
5059  LogPrintf("Warning: not punishing manually connected peer %d!\n", peer.m_id);
5060  return false;
5061  }
5062 
5063  if (pnode.addr.IsLocal()) {
5064  // We disconnect local peers for bad behavior but don't discourage (since that would discourage
5065  // all peers on the same local address)
5066  LogPrint(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n",
5067  pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
5068  pnode.fDisconnect = true;
5069  return true;
5070  }
5071 
5072  // Normal case: Disconnect the peer and discourage all nodes sharing the address
5073  LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id);
5074  if (m_banman) m_banman->Discourage(pnode.addr);
5075  m_connman.DisconnectNode(pnode.addr);
5076  return true;
5077 }
5078 
5079 bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
5080 {
5081  AssertLockHeld(g_msgproc_mutex);
5082 
5083  PeerRef peer = GetPeerRef(pfrom->GetId());
5084  if (peer == nullptr) return false;
5085 
5086  {
5087  LOCK(peer->m_getdata_requests_mutex);
5088  if (!peer->m_getdata_requests.empty()) {
5089  ProcessGetData(*pfrom, *peer, interruptMsgProc);
5090  }
5091  }
5092 
5093  const bool processed_orphan = ProcessOrphanTx(*peer);
5094 
5095  if (pfrom->fDisconnect)
5096  return false;
5097 
5098  if (processed_orphan) return true;
5099 
5100  // this maintains the order of responses
5101  // and prevents m_getdata_requests to grow unbounded
5102  {
5103  LOCK(peer->m_getdata_requests_mutex);
5104  if (!peer->m_getdata_requests.empty()) return true;
5105  }
5106 
5107  // Don't bother if send buffer is too full to respond anyway
5108  if (pfrom->fPauseSend) return false;
5109 
5110  auto poll_result{pfrom->PollMessage()};
5111  if (!poll_result) {
5112  // No message to process
5113  return false;
5114  }
5115 
5116  CNetMessage& msg{poll_result->first};
5117  bool fMoreWork = poll_result->second;
5118 
5119  TRACE6(net, inbound_message,
5120  pfrom->GetId(),
5121  pfrom->m_addr_name.c_str(),
5122  pfrom->ConnectionTypeAsString().c_str(),
5123  msg.m_type.c_str(),
5124  msg.m_recv.size(),
5125  msg.m_recv.data()
5126  );
5127 
5128  if (m_opts.capture_messages) {
5129  CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true);
5130  }
5131 
5132  try {
5133  ProcessMessage(*pfrom, msg.m_type, msg.m_recv, msg.m_time, interruptMsgProc);
5134  if (interruptMsgProc) return false;
5135  {
5136  LOCK(peer->m_getdata_requests_mutex);
5137  if (!peer->m_getdata_requests.empty()) fMoreWork = true;
5138  }
5139  // Does this peer has an orphan ready to reconsider?
5140  // (Note: we may have provided a parent for an orphan provided
5141  // by another peer that was already processed; in that case,
5142  // the extra work may not be noticed, possibly resulting in an
5143  // unnecessary 100ms delay)
5144  if (m_orphanage.HaveTxToReconsider(peer->m_id)) fMoreWork = true;
5145  } catch (const std::exception& e) {
5146  LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size, e.what(), typeid(e).name());
5147  } catch (...) {
5148  LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size);
5149  }
5150 
5151  return fMoreWork;
5152 }
5153 
5154 void PeerManagerImpl::ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds)
5155 {
5157 
5158  CNodeState &state = *State(pto.GetId());
5159 
5160  if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) {
5161  // This is an outbound peer subject to disconnection if they don't
5162  // announce a block with as much work as the current tip within
5163  // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
5164  // their chain has more work than ours, we should sync to it,
5165  // unless it's invalid, in which case we should find that out and
5166  // disconnect from them elsewhere).
5167  if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
5168  if (state.m_chain_sync.m_timeout != 0s) {
5169  state.m_chain_sync.m_timeout = 0s;
5170  state.m_chain_sync.m_work_header = nullptr;
5171  state.m_chain_sync.m_sent_getheaders = false;
5172  }
5173  } else if (state.m_chain_sync.m_timeout == 0s || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
5174  // Our best block known by this peer is behind our tip, and we're either noticing
5175  // that for the first time, OR this peer was able to catch up to some earlier point
5176  // where we checked against our tip.
5177  // Either way, set a new timeout based on current tip.
5178  state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
5179  state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
5180  state.m_chain_sync.m_sent_getheaders = false;
5181  } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) {
5182  // No evidence yet that our peer has synced to a chain with work equal to that
5183  // of our tip, when we first detected it was behind. Send a single getheaders
5184  // message to give the peer a chance to update us.
5185  if (state.m_chain_sync.m_sent_getheaders) {
5186  // They've run out of time to catch up!
5187  LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
5188  pto.fDisconnect = true;
5189  } else {
5190  assert(state.m_chain_sync.m_work_header);
5191  // Here, we assume that the getheaders message goes out,
5192  // because it'll either go out or be skipped because of a
5193  // getheaders in-flight already, in which case the peer should
5194  // still respond to us with a sufficiently high work chain tip.
5195  MaybeSendGetHeaders(pto,
5196  GetLocator(state.m_chain_sync.m_work_header->pprev),
5197  peer);
5198  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());
5199  state.m_chain_sync.m_sent_getheaders = true;
5200  // Bump the timeout to allow a response, which could clear the timeout
5201  // (if the response shows the peer has synced), reset the timeout (if
5202  // the peer syncs to the required work but not to our tip), or result
5203  // in disconnect (if we advance to the timeout and pindexBestKnownBlock
5204  // has not sufficiently progressed)
5205  state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
5206  }
5207  }
5208  }
5209 }
5210 
5211 void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now)
5212 {
5213  // If we have any extra block-relay-only peers, disconnect the youngest unless
5214  // it's given us a block -- in which case, compare with the second-youngest, and
5215  // out of those two, disconnect the peer who least recently gave us a block.
5216  // The youngest block-relay-only peer would be the extra peer we connected
5217  // to temporarily in order to sync our tip; see net.cpp.
5218  // Note that we use higher nodeid as a measure for most recent connection.
5219  if (m_connman.GetExtraBlockRelayCount() > 0) {
5220  std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0};
5221 
5222  m_connman.ForEachNode([&](CNode* pnode) {
5223  if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return;
5224  if (pnode->GetId() > youngest_peer.first) {
5225  next_youngest_peer = youngest_peer;
5226  youngest_peer.first = pnode->GetId();
5227  youngest_peer.second = pnode->m_last_block_time;
5228  }
5229  });
5230  NodeId to_disconnect = youngest_peer.first;
5231  if (youngest_peer.second > next_youngest_peer.second) {
5232  // Our newest block-relay-only peer gave us a block more recently;
5233  // disconnect our second youngest.
5234  to_disconnect = next_youngest_peer.first;
5235  }
5236  m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5238  // Make sure we're not getting a block right now, and that
5239  // we've been connected long enough for this eviction to happen
5240  // at all.
5241  // Note that we only request blocks from a peer if we learn of a
5242  // valid headers chain with at least as much work as our tip.
5243  CNodeState *node_state = State(pnode->GetId());
5244  if (node_state == nullptr ||
5245  (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->vBlocksInFlight.empty())) {
5246  pnode->fDisconnect = true;
5247  LogPrint(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n",
5248  pnode->GetId(), count_seconds(pnode->m_last_block_time));
5249  return true;
5250  } else {
5251  LogPrint(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
5252  pnode->GetId(), count_seconds(pnode->m_connected), node_state->vBlocksInFlight.size());
5253  }
5254  return false;
5255  });
5256  }
5257 
5258  // Check whether we have too many outbound-full-relay peers
5259  if (m_connman.GetExtraFullOutboundCount() > 0) {
5260  // If we have more outbound-full-relay peers than we target, disconnect one.
5261  // Pick the outbound-full-relay peer that least recently announced
5262  // us a new block, with ties broken by choosing the more recent
5263  // connection (higher node id)
5264  // Protect peers from eviction if we don't have another connection
5265  // to their network, counting both outbound-full-relay and manual peers.
5266  NodeId worst_peer = -1;
5267  int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
5268 
5269  m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_connman.GetNodesMutex()) {
5270  AssertLockHeld(::cs_main);
5271 
5272  // Only consider outbound-full-relay peers that are not already
5273  // marked for disconnection
5274  if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return;
5275  CNodeState *state = State(pnode->GetId());
5276  if (state == nullptr) return; // shouldn't be possible, but just in case
5277  // Don't evict our protected peers
5278  if (state->m_chain_sync.m_protect) return;
5279  // If this is the only connection on a particular network that is
5280  // OUTBOUND_FULL_RELAY or MANUAL, protect it.
5281  if (!m_connman.MultipleManualOrFullOutboundConns(pnode->addr.GetNetwork())) return;
5282  if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
5283  worst_peer = pnode->GetId();
5284  oldest_block_announcement = state->m_last_block_announcement;
5285  }
5286  });
5287  if (worst_peer != -1) {
5288  bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5290 
5291  // Only disconnect a peer that has been connected to us for
5292  // some reasonable fraction of our check-frequency, to give
5293  // it time for new information to have arrived.
5294  // Also don't disconnect any peer we're trying to download a
5295  // block from.
5296  CNodeState &state = *State(pnode->GetId());
5297  if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.vBlocksInFlight.empty()) {
5298  LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
5299  pnode->fDisconnect = true;
5300  return true;
5301  } else {
5302  LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
5303  pnode->GetId(), count_seconds(pnode->m_connected), state.vBlocksInFlight.size());
5304  return false;
5305  }
5306  });
5307  if (disconnected) {
5308  // If we disconnected an extra peer, that means we successfully
5309  // connected to at least one peer after the last time we
5310  // detected a stale tip. Don't try any more extra peers until
5311  // we next detect a stale tip, to limit the load we put on the
5312  // network from these extra connections.
5313  m_connman.SetTryNewOutboundPeer(false);
5314  }
5315  }
5316  }
5317 }
5318 
5319 void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
5320 {
5321  LOCK(cs_main);
5322 
5323  auto now{GetTime<std::chrono::seconds>()};
5324 
5325  EvictExtraOutboundPeers(now);
5326 
5327  if (now > m_stale_tip_check_time) {
5328  // Check whether our tip is stale, and if so, allow using an extra
5329  // outbound peer
5330  if (!m_chainman.m_blockman.LoadingBlocks() && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
5331  LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
5332  count_seconds(now - m_last_tip_update.load()));
5333  m_connman.SetTryNewOutboundPeer(true);
5334  } else if (m_connman.GetTryNewOutboundPeer()) {
5335  m_connman.SetTryNewOutboundPeer(false);
5336  }
5337  m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
5338  }
5339 
5340  if (!m_initial_sync_finished && CanDirectFetch()) {
5341  m_connman.StartExtraBlockRelayPeers();
5342  m_initial_sync_finished = true;
5343  }
5344 }
5345 
5346 void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now)
5347 {
5348  if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
5349  peer.m_ping_nonce_sent &&
5350  now > peer.m_ping_start.load() + TIMEOUT_INTERVAL)
5351  {
5352  // The ping timeout is using mocktime. To disable the check during
5353  // testing, increase -peertimeout.
5354  LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), peer.m_id);
5355  node_to.fDisconnect = true;
5356  return;
5357  }
5358 
5359  bool pingSend = false;
5360 
5361  if (peer.m_ping_queued) {
5362  // RPC ping request by user
5363  pingSend = true;
5364  }
5365 
5366  if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) {
5367  // Ping automatically sent as a latency probe & keepalive.
5368  pingSend = true;
5369  }
5370 
5371  if (pingSend) {
5372  uint64_t nonce;
5373  do {
5374  nonce = GetRand<uint64_t>();
5375  } while (nonce == 0);
5376  peer.m_ping_queued = false;
5377  peer.m_ping_start = now;
5378  if (node_to.GetCommonVersion() > BIP0031_VERSION) {
5379  peer.m_ping_nonce_sent = nonce;
5380  MakeAndPushMessage(node_to, NetMsgType::PING, nonce);
5381  } else {
5382  // Peer is too old to support ping command with nonce, pong will never arrive.
5383  peer.m_ping_nonce_sent = 0;
5384  MakeAndPushMessage(node_to, NetMsgType::PING);
5385  }
5386  }
5387 }
5388 
5389 void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time)
5390 {
5391  // Nothing to do for non-address-relay peers
5392  if (!peer.m_addr_relay_enabled) return;
5393 
5394  LOCK(peer.m_addr_send_times_mutex);
5395  // Periodically advertise our local address to the peer.
5396  if (fListen && !m_chainman.IsInitialBlockDownload() &&
5397  peer.m_next_local_addr_send < current_time) {
5398  // If we've sent before, clear the bloom filter for the peer, so that our
5399  // self-announcement will actually go out.
5400  // This might be unnecessary if the bloom filter has already rolled
5401  // over since our last self-announcement, but there is only a small
5402  // bandwidth cost that we can incur by doing this (which happens
5403  // once a day on average).
5404  if (peer.m_next_local_addr_send != 0us) {
5405  peer.m_addr_known->reset();
5406  }
5407  if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
5408  CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()};
5409  PushAddress(peer, local_addr);
5410  }
5411  peer.m_next_local_addr_send = GetExponentialRand(current_time, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
5412  }
5413 
5414  // We sent an `addr` message to this peer recently. Nothing more to do.
5415  if (current_time <= peer.m_next_addr_send) return;
5416 
5417  peer.m_next_addr_send = GetExponentialRand(current_time, AVG_ADDRESS_BROADCAST_INTERVAL);
5418 
5419  if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) {
5420  // Should be impossible since we always check size before adding to
5421  // m_addrs_to_send. Recover by trimming the vector.
5422  peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND);
5423  }
5424 
5425  // Remove addr records that the peer already knows about, and add new
5426  // addrs to the m_addr_known filter on the same pass.
5427  auto addr_already_known = [&peer](const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) {
5428  bool ret = peer.m_addr_known->contains(addr.GetKey());
5429  if (!ret) peer.m_addr_known->insert(addr.GetKey());
5430  return ret;
5431  };
5432  peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known),
5433  peer.m_addrs_to_send.end());
5434 
5435  // No addr messages to send
5436  if (peer.m_addrs_to_send.empty()) return;
5437 
5438  if (peer.m_wants_addrv2) {
5439  MakeAndPushMessage(node, NetMsgType::ADDRV2, CAddress::V2_NETWORK(peer.m_addrs_to_send));
5440  } else {
5441  MakeAndPushMessage(node, NetMsgType::ADDR, CAddress::V1_NETWORK(peer.m_addrs_to_send));
5442  }
5443  peer.m_addrs_to_send.clear();
5444 
5445  // we only send the big addr message once
5446  if (peer.m_addrs_to_send.capacity() > 40) {
5447  peer.m_addrs_to_send.shrink_to_fit();
5448  }
5449 }
5450 
5451 void PeerManagerImpl::MaybeSendSendHeaders(CNode& node, Peer& peer)
5452 {
5453  // Delay sending SENDHEADERS (BIP 130) until we're done with an
5454  // initial-headers-sync with this peer. Receiving headers announcements for
5455  // new blocks while trying to sync their headers chain is problematic,
5456  // because of the state tracking done.
5457  if (!peer.m_sent_sendheaders && node.GetCommonVersion() >= SENDHEADERS_VERSION) {
5458  LOCK(cs_main);
5459  CNodeState &state = *State(node.GetId());
5460  if (state.pindexBestKnownBlock != nullptr &&
5461  state.pindexBestKnownBlock->nChainWork > m_chainman.MinimumChainWork()) {
5462  // Tell our peer we prefer to receive headers rather than inv's
5463  // We send this to non-NODE NETWORK peers as well, because even
5464  // non-NODE NETWORK peers can announce blocks (such as pruning
5465  // nodes)
5466  MakeAndPushMessage(node, NetMsgType::SENDHEADERS);
5467  peer.m_sent_sendheaders = true;
5468  }
5469  }
5470 }
5471 
5472 void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time)
5473 {
5474  if (m_opts.ignore_incoming_txs) return;
5475  if (pto.GetCommonVersion() < FEEFILTER_VERSION) return;
5476  // peers with the forcerelay permission should not filter txs to us
5478  // Don't send feefilter messages to outbound block-relay-only peers since they should never announce
5479  // transactions to us, regardless of feefilter state.
5480  if (pto.IsBlockOnlyConn()) return;
5481 
5482  CAmount currentFilter = m_mempool.GetMinFee().GetFeePerK();
5483 
5484  if (m_chainman.IsInitialBlockDownload()) {
5485  // Received tx-inv messages are discarded when the active
5486  // chainstate is in IBD, so tell the peer to not send them.
5487  currentFilter = MAX_MONEY;
5488  } else {
5489  static const CAmount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)};
5490  if (peer.m_fee_filter_sent == MAX_FILTER) {
5491  // Send the current filter if we sent MAX_FILTER previously
5492  // and made it out of IBD.
5493  peer.m_next_send_feefilter = 0us;
5494  }
5495  }
5496  if (current_time > peer.m_next_send_feefilter) {
5497  CAmount filterToSend = m_fee_filter_rounder.round(currentFilter);
5498  // We always have a fee filter of at least the min relay fee
5499  filterToSend = std::max(filterToSend, m_mempool.m_min_relay_feerate.GetFeePerK());
5500  if (filterToSend != peer.m_fee_filter_sent) {
5501  MakeAndPushMessage(pto, NetMsgType::FEEFILTER, filterToSend);
5502  peer.m_fee_filter_sent = filterToSend;
5503  }
5504  peer.m_next_send_feefilter = GetExponentialRand(current_time, AVG_FEEFILTER_BROADCAST_INTERVAL);
5505  }
5506  // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
5507  // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
5508  else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter &&
5509  (currentFilter < 3 * peer.m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
5510  peer.m_next_send_feefilter = current_time + GetRandomDuration<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
5511  }
5512 }
5513 
5514 namespace {
5515 class CompareInvMempoolOrder
5516 {
5517  CTxMemPool* mp;
5518  bool m_wtxid_relay;
5519 public:
5520  explicit CompareInvMempoolOrder(CTxMemPool *_mempool, bool use_wtxid)
5521  {
5522  mp = _mempool;
5523  m_wtxid_relay = use_wtxid;
5524  }
5525 
5526  bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
5527  {
5528  /* As std::make_heap produces a max-heap, we want the entries with the
5529  * fewest ancestors/highest fee to sort later. */
5530  return mp->CompareDepthAndScore(*b, *a, m_wtxid_relay);
5531  }
5532 };
5533 } // namespace
5534 
5535 bool PeerManagerImpl::RejectIncomingTxs(const CNode& peer) const
5536 {
5537  // block-relay-only peers may never send txs to us
5538  if (peer.IsBlockOnlyConn()) return true;
5539  if (peer.IsFeelerConn()) return true;
5540  // In -blocksonly mode, peers need the 'relay' permission to send txs to us
5541  if (m_opts.ignore_incoming_txs && !peer.HasPermission(NetPermissionFlags::Relay)) return true;
5542  return false;
5543 }
5544 
5545 bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer)
5546 {
5547  // We don't participate in addr relay with outbound block-relay-only
5548  // connections to prevent providing adversaries with the additional
5549  // information of addr traffic to infer the link.
5550  if (node.IsBlockOnlyConn()) return false;
5551 
5552  if (!peer.m_addr_relay_enabled.exchange(true)) {
5553  // During version message processing (non-block-relay-only outbound peers)
5554  // or on first addr-related message we have received (inbound peers), initialize
5555  // m_addr_known.
5556  peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
5557  }
5558 
5559  return true;
5560 }
5561 
5562 bool PeerManagerImpl::SendMessages(CNode* pto)
5563 {
5564  AssertLockHeld(g_msgproc_mutex);
5565 
5566  PeerRef peer = GetPeerRef(pto->GetId());
5567  if (!peer) return false;
5568  const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
5569 
5570  // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
5571  // disconnect misbehaving peers even before the version handshake is complete.
5572  if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true;
5573 
5574  // Don't send anything until the version handshake is complete
5575  if (!pto->fSuccessfullyConnected || pto->fDisconnect)
5576  return true;
5577 
5578  const auto current_time{GetTime<std::chrono::microseconds>()};
5579 
5580  if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
5581  LogPrint(BCLog::NET, "addrfetch connection timeout; disconnecting peer=%d\n", pto->GetId());
5582  pto->fDisconnect = true;
5583  return true;
5584  }
5585 
5586  MaybeSendPing(*pto, *peer, current_time);
5587 
5588  // MaybeSendPing may have marked peer for disconnection
5589  if (pto->fDisconnect) return true;
5590 
5591  MaybeSendAddr(*pto, *peer, current_time);
5592 
5593  MaybeSendSendHeaders(*pto, *peer);
5594 
5595  {
5596  LOCK(cs_main);
5597 
5598  CNodeState &state = *State(pto->GetId());
5599 
5600  // Start block sync
5601  if (m_chainman.m_best_header == nullptr) {
5602  m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
5603  }
5604 
5605  // Determine whether we might try initial headers sync or parallel
5606  // block download from this peer -- this mostly affects behavior while
5607  // in IBD (once out of IBD, we sync from all peers).
5608  bool sync_blocks_and_headers_from_peer = false;
5609  if (state.fPreferredDownload) {
5610  sync_blocks_and_headers_from_peer = true;
5611  } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) {
5612  // Typically this is an inbound peer. If we don't have any outbound
5613  // peers, or if we aren't downloading any blocks from such peers,
5614  // then allow block downloads from this peer, too.
5615  // We prefer downloading blocks from outbound peers to avoid
5616  // putting undue load on (say) some home user who is just making
5617  // outbound connections to the network, but if our only source of
5618  // the latest blocks is from an inbound peer, we have to be sure to
5619  // eventually download it (and not just wait indefinitely for an
5620  // outbound peer to have it).
5621  if (m_num_preferred_download_peers == 0 || mapBlocksInFlight.empty()) {
5622  sync_blocks_and_headers_from_peer = true;
5623  }
5624  }
5625 
5626  if (!state.fSyncStarted && CanServeBlocks(*peer) && !m_chainman.m_blockman.LoadingBlocks()) {
5627  // Only actively request headers from a single peer, unless we're close to today.
5628  if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->Time() > NodeClock::now() - 24h) {
5629  const CBlockIndex* pindexStart = m_chainman.m_best_header;
5630  /* If possible, start at the block preceding the currently
5631  best known header. This ensures that we always get a
5632  non-empty list of headers back as long as the peer
5633  is up-to-date. With a non-empty response, we can initialise
5634  the peer's known best block. This wouldn't be possible
5635  if we requested starting at m_chainman.m_best_header and
5636  got back an empty response. */
5637  if (pindexStart->pprev)
5638  pindexStart = pindexStart->pprev;
5639  if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) {
5640  LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height);
5641 
5642  state.fSyncStarted = true;
5643  peer->m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
5644  (
5645  // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
5646  // to maintain precision
5647  std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
5648  Ticks<std::chrono::seconds>(NodeClock::now() - m_chainman.m_best_header->Time()) / consensusParams.nPowTargetSpacing
5649  );
5650  nSyncStarted++;
5651  }
5652  }
5653  }
5654 
5655  //
5656  // Try sending block announcements via headers
5657  //
5658  {
5659  // If we have no more than MAX_BLOCKS_TO_ANNOUNCE in our
5660  // list of block hashes we're relaying, and our peer wants
5661  // headers announcements, then find the first header
5662  // not yet known to our peer but would connect, and send.
5663  // If no header would connect, or if we have too many
5664  // blocks, or if the peer doesn't want headers, just
5665  // add all to the inv queue.
5666  LOCK(peer->m_block_inv_mutex);
5667  std::vector<CBlock> vHeaders;
5668  bool fRevertToInv = ((!peer->m_prefers_headers &&
5669  (!state.m_requested_hb_cmpctblocks || peer->m_blocks_for_headers_relay.size() > 1)) ||
5670  peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE);
5671  const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
5672  ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
5673 
5674  if (!fRevertToInv) {
5675  bool fFoundStartingHeader = false;
5676  // Try to find first header that our peer doesn't have, and
5677  // then send all headers past that one. If we come across any
5678  // headers that aren't on m_chainman.ActiveChain(), give up.
5679  for (const uint256& hash : peer->m_blocks_for_headers_relay) {
5680  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
5681  assert(pindex);
5682  if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
5683  // Bail out if we reorged away from this block
5684  fRevertToInv = true;
5685  break;
5686  }
5687  if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
5688  // This means that the list of blocks to announce don't
5689  // connect to each other.
5690  // This shouldn't really be possible to hit during
5691  // regular operation (because reorgs should take us to
5692  // a chain that has some block not on the prior chain,
5693  // which should be caught by the prior check), but one
5694  // way this could happen is by using invalidateblock /
5695  // reconsiderblock repeatedly on the tip, causing it to
5696  // be added multiple times to m_blocks_for_headers_relay.
5697  // Robustly deal with this rare situation by reverting
5698  // to an inv.
5699  fRevertToInv = true;
5700  break;
5701  }
5702  pBestIndex = pindex;
5703  if (fFoundStartingHeader) {
5704  // add this to the headers message
5705  vHeaders.emplace_back(pindex->GetBlockHeader());
5706  } else if (PeerHasHeader(&state, pindex)) {
5707  continue; // keep looking for the first new block
5708  } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
5709  // Peer doesn't have this header but they do have the prior one.
5710  // Start sending headers.
5711  fFoundStartingHeader = true;
5712  vHeaders.emplace_back(pindex->GetBlockHeader());
5713  } else {
5714  // Peer doesn't have this header or the prior one -- nothing will
5715  // connect, so bail out.
5716  fRevertToInv = true;
5717  break;
5718  }
5719  }
5720  }
5721  if (!fRevertToInv && !vHeaders.empty()) {
5722  if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
5723  // We only send up to 1 block as header-and-ids, as otherwise
5724  // probably means we're doing an initial-ish-sync or they're slow
5725  LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
5726  vHeaders.front().GetHash().ToString(), pto->GetId());
5727 
5728  std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
5729  {
5730  LOCK(m_most_recent_block_mutex);
5731  if (m_most_recent_block_hash == pBestIndex->GetBlockHash()) {
5732  cached_cmpctblock_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, *m_most_recent_compact_block);
5733  }
5734  }
5735  if (cached_cmpctblock_msg.has_value()) {
5736  PushMessage(*pto, std::move(cached_cmpctblock_msg.value()));
5737  } else {
5738  CBlock block;
5739  const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(block, *pBestIndex)};
5740  assert(ret);
5741  CBlockHeaderAndShortTxIDs cmpctblock{block};
5742  MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK, cmpctblock);
5743  }
5744  state.pindexBestHeaderSent = pBestIndex;
5745  } else if (peer->m_prefers_headers) {
5746  if (vHeaders.size() > 1) {
5747  LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
5748  vHeaders.size(),
5749  vHeaders.front().GetHash().ToString(),
5750  vHeaders.back().GetHash().ToString(), pto->GetId());
5751  } else {
5752  LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
5753  vHeaders.front().GetHash().ToString(), pto->GetId());
5754  }
5755  MakeAndPushMessage(*pto, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders));
5756  state.pindexBestHeaderSent = pBestIndex;
5757  } else
5758  fRevertToInv = true;
5759  }
5760  if (fRevertToInv) {
5761  // If falling back to using an inv, just try to inv the tip.
5762  // The last entry in m_blocks_for_headers_relay was our tip at some point
5763  // in the past.
5764  if (!peer->m_blocks_for_headers_relay.empty()) {
5765  const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back();
5766  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
5767  assert(pindex);
5768 
5769  // Warn if we're announcing a block that is not on the main chain.
5770  // This should be very rare and could be optimized out.
5771  // Just log for now.
5772  if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
5773  LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
5774  hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString());
5775  }
5776 
5777  // If the peer's chain has this block, don't inv it back.
5778  if (!PeerHasHeader(&state, pindex)) {
5779  peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
5780  LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
5781  pto->GetId(), hashToAnnounce.ToString());
5782  }
5783  }
5784  }
5785  peer->m_blocks_for_headers_relay.clear();
5786  }
5787 
5788  //
5789  // Message: inventory
5790  //
5791  std::vector<CInv> vInv;
5792  {
5793  LOCK(peer->m_block_inv_mutex);
5794  vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_TARGET));
5795 
5796  // Add blocks
5797  for (const uint256& hash : peer->m_blocks_for_inv_relay) {
5798  vInv.emplace_back(MSG_BLOCK, hash);
5799  if (vInv.size() == MAX_INV_SZ) {
5800  MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5801  vInv.clear();
5802  }
5803  }
5804  peer->m_blocks_for_inv_relay.clear();
5805  }
5806 
5807  if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
5808  LOCK(tx_relay->m_tx_inventory_mutex);
5809  // Check whether periodic sends should happen
5810  bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
5811  if (tx_relay->m_next_inv_send_time < current_time) {
5812  fSendTrickle = true;
5813  if (pto->IsInboundConn()) {
5814  tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL);
5815  } else {
5816  tx_relay->m_next_inv_send_time = GetExponentialRand(current_time, OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
5817  }
5818  }
5819 
5820  // Time to send but the peer has requested we not relay transactions.
5821  if (fSendTrickle) {
5822  LOCK(tx_relay->m_bloom_filter_mutex);
5823  if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear();
5824  }
5825 
5826  // Respond to BIP35 mempool requests
5827  if (fSendTrickle && tx_relay->m_send_mempool) {
5828  auto vtxinfo = m_mempool.infoAll();
5829  tx_relay->m_send_mempool = false;
5830  const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
5831 
5832  LOCK(tx_relay->m_bloom_filter_mutex);
5833 
5834  for (const auto& txinfo : vtxinfo) {
5835  CInv inv{
5836  peer->m_wtxid_relay ? MSG_WTX : MSG_TX,
5837  peer->m_wtxid_relay ?
5838  txinfo.tx->GetWitnessHash().ToUint256() :
5839  txinfo.tx->GetHash().ToUint256(),
5840  };
5841  tx_relay->m_tx_inventory_to_send.erase(inv.hash);
5842 
5843  // Don't send transactions that peers will not put into their mempool
5844  if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
5845  continue;
5846  }
5847  if (tx_relay->m_bloom_filter) {
5848  if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
5849  }
5850  tx_relay->m_tx_inventory_known_filter.insert(inv.hash);
5851  vInv.push_back(inv);
5852  if (vInv.size() == MAX_INV_SZ) {
5853  MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5854  vInv.clear();
5855  }
5856  }
5857  }
5858 
5859  // Determine transactions to relay
5860  if (fSendTrickle) {
5861  // Produce a vector with all candidates for sending
5862  std::vector<std::set<uint256>::iterator> vInvTx;
5863  vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
5864  for (std::set<uint256>::iterator it = tx_relay->m_tx_inventory_to_send.begin(); it != tx_relay->m_tx_inventory_to_send.end(); it++) {
5865  vInvTx.push_back(it);
5866  }
5867  const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
5868  // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
5869  // A heap is used so that not all items need sorting if only a few are being sent.
5870  CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, peer->m_wtxid_relay);
5871  std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
5872  // No reason to drain out at many times the network's capacity,
5873  // especially since we have many peers and some will draw much shorter delays.
5874  unsigned int nRelayedTransactions = 0;
5875  LOCK(tx_relay->m_bloom_filter_mutex);
5876  size_t broadcast_max{INVENTORY_BROADCAST_TARGET + (tx_relay->m_tx_inventory_to_send.size()/1000)*5};
5877  broadcast_max = std::min<size_t>(INVENTORY_BROADCAST_MAX, broadcast_max);
5878  while (!vInvTx.empty() && nRelayedTransactions < broadcast_max) {
5879  // Fetch the top element from the heap
5880  std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
5881  std::set<uint256>::iterator it = vInvTx.back();
5882  vInvTx.pop_back();
5883  uint256 hash = *it;
5884  CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
5885  // Remove it from the to-be-sent set
5886  tx_relay->m_tx_inventory_to_send.erase(it);
5887  // Check if not in the filter already
5888  if (tx_relay->m_tx_inventory_known_filter.contains(hash)) {
5889  continue;
5890  }
5891  // Not in the mempool anymore? don't bother sending it.
5892  auto txinfo = m_mempool.info(ToGenTxid(inv));
5893  if (!txinfo.tx) {
5894  continue;
5895  }
5896  // Peer told you to not send transactions at that feerate? Don't bother sending it.
5897  if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
5898  continue;
5899  }
5900  if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
5901  // Send
5902  vInv.push_back(inv);
5903  nRelayedTransactions++;
5904  if (vInv.size() == MAX_INV_SZ) {
5905  MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5906  vInv.clear();
5907  }
5908  tx_relay->m_tx_inventory_known_filter.insert(hash);
5909  }
5910 
5911  // Ensure we'll respond to GETDATA requests for anything we've just announced
5912  LOCK(m_mempool.cs);
5913  tx_relay->m_last_inv_sequence = m_mempool.GetSequence();
5914  }
5915  }
5916  if (!vInv.empty())
5917  MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
5918 
5919  // Detect whether we're stalling
5920  auto stalling_timeout = m_block_stalling_timeout.load();
5921  if (state.m_stalling_since.count() && state.m_stalling_since < current_time - stalling_timeout) {
5922  // Stalling only triggers when the block download window cannot move. During normal steady state,
5923  // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5924  // should only happen during initial block download.
5925  LogPrintf("Peer=%d%s is stalling block download, disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : "");
5926  pto->fDisconnect = true;
5927  // Increase timeout for the next peer so that we don't disconnect multiple peers if our own
5928  // bandwidth is insufficient.
5929  const auto new_timeout = std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX);
5930  if (stalling_timeout != new_timeout && m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) {
5931  LogPrint(BCLog::NET, "Increased stalling timeout temporarily to %d seconds\n", count_seconds(new_timeout));
5932  }
5933  return true;
5934  }
5935  // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N)
5936  // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
5937  // We compensate for other peers to prevent killing off peers due to our own downstream link
5938  // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5939  // to unreasonably increase our timeout.
5940  if (state.vBlocksInFlight.size() > 0) {
5941  QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5942  int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1;
5943  if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
5944  LogPrintf("Timeout downloading block %s from peer=%d%s, disconnecting\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : "");
5945  pto->fDisconnect = true;
5946  return true;
5947  }
5948  }
5949  // Check for headers sync timeouts
5950  if (state.fSyncStarted && peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
5951  // Detect whether this is a stalling initial-headers-sync peer
5952  if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {
5953  if (current_time > peer->m_headers_sync_timeout && nSyncStarted == 1 && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)) {
5954  // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
5955  // and we have others we could be using instead.
5956  // Note: If all our peers are inbound, then we won't
5957  // disconnect our sync peer for stalling; we have bigger
5958  // problems if we can't get any outbound peers.
5960  LogPrintf("Timeout downloading headers from peer=%d%s, disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : "");
5961  pto->fDisconnect = true;
5962  return true;
5963  } else {
5964  LogPrintf("Timeout downloading headers from noban peer=%d%s, not disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : "");
5965  // Reset the headers sync state so that we have a
5966  // chance to try downloading from a different peer.
5967  // Note: this will also result in at least one more
5968  // getheaders message to be sent to
5969  // this peer (eventually).
5970  state.fSyncStarted = false;
5971  nSyncStarted--;
5972  peer->m_headers_sync_timeout = 0us;
5973  }
5974  }
5975  } else {
5976  // After we've caught up once, reset the timeout so we can't trigger
5977  // disconnect later.
5978  peer->m_headers_sync_timeout = std::chrono::microseconds::max();
5979  }
5980  }
5981 
5982  // Check that outbound peers have reasonable chains
5983  // GetTime() is used by this anti-DoS logic so we can test this using mocktime
5984  ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
5985 
5986  //
5987  // Message: getdata (blocks)
5988  //
5989  std::vector<CInv> vGetData;
5990  if (CanServeBlocks(*peer) && ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) || !m_chainman.IsInitialBlockDownload()) && state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5991  std::vector<const CBlockIndex*> vToDownload;
5992  NodeId staller = -1;
5993  auto get_inflight_budget = [&state]() {
5994  return std::max(0, MAX_BLOCKS_IN_TRANSIT_PER_PEER - static_cast<int>(state.vBlocksInFlight.size()));
5995  };
5996 
5997  // If a snapshot chainstate is in use, we want to find its next blocks
5998  // before the background chainstate to prioritize getting to network tip.
5999  FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload, staller);
6000  if (m_chainman.BackgroundSyncInProgress() && !IsLimitedPeer(*peer)) {
6001  TryDownloadingHistoricalBlocks(
6002  *peer,
6003  get_inflight_budget(),
6004  vToDownload, m_chainman.GetBackgroundSyncTip(),
6005  Assert(m_chainman.GetSnapshotBaseBlock()));
6006  }
6007  for (const CBlockIndex *pindex : vToDownload) {
6008  uint32_t nFetchFlags = GetFetchFlags(*peer);
6009  vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash());
6010  BlockRequested(pto->GetId(), *pindex);
6011  LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
6012  pindex->nHeight, pto->GetId());
6013  }
6014  if (state.vBlocksInFlight.empty() && staller != -1) {
6015  if (State(staller)->m_stalling_since == 0us) {
6016  State(staller)->m_stalling_since = current_time;
6017  LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
6018  }
6019  }
6020  }
6021 
6022  //
6023  // Message: getdata (transactions)
6024  //
6025  std::vector<std::pair<NodeId, GenTxid>> expired;
6026  auto requestable = m_txrequest.GetRequestable(pto->GetId(), current_time, &expired);
6027  for (const auto& entry : expired) {
6028  LogPrint(BCLog::NET, "timeout of inflight %s %s from peer=%d\n", entry.second.IsWtxid() ? "wtx" : "tx",
6029  entry.second.GetHash().ToString(), entry.first);
6030  }
6031  for (const GenTxid& gtxid : requestable) {
6032  if (!AlreadyHaveTx(gtxid)) {
6033  LogPrint(BCLog::NET, "Requesting %s %s peer=%d\n", gtxid.IsWtxid() ? "wtx" : "tx",
6034  gtxid.GetHash().ToString(), pto->GetId());
6035  vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*peer)), gtxid.GetHash());
6036  if (vGetData.size() >= MAX_GETDATA_SZ) {
6037  MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData);
6038  vGetData.clear();
6039  }
6040  m_txrequest.RequestedTx(pto->GetId(), gtxid.GetHash(), current_time + GETDATA_TX_INTERVAL);
6041  } else {
6042  // We have already seen this transaction, no need to download. This is just a belt-and-suspenders, as
6043  // this should already be called whenever a transaction becomes AlreadyHaveTx().
6044  m_txrequest.ForgetTxHash(gtxid.GetHash());
6045  }
6046  }
6047 
6048 
6049  if (!vGetData.empty())
6050  MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData);
6051  } // release cs_main
6052  MaybeSendFeefilter(*pto, *peer, current_time);
6053  return true;
6054 }
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int ret
if(!SetupNetworking())
ArgsManager & args
Definition: bitcoind.cpp:268
@ READ_STATUS_OK
@ READ_STATUS_INVALID
@ READ_STATUS_FAILED
enum ReadStatus_t ReadStatus
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
BlockFilterType
Definition: blockfilter.h:93
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:131
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:50
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:165
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:146
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:111
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:107
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition: chain.h:115
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:97
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:121
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:77
#define Assume(val)
Assume is the identity function.
Definition: check.h:89
Stochastic address manager.
Definition: addrman.h:88
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
Definition: addrman.cpp:1335
bool Good(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
Mark an address record as accessible and attempt to move it to addrman's tried table.
Definition: addrman.cpp:1300
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
Definition: addrman.cpp:1295
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Definition: addrman.cpp:1340
Definition: banman.h:59
bool IsBanned(const CNetAddr &net_addr) EXCLUSIVE_LOCKS_REQUIRED(!m_banned_mutex)
Return whether net_addr is banned.
Definition: banman.cpp:89
bool IsDiscouraged(const CNetAddr &net_addr) EXCLUSIVE_LOCKS_REQUIRED(!m_banned_mutex)
Return whether net_addr is discouraged.
Definition: banman.cpp:83
void Discourage(const CNetAddr &net_addr) EXCLUSIVE_LOCKS_REQUIRED(!m_banned_mutex)
Definition: banman.cpp:124
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
bool LookupFilterHashRange(int start_height, const CBlockIndex *stop_index, std::vector< uint256 > &hashes_out) const
Get a range of filter hashes between two heights on a chain.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
std::vector< CTransactionRef > txn
std::vector< uint16_t > indexes
A CService with information about it as peer.
Definition: protocol.h:332
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:423
static constexpr SerParams V1_NETWORK
Definition: protocol.h:373
NodeSeconds nTime
Always included in serialization. The behavior is unspecified if the value is not representable as ui...
Definition: protocol.h:421
static constexpr SerParams V2_NETWORK
Definition: protocol.h:374
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
uint256 hashPrevBlock
Definition: block.h:26
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:147
CBlockHeader GetBlockHeader() const
Definition: chain.h:231
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:165
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
Definition: chain.h:260
uint256 GetBlockHash() const
Definition: chain.h:244
int64_t GetBlockTime() const
Definition: chain.h:267
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:170
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:296
NodeSeconds Time() const
Definition: chain.h:262
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:120
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:209
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:45
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
Definition: bloom.cpp:89
An in-memory indexed chain of blocks.
Definition: chain.h:418
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:454
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:434
int Height() const
Return the maximal height in the chain.
Definition: chain.h:463
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:448
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:81
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:93
Definition: net.h:1036
void ForEachNode(const NodeFn &func)
Definition: net.h:1135
RecursiveMutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3781
bool GetNetworkActive() const
Definition: net.h:1120
bool GetTryNewOutboundPeer() const
Definition: net.cpp:2312
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2317
int GetExtraBlockRelayCount() const
Definition: net.cpp:2349
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2160
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:3601
void StartExtraBlockRelayPeers()
Definition: net.cpp:2323
bool DisconnectNode(const std::string &node)
Definition: net.cpp:3501
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3794
uint32_t GetMappedAS(const CNetAddr &addr) const
Definition: net.cpp:3484
int GetExtraFullOutboundCount() const
Definition: net.cpp:2335
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network, const bool filtered=true) const
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:3376
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:365
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1943
bool GetUseAddrmanOutgoing() const
Definition: net.h:1121
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition: feerate.h:65
inv message data
Definition: protocol.h:458
bool IsMsgCmpctBlk() const
Definition: protocol.h:475
bool IsMsgBlk() const
Definition: protocol.h:472
std::string ToString() const
Definition: protocol.cpp:158
bool IsMsgWtx() const
Definition: protocol.h:473
bool IsGenTxMsg() const
Definition: protocol.h:479
bool IsMsgTx() const
Definition: protocol.h:471
bool IsMsgFilteredBlk() const
Definition: protocol.h:474
uint256 hash
Definition: protocol.h:489
bool IsGenBlkMsg() const
Definition: protocol.h:483
bool IsMsgWitnessBlk() const
Definition: protocol.h:476
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:126
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
Definition: merkleblock.h:138
bool IsRelayable() const
Whether this address should be relayed to other peers even if we can't reach it ourselves.
Definition: netaddress.h:218
bool IsRoutable() const
Definition: netaddress.cpp:463
static constexpr SerParams V1
Definition: netaddress.h:231
bool IsValid() const
Definition: netaddress.cpp:425
bool IsLocal() const
Definition: netaddress.cpp:399
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:478
Transport protocol agnostic message container.
Definition: net.h:233
Information about a peer.
Definition: net.h:672
bool IsFeelerConn() const
Definition: net.h:803
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:705
bool ExpectServicesFromConn() const
Definition: net.h:815
std::atomic< int > nVersion
Definition: net.h:716
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:851
bool IsInboundConn() const
Definition: net.h:811
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:724
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:760
NodeId GetId() const
Definition: net.h:894
bool IsManualConn() const
Definition: net.h:779
std::atomic< int64_t > nTimeOffset
Definition: net.h:706
const std::string m_addr_name
Definition: net.h:711
std::string ConnectionTypeAsString() const
Definition: net.h:948
void SetCommonVersion(int greatest_common_version)
Definition: net.h:919
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:846
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:855
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:848
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:951
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:728
bool IsAddrFetchConn() const
Definition: net.h:807
uint64_t GetLocalNonce() const
Definition: net.h:898
const CAddress addr
Definition: net.h:708
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:569
bool IsBlockOnlyConn() const
Definition: net.h:799
int GetCommonVersion() const
Definition: net.h:924
bool IsFullOutboundConn() const
Definition: net.h:775
Mutex m_subver_mutex
Definition: net.h:717
std::atomic_bool fPauseSend
Definition: net.h:737
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
Definition: net.cpp:3715
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:859
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition: net.h:676
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:715
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:866
std::atomic_bool fDisconnect
Definition: net.h:731
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:872
Txid hash
Definition: transaction.h:31
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:109
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:40
void scheduleEvery(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat f until the scheduler is stopped.
Definition: scheduler.cpp:108
void scheduleFromNow(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Call f once after the delta has passed.
Definition: scheduler.h:53
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
std::string ToStringAddrPort() const
Definition: netaddress.cpp:902
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:894
SipHash-2-4.
Definition: siphash.h:15
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:77
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data It is treated as if this was the little-endian interpretation of ...
Definition: siphash.cpp:28
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
bool HasWitness() const
Definition: transaction.h:373
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:344
const std::vector< CTxIn > vin
Definition: transaction.h:306
An input of a transaction.
Definition: transaction.h:67
COutPoint prevout
Definition: transaction.h:69
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:302
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1033
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:390
CFeeRate GetMinFee(size_t sizelimit) const
Definition: txmempool.cpp:1095
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:847
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1027
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:826
TxMempoolInfo info(const GenTxid &gtxid) const
Definition: txmempool.cpp:856
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:718
const CFeeRate m_min_relay_feerate
Definition: txmempool.h:442
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:736
TxMempoolInfo info_for_relay(const GenTxid &gtxid, uint64_t last_sequence) const
Returns info for a transaction if its entry_sequence < last_sequence.
Definition: txmempool.cpp:865
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:678
unsigned long size() const
Definition: txmempool.h:660
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
Notifies listeners that a block which builds directly on our current tip has been received and connec...
virtual void BlockConnected(ChainstateRole role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected Provides the block that was disconnected.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:850
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1069
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1068
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:937
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:959
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1074
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1071
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1079
void ReportHeadersPresync(const arith_uint256 &work, int64_t height, int64_t timestamp)
This is used by net_processing to report pre-synchronization progress of headers, as headers are not ...
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:966
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
bool empty() const
Definition: streams.h:182
size_type size() const
Definition: streams.h:181
void ignore(size_t num_ignore)
Definition: streams.h:236
int in_avail() const
Definition: streams.h:216
Fast randomness source.
Definition: random.h:145
A generic txid reference (txid or wtxid).
Definition: transaction.h:428
bool IsWtxid() const
Definition: transaction.h:436
const uint256 & GetHash() const LIFETIMEBOUND
Definition: transaction.h:437
static GenTxid Wtxid(const uint256 &hash)
Definition: transaction.h:435
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:434
HeadersSyncState:
Definition: headerssync.h:101
@ FINAL
We're done syncing with this peer and can discard any remaining state.
@ PRESYNC
PRESYNC means the peer has not yet demonstrated their chain has sufficient work and we're only buildi...
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:995
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const =0
Callback to determine whether the given set of service flags are sufficient for a peer to be "relevan...
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual void InitializeNode(CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< CTransactionRef > &extra_txn)
bool IsTxAvailable(size_t index) const
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
virtual void ProcessMessage(CNode &pfrom, const std::string &msg_type, DataStream &vRecv, const std::chrono::microseconds time_received, const std::atomic< bool > &interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process a single message from a peer.
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, Options opts)
virtual void SendPings()=0
Send ping message to all peers.
virtual std::optional< std::string > FetchBlock(NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
virtual ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const =0
Gets the set of service flags which are "desirable" for a given peer.
virtual void StartScheduledTasks(CScheduler &scheduler)=0
Begin running background tasks, should only be called once.
virtual bool IgnoresIncomingTxs()=0
Whether this node ignores txs received over p2p.
virtual void UnitTestMisbehaving(NodeId peer_id, int howmuch)=0
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)=0
This function is used for testing the stale tip eviction logic, see denialofservice_tests....
virtual void CheckForStaleTipAndEvictPeers()=0
Evict extra outbound peers.
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:124
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
A class to track orphan transactions (failed on TX_MISSING_INPUTS) Since we cannot distinguish orphan...
Definition: txorphanage.h:21
bool HaveTxToReconsider(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Does this peer have any work to do?
void AddChildrenToWorkSet(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Add any orphans that list a particular tx as a parent into the from peer's work set.
void LimitOrphans(unsigned int max_orphans, FastRandomContext &rng) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Limit the orphanage to the given maximum.
void EraseForBlock(const CBlock &block) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase all orphans included in or invalidated by a new block.
bool AddTx(const CTransactionRef &tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Add a new orphan transaction.
Definition: txorphanage.cpp:20
bool HaveTx(const GenTxid &gtxid) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check if we already have an orphan transaction (by txid or wtxid)
size_t Size() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Return how many entries exist in the orphange.
Definition: txorphanage.h:55
CTransactionRef GetTxToReconsider(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Extract a transaction from a peer's work set Returns nullptr if there are no transactions to work on.
int EraseTx(const Txid &txid) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase an orphan by txid.
Definition: txorphanage.cpp:57
void EraseForPeer(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase all orphans announced by a peer (eg, after that peer disconnects)
Definition: txorphanage.cpp:97
Data structure to keep track of, and schedule, transaction downloads from peers.
Definition: txrequest.h:96
bool IsValid() const
Definition: validation.h:122
Result GetResult() const
Definition: validation.h:125
std::string ToString() const
Definition: validation.h:128
bool IsInvalid() const
Definition: validation.h:123
256-bit unsigned big integer.
constexpr bool IsNull() const
Definition: uint256.h:42
std::string ToString() const
Definition: uint256.cpp:55
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos) const
bool LoadingBlocks() const
Definition: blockstorage.h:325
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:319
std::string ToString() const
const uint256 & ToUint256() const LIFETIMEBOUND
256-bit opaque blob.
Definition: uint256.h:106
std::string TransportTypeAsString(TransportProtocolType transport_type)
Convert TransportProtocolType enum to a string value.
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_RECENT_CONSENSUS_CHANGE
Invalid by a change to consensus rules more recent than SegWit.
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ BLOCK_RESULT_UNSET
initial value. Block has not yet been rejected
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
@ TX_UNKNOWN
transaction was not validated because package failed
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_INPUTS_NOT_STANDARD
inputs (covered by txid) failed policy rules
@ TX_WITNESS_STRIPPED
Transaction is missing a witness.
@ TX_CONFLICT
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
@ TX_RECENT_CONSENSUS_CHANGE
Invalid by a change to consensus rules more recent than SegWit.
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_WITNESS_MUTATED
Transaction might have a witness prior to SegWit activation, or witness may have been malleated (whic...
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_RESULT_UNSET
initial value. Tx has not yet been rejected
@ TX_CONSENSUS
invalid by consensus rules
@ TX_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep, [[maybe_unused]] VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params &params, Consensus::BuriedDeployment dep, [[maybe_unused]] VersionBitsCache &versionbitscache)
Determine if a deployment is active for this block.
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
bool fLogIPs
Definition: logging.cpp:40
#define LogPrintLevel(category, level,...)
Definition: logging.h:251
#define LogPrint(category,...)
Definition: logging.h:263
#define LogInfo(...)
Definition: logging.h:239
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:209
#define LogDebug(category,...)
Definition: logging.h:259
#define LogPrintf(...)
Definition: logging.h:244
unsigned int nonce
Definition: miner_tests.cpp:71
@ TXPACKAGES
Definition: logging.h:71
@ MEMPOOLREJ
Definition: logging.h:57
@ MEMPOOL
Definition: logging.h:43
@ NET
Definition: logging.h:41
Transaction validation functions.
@ DEPLOYMENT_SEGWIT
Definition: params.h:28
CSerializedNetMsg Make(std::string msg_type, Args &&... args)
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:31
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:43
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:41
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:25
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:33
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:24
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:16
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:34
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition: protocol.cpp:29
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:36
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:26
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:44
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:30
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition: protocol.cpp:37
const char * SENDTXRCNCL
Contains a 4-byte version number and an 8-byte salt.
Definition: protocol.cpp:47
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:27
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:40
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:23
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:32
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:15
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:13
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:21
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition: protocol.cpp:35
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:22
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:19
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:14
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:39
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.cpp:42
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:17
const char * WTXIDRELAY
Indicates that a node prefers to relay transactions via wtxid, rather than txid.
Definition: protocol.cpp:46
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:28
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:20
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:45
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:38
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:18
Functions to serialize / deserialize common bitcoin types.
Definition: common-types.h:50
Definition: init.h:25
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:238
bool fListen
Definition: net.cpp:116
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:119
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:3882
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:310
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:65
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:57
int64_t NodeId
Definition: net.h:97
static constexpr auto HEADERS_RESPONSE_TIME
How long to wait for a peer to respond to a getheaders request.
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of address records permitted in an ADDR message.
static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET
The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND based inc...
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT
Default time during which a peer must stall block download progress before being disconnected.
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL
Average delay between feefilter broadcasts in seconds.
static constexpr auto EXTRA_PEER_CHECK_INTERVAL
How frequently to check for extra outbound peers and disconnect.
static const unsigned int BLOCK_DOWNLOAD_WINDOW
Size of the "block download window": how far ahead of our current height do we fetch?...
static constexpr int STALE_RELAY_AGE_LIMIT
Age after which a stale block will no longer be served if requested as protection against fingerprint...
static constexpr int HISTORICAL_BLOCK_AGE
Age after which a block is considered historical for purposes of rate limiting block relay.
static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL
Delay between rotating the peers we relay a particular address to.
static const int MAX_NUM_UNCONNECTING_HEADERS_MSGS
Maximum number of unconnecting headers announcements before DoS score.
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict.
static constexpr auto CHAIN_SYNC_TIMEOUT
Timeout for (unprotected) outbound peers to sync to our chainwork.
static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for outbound peers.
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS
Minimum blocks required to signal NODE_NETWORK_LIMITED.
static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
Average delay between local address broadcasts.
static const int MAX_BLOCKTXN_DEPTH
Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for.
static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT
Maximum number of in-flight transaction requests from a peer.
static constexpr uint64_t CMPCTBLOCKS_VERSION
The compactblocks version we support.
static constexpr auto OVERLOADED_PEER_TX_DELAY
How long to delay requesting transactions from overloaded peers (see MAX_PEER_TX_REQUEST_IN_FLIGHT).
static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT
Protect at least this many outbound peers from disconnection due to slow/ behind headers chain.
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for inbound peers.
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY
Maximum feefilter broadcast delay after significant change.
static constexpr uint32_t MAX_GETCFILTERS_SIZE
Maximum number of compact filters that may be requested with one getcfilters.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE
Headers download timeout.
static const unsigned int MAX_GETDATA_SZ
Limit to avoid sending big packets.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in multiples of the block interval (i.e.
static constexpr auto STALE_CHECK_INTERVAL
How frequently to check for stale tips.
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL
Average delay between peer address broadcasts.
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
static constexpr unsigned int INVENTORY_BROADCAST_TARGET
Target number of tx inventory items to send per transmission.
static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS
Maximum number of transactions to consider for requesting, per peer.
static constexpr auto TXID_RELAY_DELAY
How long to delay requesting transactions via txids, if we have wtxid-relaying peers.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
Additional block download timeout per parallel downloading peer (i.e.
static constexpr double MAX_ADDR_RATE_PER_SECOND
The maximum rate of address records we're willing to process on average.
static constexpr auto PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive.
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested.
static constexpr auto GETDATA_TX_INTERVAL
How long to wait before downloading a transaction from an additional peer.
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
static const unsigned int NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS
Window, in blocks, for connecting to NODE_NETWORK_LIMITED peers.
static constexpr uint32_t MAX_GETCFHEADERS_SIZE
Maximum number of cf hashes that may be requested with one getcfheaders.
static constexpr auto BLOCK_STALLING_TIMEOUT_MAX
Maximum timeout for stalling block download.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY
SHA256("main address relay")[0:8].
static constexpr unsigned int INVENTORY_BROADCAST_MAX
Maximum number of inventory items to send per transmission.
static const unsigned int MAX_HEADERS_RESULTS
Number of headers sent in one getheaders result.
static constexpr size_t MAX_PCT_ADDR_TO_SEND
the maximum percentage of addresses from our addrman to return in response to a getaddr message.
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
static constexpr auto NONPREF_PEER_TX_DELAY
How long to delay requesting transactions from non-preferred peers.
static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND
Maximum rate of inventory items to send per second.
static const unsigned int MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK
Maximum number of outstanding CMPCTBLOCK requests for the same block.
static const int DISCOURAGEMENT_THRESHOLD
Threshold for marking a node to be discouraged, e.g.
ReachableNets g_reachable_nets
Definition: netbase.cpp:43
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:708
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: policy.h:57
static constexpr TransactionSerParams TX_NO_WITNESS
Definition: transaction.h:196
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:195
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
GenTxid ToGenTxid(const CInv &inv)
Convert a TX/WITNESS_TX/WTX CInv to a GenTxid.
Definition: protocol.cpp:207
const uint32_t MSG_WITNESS_FLAG
getdata message type flags
Definition: protocol.h:434
@ MSG_TX
Definition: protocol.h:443
@ MSG_WTX
Defined in BIP 339.
Definition: protocol.h:445
@ MSG_BLOCK
Definition: protocol.h:444
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:448
@ MSG_WITNESS_BLOCK
Defined in BIP144.
Definition: protocol.h:449
ServiceFlags
nServices flags
Definition: protocol.h:274
@ NODE_NONE
Definition: protocol.h:277
@ NODE_WITNESS
Definition: protocol.h:285
@ NODE_NETWORK_LIMITED
Definition: protocol.h:292
@ NODE_BLOOM
Definition: protocol.h:282
@ NODE_NETWORK
Definition: protocol.h:280
@ NODE_COMPACT_FILTERS
Definition: protocol.h:288
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
Definition: protocol.h:325
static const int WTXID_RELAY_VERSION
"wtxidrelay" command for wtxid-based relay starts with this version
static const int SHORT_IDS_BLOCKS_VERSION
short-id-based block download starts with this version
static const int SENDHEADERS_VERSION
"sendheaders" command and announcing blocks with headers starts with this version
static const int PROTOCOL_VERSION
network protocol versioning
static const int FEEFILTER_VERSION
"feefilter" tells peers to filter invs to you by fee starts with this version
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
static const int INVALID_CB_NO_BAN_VERSION
not banning for invalid compact blocks starts with this version
static const int BIP0031_VERSION
BIP 0031, pong message, is enabled for all versions AFTER this one.
std::chrono::microseconds GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future sampled from an exponential distribution (https://en....
Definition: random.cpp:764
constexpr auto GetRandMillis
Definition: random.h:98
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:265
reverse_range< T > reverse_iterate(T &x)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:27
#define LIMITED_STRING(obj, n)
Definition: serialize.h:515
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:352
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) unsigned char member types only.
Definition: span.h:304
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:65
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:110
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:124
std::vector< uint256 > vHave
Definition: block.h:134
bool IsNull() const
Definition: block.h:152
std::chrono::microseconds m_ping_wait
std::vector< int > vHeightInFlight
CAmount m_fee_filter_received
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
int64_t presync_height
ServiceFlags their_services
Parameters that influence chain consensus.
Definition: params.h:74
int64_t nPowTargetSpacing
Definition: params.h:112
std::chrono::seconds PowTargetSpacing() const
Definition: params.h:114
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:127
const ResultType m_result_type
Result type.
Definition: validation.h:136
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx.
Definition: validation.h:142
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:139
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:21
std::chrono::time_point< NodeClock > time_point
Definition: time.h:17
#define AssertLockNotHeld(cs)
Definition: sync.h:147
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define GUARDED_BY(x)
Definition: threadsafety.h:38
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
#define PT_GUARDED_BY(x)
Definition: threadsafety.h:39
int64_t GetTime()
Definition: time.cpp:48
constexpr int64_t count_microseconds(std::chrono::microseconds t)
Definition: time.h:56
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:54
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:23
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
Definition: timedata.cpp:42
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
#define TRACE6(context, event, a, b, c, d, e, f)
Definition: trace.h:38
ReconciliationRegisterResult
static constexpr uint32_t TXRECONCILIATION_VERSION
Supported transaction reconciliation protocol version.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
bool IsBlockMutated(const CBlock &block, bool check_witness_root)
Check if a block has been mutated (with respect to its merkle root and witness commitments).
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
AssertLockHeld(pool.cs)
arith_uint256 CalculateClaimedHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the claimed work on a given set of headers.
assert(!tx.IsCoinBase())
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:66