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