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