Bitcoin Core  22.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 <index/blockfilterindex.h>
18 #include <merkleblock.h>
19 #include <netbase.h>
20 #include <netmessagemaker.h>
21 #include <node/blockstorage.h>
22 #include <policy/fees.h>
23 #include <policy/policy.h>
24 #include <primitives/block.h>
25 #include <primitives/transaction.h>
26 #include <random.h>
27 #include <reverse_iterator.h>
28 #include <scheduler.h>
29 #include <streams.h>
30 #include <sync.h>
31 #include <tinyformat.h>
32 #include <txmempool.h>
33 #include <txorphanage.h>
34 #include <txrequest.h>
35 #include <util/check.h> // For NDEBUG compile time check
36 #include <util/strencodings.h>
37 #include <util/system.h>
38 #include <util/trace.h>
39 #include <validation.h>
40 
41 #include <algorithm>
42 #include <atomic>
43 #include <chrono>
44 #include <memory>
45 #include <optional>
46 #include <typeinfo>
47 
50 using node::fImporting;
51 using node::fPruneMode;
52 using node::fReindex;
53 
55 static constexpr auto RELAY_TX_CACHE_TIME = 15min;
57 static constexpr auto UNCONDITIONAL_RELAY_DELAY = 2min;
60 static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min;
61 static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;
65 static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
67 static constexpr auto CHAIN_SYNC_TIMEOUT{20min};
69 static constexpr auto STALE_CHECK_INTERVAL{10min};
71 static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};
73 static constexpr auto MINIMUM_CONNECT_TIME{30s};
75 static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
78 static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
81 static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
83 static constexpr auto PING_INTERVAL{2min};
85 static const unsigned int MAX_LOCATOR_SZ = 101;
87 static const unsigned int MAX_INV_SZ = 50000;
90 static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT = 100;
95 static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 5000;
97 static constexpr auto TXID_RELAY_DELAY{2s};
99 static constexpr auto NONPREF_PEER_TX_DELAY{2s};
101 static constexpr auto OVERLOADED_PEER_TX_DELAY{2s};
103 static constexpr auto GETDATA_TX_INTERVAL{60s};
105 static const unsigned int MAX_GETDATA_SZ = 1000;
107 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
109 static constexpr auto BLOCK_STALLING_TIMEOUT{2s};
112 static const unsigned int MAX_HEADERS_RESULTS = 2000;
115 static const int MAX_CMPCTBLOCK_DEPTH = 5;
117 static const int MAX_BLOCKTXN_DEPTH = 10;
122 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
124 static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1;
126 static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5;
128 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
130 static const int MAX_UNCONNECTING_HEADERS = 10;
132 static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
134 static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h};
136 static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s};
139 static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s};
143 static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s};
146 static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7;
150 static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY = 3500;
155 static_assert(INVENTORY_MAX_RECENT_RELAY >= INVENTORY_BROADCAST_PER_SECOND * UNCONDITIONAL_RELAY_DELAY / std::chrono::seconds{1}, "INVENTORY_RELAY_MAX too low");
157 static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min};
159 static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min};
161 static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
163 static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;
165 static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
167 static constexpr size_t MAX_ADDR_TO_SEND{1000};
170 static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
175 
176 // Internal stuff
177 namespace {
179 struct QueuedBlock {
181  const CBlockIndex* pindex;
183  std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
184 };
185 
198 struct Peer {
200  const NodeId m_id{0};
201 
203  Mutex m_misbehavior_mutex;
205  int m_misbehavior_score GUARDED_BY(m_misbehavior_mutex){0};
207  bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false};
208 
210  Mutex m_block_inv_mutex;
214  std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex);
218  std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex);
223  uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {};
224 
226  std::atomic<int> m_starting_height{-1};
227 
229  std::atomic<uint64_t> m_ping_nonce_sent{0};
231  std::atomic<std::chrono::microseconds> m_ping_start{0us};
233  std::atomic<bool> m_ping_queued{false};
234 
236  std::vector<CAddress> m_addrs_to_send;
246  std::unique_ptr<CRollingBloomFilter> m_addr_known;
261  std::atomic_bool m_addr_relay_enabled{false};
263  bool m_getaddr_sent{false};
265  mutable Mutex m_addr_send_times_mutex;
267  std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
269  std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
272  std::atomic_bool m_wants_addrv2{false};
274  bool m_getaddr_recvd{false};
277  double m_addr_token_bucket{1.0};
279  std::chrono::microseconds m_addr_token_timestamp{GetTime<std::chrono::microseconds>()};
281  std::atomic<uint64_t> m_addr_rate_limited{0};
283  std::atomic<uint64_t> m_addr_processed{0};
284 
286  std::set<uint256> m_orphan_work_set GUARDED_BY(g_cs_orphans);
287 
289  Mutex m_getdata_requests_mutex;
291  std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);
292 
293  explicit Peer(NodeId id)
294  : m_id(id)
295  {}
296 };
297 
298 using PeerRef = std::shared_ptr<Peer>;
299 
300 class PeerManagerImpl final : public PeerManager
301 {
302 public:
303  PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
304  BanMan* banman, ChainstateManager& chainman,
305  CTxMemPool& pool, bool ignore_incoming_txs);
306 
308  void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override;
309  void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override;
310  void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override;
311  void BlockChecked(const CBlock& block, const BlockValidationState& state) override;
312  void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override;
313 
315  void InitializeNode(CNode* pnode) override;
316  void FinalizeNode(const CNode& node) override;
317  bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override;
318  bool SendMessages(CNode* pto) override EXCLUSIVE_LOCKS_REQUIRED(pto->cs_sendProcessing);
319 
321  void StartScheduledTasks(CScheduler& scheduler) override;
322  void CheckForStaleTipAndEvictPeers() override;
323  bool FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index) override;
324  bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override;
325  bool IgnoresIncomingTxs() override { return m_ignore_incoming_txs; }
326  void SendPings() override;
327  void RelayTransaction(const uint256& txid, const uint256& wtxid) override;
328  void SetBestHeight(int height) override { m_best_height = height; };
329  void Misbehaving(const NodeId pnode, const int howmuch, const std::string& message) override;
330  void ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
331  const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override;
332 
333 private:
334  void _RelayTransaction(const uint256& txid, const uint256& wtxid)
336 
338  void ConsiderEviction(CNode& pto, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
339 
341  void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
342 
344  void ReattemptInitialBroadcast(CScheduler& scheduler);
345 
348  PeerRef GetPeerRef(NodeId id) const;
349 
352  PeerRef RemovePeer(NodeId id);
353 
364  bool MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
365  bool via_compact_block, const std::string& message = "");
366 
372  bool MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state, const std::string& message = "");
373 
380  bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer);
381 
382  void ProcessOrphanTx(std::set<uint256>& orphan_work_set) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_cs_orphans);
384  void ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
385  const std::vector<CBlockHeader>& headers,
386  bool via_compact_block);
387 
388  void SendBlockTransactions(CNode& pfrom, const CBlock& block, const BlockTransactionsRequest& req);
389 
393  void AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
395 
397  void PushNodeVersion(CNode& pnode);
398 
403  void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now);
404 
406  void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time);
407 
415  void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable);
416 
418  void MaybeSendFeefilter(CNode& node, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
419 
420  const CChainParams& m_chainparams;
421  CConnman& m_connman;
422  AddrMan& m_addrman;
424  BanMan* const m_banman;
425  ChainstateManager& m_chainman;
426  CTxMemPool& m_mempool;
427  TxRequestTracker m_txrequest GUARDED_BY(::cs_main);
428 
430  std::atomic<int> m_best_height{-1};
431 
433  std::chrono::seconds m_stale_tip_check_time{0s};
434 
436  const bool m_ignore_incoming_txs;
437 
440  bool m_initial_sync_finished{false};
441 
444  mutable Mutex m_peer_mutex;
451  std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex);
452 
454  int nSyncStarted GUARDED_BY(cs_main) = 0;
455 
462  std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main);
463 
465  int m_wtxid_relay_peers GUARDED_BY(cs_main) = 0;
466 
468  int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
469 
470  bool AlreadyHaveTx(const GenTxid& gtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
471 
506  CRollingBloomFilter m_recent_rejects GUARDED_BY(::cs_main){120'000, 0.000'001};
507  uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main);
508 
509  /*
510  * Filter for transactions that have been recently confirmed.
511  * We use this to avoid requesting transactions that have already been
512  * confirnmed.
513  *
514  * Blocks don't typically have more than 4000 transactions, so this should
515  * be at least six blocks (~1 hr) worth of transactions that we can store,
516  * inserting both a txid and wtxid for every observed transaction.
517  * If the number of transactions appearing in a block goes up, or if we are
518  * seeing getdata requests more than an hour after initial announcement, we
519  * can increase this number.
520  * The false positive rate of 1/1M should come out to less than 1
521  * transaction per day that would be inadvertently ignored (which is the
522  * same probability that we have in the reject filter).
523  */
524  Mutex m_recent_confirmed_transactions_mutex;
525  CRollingBloomFilter m_recent_confirmed_transactions GUARDED_BY(m_recent_confirmed_transactions_mutex){48'000, 0.000'001};
526 
528  bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
529 
534  void RemoveBlockRequest(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
535 
536  /* Mark a block as in flight
537  * Returns false, still setting pit, if the block was already in flight from the same peer
538  * pit will only be valid as long as the same cs_main lock is being held
539  */
540  bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
541 
542  bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
543 
547  void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
548 
549  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight GUARDED_BY(cs_main);
550 
552  std::atomic<std::chrono::seconds> m_last_tip_update{0s};
553 
555  CTransactionRef FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now) LOCKS_EXCLUDED(cs_main);
556 
557  void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(peer.m_getdata_requests_mutex) LOCKS_EXCLUDED(::cs_main);
558 
560  void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing);
561 
563  typedef std::map<uint256, CTransactionRef> MapRelay;
564  MapRelay mapRelay GUARDED_BY(cs_main);
566  std::deque<std::pair<std::chrono::microseconds, MapRelay::iterator>> g_relay_expiration GUARDED_BY(cs_main);
567 
574  void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
575 
577  std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
578 
580  int m_peers_downloading_from GUARDED_BY(cs_main) = 0;
581 
583  TxOrphanage m_orphanage;
584 
585  void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans);
586 
590  std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_cs_orphans);
592  size_t vExtraTxnForCompactIt GUARDED_BY(g_cs_orphans) = 0;
593 
595  void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
597  void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
598  bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
599 
606  bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
607  bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
608  void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv);
609 
624  bool PrepareBlockFilterRequest(CNode& peer,
625  BlockFilterType filter_type, uint32_t start_height,
626  const uint256& stop_hash, uint32_t max_height_diff,
627  const CBlockIndex*& stop_index,
628  BlockFilterIndex*& filter_index);
629 
638  void ProcessGetCFilters(CNode& peer, CDataStream& vRecv);
639 
648  void ProcessGetCFHeaders(CNode& peer, CDataStream& vRecv);
649 
658  void ProcessGetCFCheckPt(CNode& peer, CDataStream& vRecv);
659 
666  bool SetupAddressRelay(const CNode& node, Peer& peer);
667 };
668 } // namespace
669 
670 namespace {
672  int nPreferredDownload GUARDED_BY(cs_main) = 0;
673 } // namespace
674 
675 namespace {
682 struct CNodeState {
684  const CBlockIndex* pindexBestKnownBlock{nullptr};
686  uint256 hashLastUnknownBlock{};
688  const CBlockIndex* pindexLastCommonBlock{nullptr};
690  const CBlockIndex* pindexBestHeaderSent{nullptr};
692  int nUnconnectingHeaders{0};
694  bool fSyncStarted{false};
696  std::chrono::microseconds m_headers_sync_timeout{0us};
698  std::chrono::microseconds m_stalling_since{0us};
699  std::list<QueuedBlock> vBlocksInFlight;
701  std::chrono::microseconds m_downloading_since{0us};
702  int nBlocksInFlight{0};
704  bool fPreferredDownload{false};
706  bool fPreferHeaders{false};
708  bool fPreferHeaderAndIDs{false};
714  bool fProvidesHeaderAndIDs{false};
716  bool fHaveWitness{false};
718  bool fWantsCmpctWitness{false};
723  bool fSupportsDesiredCmpctVersion{false};
724 
749  struct ChainSyncTimeoutState {
751  std::chrono::seconds m_timeout{0s};
753  const CBlockIndex* m_work_header{nullptr};
755  bool m_sent_getheaders{false};
757  bool m_protect{false};
758  };
759 
760  ChainSyncTimeoutState m_chain_sync;
761 
763  int64_t m_last_block_announcement{0};
764 
766  const bool m_is_inbound;
767 
769  CRollingBloomFilter m_recently_announced_invs = CRollingBloomFilter{INVENTORY_MAX_RECENT_RELAY, 0.000001};
770 
772  bool m_wtxid_relay{false};
773 
774  CNodeState(bool is_inbound) : m_is_inbound(is_inbound) {}
775 };
776 
778 static std::map<NodeId, CNodeState> mapNodeState GUARDED_BY(cs_main);
779 
780 static CNodeState *State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
781  std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
782  if (it == mapNodeState.end())
783  return nullptr;
784  return &it->second;
785 }
786 
792 static bool IsAddrCompatible(const Peer& peer, const CAddress& addr)
793 {
794  return peer.m_wants_addrv2 || addr.IsAddrV1Compatible();
795 }
796 
797 static void AddAddressKnown(Peer& peer, const CAddress& addr)
798 {
799  assert(peer.m_addr_known);
800  peer.m_addr_known->insert(addr.GetKey());
801 }
802 
803 static void PushAddress(Peer& peer, const CAddress& addr, FastRandomContext& insecure_rand)
804 {
805  // Known checking here is only to save space from duplicates.
806  // Before sending, we'll filter it again for known addresses that were
807  // added after addresses were pushed.
808  assert(peer.m_addr_known);
809  if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) {
810  if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) {
811  peer.m_addrs_to_send[insecure_rand.randrange(peer.m_addrs_to_send.size())] = addr;
812  } else {
813  peer.m_addrs_to_send.push_back(addr);
814  }
815  }
816 }
817 
818 static void UpdatePreferredDownload(const CNode& node, CNodeState* state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
819 {
820  nPreferredDownload -= state->fPreferredDownload;
821 
822  // Whether this node should be marked as a preferred download node.
823  state->fPreferredDownload = (!node.IsInboundConn() || node.HasPermission(NetPermissionFlags::NoBan)) && !node.IsAddrFetchConn() && !node.fClient;
824 
825  nPreferredDownload += state->fPreferredDownload;
826 }
827 
828 bool PeerManagerImpl::IsBlockRequested(const uint256& hash)
829 {
830  return mapBlocksInFlight.find(hash) != mapBlocksInFlight.end();
831 }
832 
833 void PeerManagerImpl::RemoveBlockRequest(const uint256& hash)
834 {
835  auto it = mapBlocksInFlight.find(hash);
836  if (it == mapBlocksInFlight.end()) {
837  // Block was not requested
838  return;
839  }
840 
841  auto [node_id, list_it] = it->second;
842  CNodeState *state = State(node_id);
843  assert(state != nullptr);
844 
845  if (state->vBlocksInFlight.begin() == list_it) {
846  // First block on the queue was received, update the start download time for the next one
847  state->m_downloading_since = std::max(state->m_downloading_since, GetTime<std::chrono::microseconds>());
848  }
849  state->vBlocksInFlight.erase(list_it);
850 
851  state->nBlocksInFlight--;
852  if (state->nBlocksInFlight == 0) {
853  // Last validated block on the queue was received.
854  m_peers_downloading_from--;
855  }
856  state->m_stalling_since = 0us;
857  mapBlocksInFlight.erase(it);
858 }
859 
860 bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit)
861 {
862  const uint256& hash{block.GetBlockHash()};
863 
864  CNodeState *state = State(nodeid);
865  assert(state != nullptr);
866 
867  // Short-circuit most stuff in case it is from the same node
868  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
869  if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
870  if (pit) {
871  *pit = &itInFlight->second.second;
872  }
873  return false;
874  }
875 
876  // Make sure it's not listed somewhere already.
877  RemoveBlockRequest(hash);
878 
879  std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
880  {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool) : nullptr)});
881  state->nBlocksInFlight++;
882  if (state->nBlocksInFlight == 1) {
883  // We're starting a block download (batch) from this peer.
884  state->m_downloading_since = GetTime<std::chrono::microseconds>();
885  m_peers_downloading_from++;
886  }
887  itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
888  if (pit) {
889  *pit = &itInFlight->second.second;
890  }
891  return true;
892 }
893 
894 void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid)
895 {
897 
898  // Never request high-bandwidth mode from peers if we're blocks-only. Our
899  // mempool will not contain the transactions necessary to reconstruct the
900  // compact block.
901  if (m_ignore_incoming_txs) return;
902 
903  CNodeState* nodestate = State(nodeid);
904  if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
905  // Never ask from peers who can't provide witnesses.
906  return;
907  }
908  if (nodestate->fProvidesHeaderAndIDs) {
909  int num_outbound_hb_peers = 0;
910  for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
911  if (*it == nodeid) {
912  lNodesAnnouncingHeaderAndIDs.erase(it);
913  lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
914  return;
915  }
916  CNodeState *state = State(*it);
917  if (state != nullptr && !state->m_is_inbound) ++num_outbound_hb_peers;
918  }
919  if (nodestate->m_is_inbound) {
920  // If we're adding an inbound HB peer, make sure we're not removing
921  // our last outbound HB peer in the process.
922  if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 1) {
923  CNodeState *remove_node = State(lNodesAnnouncingHeaderAndIDs.front());
924  if (remove_node != nullptr && !remove_node->m_is_inbound) {
925  // Put the HB outbound peer in the second slot, so that it
926  // doesn't get removed.
927  std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
928  }
929  }
930  }
931  m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
933  uint64_t nCMPCTBLOCKVersion = 2;
934  if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
935  // As per BIP152, we only get 3 of our peers to announce
936  // blocks using compact encodings.
937  m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this, nCMPCTBLOCKVersion](CNode* pnodeStop){
938  m_connman.PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetCommonVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
939  // save BIP152 bandwidth state: we select peer to be low-bandwidth
940  pnodeStop->m_bip152_highbandwidth_to = false;
941  return true;
942  });
943  lNodesAnnouncingHeaderAndIDs.pop_front();
944  }
945  m_connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetCommonVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion));
946  // save BIP152 bandwidth state: we select peer to be high-bandwidth
947  pfrom->m_bip152_highbandwidth_to = true;
948  lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
949  return true;
950  });
951  }
952 }
953 
954 bool PeerManagerImpl::TipMayBeStale()
955 {
957  const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
958  if (m_last_tip_update.load() == 0s) {
959  m_last_tip_update = GetTime<std::chrono::seconds>();
960  }
961  return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty();
962 }
963 
964 bool PeerManagerImpl::CanDirectFetch()
965 {
966  return m_chainman.ActiveChain().Tip()->GetBlockTime() > GetAdjustedTime() - m_chainparams.GetConsensus().nPowTargetSpacing * 20;
967 }
968 
969 static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
970 {
971  if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
972  return true;
973  if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
974  return true;
975  return false;
976 }
977 
978 void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) {
979  CNodeState *state = State(nodeid);
980  assert(state != nullptr);
981 
982  if (!state->hashLastUnknownBlock.IsNull()) {
983  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
984  if (pindex && pindex->nChainWork > 0) {
985  if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
986  state->pindexBestKnownBlock = pindex;
987  }
988  state->hashLastUnknownBlock.SetNull();
989  }
990  }
991 }
992 
993 void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
994  CNodeState *state = State(nodeid);
995  assert(state != nullptr);
996 
997  ProcessBlockAvailability(nodeid);
998 
999  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
1000  if (pindex && pindex->nChainWork > 0) {
1001  // An actually better block was announced.
1002  if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1003  state->pindexBestKnownBlock = pindex;
1004  }
1005  } else {
1006  // An unknown block was announced; just assume that the latest one is the best one.
1007  state->hashLastUnknownBlock = hash;
1008  }
1009 }
1010 
1011 void PeerManagerImpl::FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller)
1012 {
1013  if (count == 0)
1014  return;
1015 
1016  vBlocks.reserve(vBlocks.size() + count);
1017  CNodeState *state = State(nodeid);
1018  assert(state != nullptr);
1019 
1020  // Make sure pindexBestKnownBlock is up to date, we'll need it.
1021  ProcessBlockAvailability(nodeid);
1022 
1023  if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
1024  // This peer has nothing interesting.
1025  return;
1026  }
1027 
1028  if (state->pindexLastCommonBlock == nullptr) {
1029  // Bootstrap quickly by guessing a parent of our best tip is the forking point.
1030  // Guessing wrong in either direction is not a problem.
1031  state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())];
1032  }
1033 
1034  // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
1035  // of its current tip anymore. Go back enough to fix that.
1036  state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
1037  if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
1038  return;
1039 
1040  const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
1041  std::vector<const CBlockIndex*> vToFetch;
1042  const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
1043  // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
1044  // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
1045  // download that next block if the window were 1 larger.
1046  int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1047  int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1048  NodeId waitingfor = -1;
1049  while (pindexWalk->nHeight < nMaxHeight) {
1050  // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
1051  // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
1052  // as iterating over ~100 CBlockIndex* entries anyway.
1053  int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
1054  vToFetch.resize(nToFetch);
1055  pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
1056  vToFetch[nToFetch - 1] = pindexWalk;
1057  for (unsigned int i = nToFetch - 1; i > 0; i--) {
1058  vToFetch[i - 1] = vToFetch[i]->pprev;
1059  }
1060 
1061  // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
1062  // are not yet downloaded and not in flight to vBlocks. In the meantime, update
1063  // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
1064  // already part of our chain (and therefore don't need it even if pruned).
1065  for (const CBlockIndex* pindex : vToFetch) {
1066  if (!pindex->IsValid(BLOCK_VALID_TREE)) {
1067  // We consider the chain that this peer is on invalid.
1068  return;
1069  }
1070  if (!State(nodeid)->fHaveWitness && DeploymentActiveAt(*pindex, consensusParams, Consensus::DEPLOYMENT_SEGWIT)) {
1071  // We wouldn't download this block or its descendants from this peer.
1072  return;
1073  }
1074  if (pindex->nStatus & BLOCK_HAVE_DATA || m_chainman.ActiveChain().Contains(pindex)) {
1075  if (pindex->HaveTxsDownloaded())
1076  state->pindexLastCommonBlock = pindex;
1077  } else if (!IsBlockRequested(pindex->GetBlockHash())) {
1078  // The block is not already downloaded, and not yet in flight.
1079  if (pindex->nHeight > nWindowEnd) {
1080  // We reached the end of the window.
1081  if (vBlocks.size() == 0 && waitingfor != nodeid) {
1082  // We aren't able to fetch anything, but we would be if the download window was one larger.
1083  nodeStaller = waitingfor;
1084  }
1085  return;
1086  }
1087  vBlocks.push_back(pindex);
1088  if (vBlocks.size() == count) {
1089  return;
1090  }
1091  } else if (waitingfor == -1) {
1092  // This is the first already-in-flight block.
1093  waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
1094  }
1095  }
1096  }
1097 }
1098 
1099 } // namespace
1100 
1101 void PeerManagerImpl::PushNodeVersion(CNode& pnode)
1102 {
1103  // Note that pnode->GetLocalServices() is a reflection of the local
1104  // services we were offering when the CNode object was created for this
1105  // peer.
1106  uint64_t my_services{pnode.GetLocalServices()};
1107  const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())};
1108  uint64_t nonce = pnode.GetLocalNonce();
1109  const int nNodeStartingHeight{m_best_height};
1110  NodeId nodeid = pnode.GetId();
1111  CAddress addr = pnode.addr;
1112 
1113  CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService();
1114  uint64_t your_services{addr.nServices};
1115 
1116  const bool tx_relay = !m_ignore_incoming_txs && pnode.m_tx_relay != nullptr && !pnode.IsFeelerConn();
1117  m_connman.PushMessage(&pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime,
1118  your_services, addr_you, // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime)
1119  my_services, CService(), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime)
1120  nonce, strSubVersion, nNodeStartingHeight, tx_relay));
1121 
1122  if (fLogIPs) {
1123  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);
1124  } else {
1125  LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid);
1126  }
1127 }
1128 
1129 void PeerManagerImpl::AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
1130 {
1131  AssertLockHeld(::cs_main); // For m_txrequest
1132  NodeId nodeid = node.GetId();
1133  if (!node.HasPermission(NetPermissionFlags::Relay) && m_txrequest.Count(nodeid) >= MAX_PEER_TX_ANNOUNCEMENTS) {
1134  // Too many queued announcements from this peer
1135  return;
1136  }
1137  const CNodeState* state = State(nodeid);
1138 
1139  // Decide the TxRequestTracker parameters for this announcement:
1140  // - "preferred": if fPreferredDownload is set (= outbound, or NetPermissionFlags::NoBan permission)
1141  // - "reqtime": current time plus delays for:
1142  // - NONPREF_PEER_TX_DELAY for announcements from non-preferred connections
1143  // - TXID_RELAY_DELAY for txid announcements while wtxid peers are available
1144  // - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least
1145  // MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay).
1146  auto delay{0us};
1147  const bool preferred = state->fPreferredDownload;
1148  if (!preferred) delay += NONPREF_PEER_TX_DELAY;
1149  if (!gtxid.IsWtxid() && m_wtxid_relay_peers > 0) delay += TXID_RELAY_DELAY;
1150  const bool overloaded = !node.HasPermission(NetPermissionFlags::Relay) &&
1151  m_txrequest.CountInFlight(nodeid) >= MAX_PEER_TX_REQUEST_IN_FLIGHT;
1152  if (overloaded) delay += OVERLOADED_PEER_TX_DELAY;
1153  m_txrequest.ReceivedInv(nodeid, gtxid, preferred, current_time + delay);
1154 }
1155 
1156 // This function is used for testing the stale tip eviction logic, see
1157 // denialofservice_tests.cpp
1158 void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
1159 {
1160  LOCK(cs_main);
1161  CNodeState *state = State(node);
1162  if (state) state->m_last_block_announcement = time_in_seconds;
1163 }
1164 
1165 void PeerManagerImpl::InitializeNode(CNode *pnode)
1166 {
1167  NodeId nodeid = pnode->GetId();
1168  {
1169  LOCK(cs_main);
1170  mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(pnode->IsInboundConn()));
1171  assert(m_txrequest.Count(nodeid) == 0);
1172  }
1173  {
1174  PeerRef peer = std::make_shared<Peer>(nodeid);
1175  LOCK(m_peer_mutex);
1176  m_peer_map.emplace_hint(m_peer_map.end(), nodeid, std::move(peer));
1177  }
1178  if (!pnode->IsInboundConn()) {
1179  PushNodeVersion(*pnode);
1180  }
1181 }
1182 
1183 void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler)
1184 {
1185  std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs();
1186 
1187  for (const auto& txid : unbroadcast_txids) {
1188  CTransactionRef tx = m_mempool.get(txid);
1189 
1190  if (tx != nullptr) {
1191  LOCK(cs_main);
1192  _RelayTransaction(txid, tx->GetWitnessHash());
1193  } else {
1194  m_mempool.RemoveUnbroadcastTx(txid, true);
1195  }
1196  }
1197 
1198  // Schedule next run for 10-15 minutes in the future.
1199  // We add randomness on every cycle to avoid the possibility of P2P fingerprinting.
1200  const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
1201  scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1202 }
1203 
1204 void PeerManagerImpl::FinalizeNode(const CNode& node)
1205 {
1206  NodeId nodeid = node.GetId();
1207  int misbehavior{0};
1208  {
1209  LOCK(cs_main);
1210  {
1211  // We remove the PeerRef from g_peer_map here, but we don't always
1212  // destruct the Peer. Sometimes another thread is still holding a
1213  // PeerRef, so the refcount is >= 1. Be careful not to do any
1214  // processing here that assumes Peer won't be changed before it's
1215  // destructed.
1216  PeerRef peer = RemovePeer(nodeid);
1217  assert(peer != nullptr);
1218  misbehavior = WITH_LOCK(peer->m_misbehavior_mutex, return peer->m_misbehavior_score);
1219  }
1220  CNodeState *state = State(nodeid);
1221  assert(state != nullptr);
1222 
1223  if (state->fSyncStarted)
1224  nSyncStarted--;
1225 
1226  for (const QueuedBlock& entry : state->vBlocksInFlight) {
1227  mapBlocksInFlight.erase(entry.pindex->GetBlockHash());
1228  }
1229  WITH_LOCK(g_cs_orphans, m_orphanage.EraseForPeer(nodeid));
1230  m_txrequest.DisconnectedPeer(nodeid);
1231  nPreferredDownload -= state->fPreferredDownload;
1232  m_peers_downloading_from -= (state->nBlocksInFlight != 0);
1233  assert(m_peers_downloading_from >= 0);
1234  m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
1235  assert(m_outbound_peers_with_protect_from_disconnect >= 0);
1236  m_wtxid_relay_peers -= state->m_wtxid_relay;
1237  assert(m_wtxid_relay_peers >= 0);
1238 
1239  mapNodeState.erase(nodeid);
1240 
1241  if (mapNodeState.empty()) {
1242  // Do a consistency check after the last peer is removed.
1243  assert(mapBlocksInFlight.empty());
1244  assert(nPreferredDownload == 0);
1245  assert(m_peers_downloading_from == 0);
1246  assert(m_outbound_peers_with_protect_from_disconnect == 0);
1247  assert(m_wtxid_relay_peers == 0);
1248  assert(m_txrequest.Size() == 0);
1249  assert(m_orphanage.Size() == 0);
1250  }
1251  } // cs_main
1252  if (node.fSuccessfullyConnected && misbehavior == 0 &&
1253  !node.IsBlockOnlyConn() && !node.IsInboundConn()) {
1254  // Only change visible addrman state for full outbound peers. We don't
1255  // call Connected() for feeler connections since they don't have
1256  // fSuccessfullyConnected set.
1257  m_addrman.Connected(node.addr);
1258  }
1259  LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
1260 }
1261 
1262 PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const
1263 {
1264  LOCK(m_peer_mutex);
1265  auto it = m_peer_map.find(id);
1266  return it != m_peer_map.end() ? it->second : nullptr;
1267 }
1268 
1269 PeerRef PeerManagerImpl::RemovePeer(NodeId id)
1270 {
1271  PeerRef ret;
1272  LOCK(m_peer_mutex);
1273  auto it = m_peer_map.find(id);
1274  if (it != m_peer_map.end()) {
1275  ret = std::move(it->second);
1276  m_peer_map.erase(it);
1277  }
1278  return ret;
1279 }
1280 
1281 bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const
1282 {
1283  {
1284  LOCK(cs_main);
1285  CNodeState* state = State(nodeid);
1286  if (state == nullptr)
1287  return false;
1288  stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
1289  stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
1290  for (const QueuedBlock& queue : state->vBlocksInFlight) {
1291  if (queue.pindex)
1292  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
1293  }
1294  }
1295 
1296  PeerRef peer = GetPeerRef(nodeid);
1297  if (peer == nullptr) return false;
1298  stats.m_starting_height = peer->m_starting_height;
1299  // It is common for nodes with good ping times to suddenly become lagged,
1300  // due to a new block arriving or other large transfer.
1301  // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
1302  // since pingtime does not update until the ping is complete, which might take a while.
1303  // So, if a ping is taking an unusually long time in flight,
1304  // the caller can immediately detect that this is happening.
1305  auto ping_wait{0us};
1306  if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) {
1307  ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
1308  }
1309 
1310  stats.m_ping_wait = ping_wait;
1311  stats.m_addr_processed = peer->m_addr_processed.load();
1312  stats.m_addr_rate_limited = peer->m_addr_rate_limited.load();
1313  stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load();
1314 
1315  return true;
1316 }
1317 
1318 void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx)
1319 {
1320  size_t max_extra_txn = gArgs.GetIntArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
1321  if (max_extra_txn <= 0)
1322  return;
1323  if (!vExtraTxnForCompact.size())
1324  vExtraTxnForCompact.resize(max_extra_txn);
1325  vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
1326  vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
1327 }
1328 
1329 void PeerManagerImpl::Misbehaving(const NodeId pnode, const int howmuch, const std::string& message)
1330 {
1331  assert(howmuch > 0);
1332 
1333  PeerRef peer = GetPeerRef(pnode);
1334  if (peer == nullptr) return;
1335 
1336  LOCK(peer->m_misbehavior_mutex);
1337  const int score_before{peer->m_misbehavior_score};
1338  peer->m_misbehavior_score += howmuch;
1339  const int score_now{peer->m_misbehavior_score};
1340 
1341  const std::string message_prefixed = message.empty() ? "" : (": " + message);
1342  std::string warning;
1343 
1344  if (score_now >= DISCOURAGEMENT_THRESHOLD && score_before < DISCOURAGEMENT_THRESHOLD) {
1345  warning = " DISCOURAGE THRESHOLD EXCEEDED";
1346  peer->m_should_discourage = true;
1347  }
1348 
1349  LogPrint(BCLog::NET, "Misbehaving: peer=%d (%d -> %d)%s%s\n",
1350  pnode, score_before, score_now, warning, message_prefixed);
1351 }
1352 
1353 bool PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
1354  bool via_compact_block, const std::string& message)
1355 {
1356  switch (state.GetResult()) {
1358  break;
1359  // The node is providing invalid data:
1362  if (!via_compact_block) {
1363  Misbehaving(nodeid, 100, message);
1364  return true;
1365  }
1366  break;
1368  {
1369  LOCK(cs_main);
1370  CNodeState *node_state = State(nodeid);
1371  if (node_state == nullptr) {
1372  break;
1373  }
1374 
1375  // Discourage outbound (but not inbound) peers if on an invalid chain.
1376  // Exempt HB compact block peers. Manual connections are always protected from discouragement.
1377  if (!via_compact_block && !node_state->m_is_inbound) {
1378  Misbehaving(nodeid, 100, message);
1379  return true;
1380  }
1381  break;
1382  }
1386  Misbehaving(nodeid, 100, message);
1387  return true;
1388  // Conflicting (but not necessarily invalid) data or different policy:
1390  // TODO: Handle this much more gracefully (10 DoS points is super arbitrary)
1391  Misbehaving(nodeid, 10, message);
1392  return true;
1395  break;
1396  }
1397  if (message != "") {
1398  LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
1399  }
1400  return false;
1401 }
1402 
1403 bool PeerManagerImpl::MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state, const std::string& message)
1404 {
1405  switch (state.GetResult()) {
1407  break;
1408  // The node is providing invalid data:
1410  Misbehaving(nodeid, 100, message);
1411  return true;
1412  // Conflicting (but not necessarily invalid) data or different policy:
1423  break;
1424  }
1425  if (message != "") {
1426  LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
1427  }
1428  return false;
1429 }
1430 
1431 bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
1432 {
1434  if (m_chainman.ActiveChain().Contains(pindex)) return true;
1435  return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
1438 }
1439 
1440 bool PeerManagerImpl::FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index)
1441 {
1442  if (fImporting || fReindex) return false;
1443 
1444  LOCK(cs_main);
1445  // Ensure this peer exists and hasn't been disconnected
1446  CNodeState* state = State(id);
1447  if (state == nullptr) return false;
1448  // Ignore pre-segwit peers
1449  if (!state->fHaveWitness) return false;
1450 
1451  // Mark block as in-flight unless it already is
1452  if (!BlockRequested(id, index)) return false;
1453 
1454  // Construct message to request the block
1455  std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)};
1456 
1457  // Send block request message to the peer
1458  bool success = m_connman.ForNode(id, [this, &invs](CNode* node) {
1459  const CNetMsgMaker msgMaker(node->GetCommonVersion());
1460  this->m_connman.PushMessage(node, msgMaker.Make(NetMsgType::GETDATA, invs));
1461  return true;
1462  });
1463 
1464  if (success) {
1465  LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1466  hash.ToString(), id);
1467  } else {
1468  RemoveBlockRequest(hash);
1469  LogPrint(BCLog::NET, "Failed to request block %s from peer=%d\n",
1470  hash.ToString(), id);
1471  }
1472  return success;
1473 }
1474 
1475 std::unique_ptr<PeerManager> PeerManager::make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
1476  BanMan* banman, ChainstateManager& chainman,
1477  CTxMemPool& pool, bool ignore_incoming_txs)
1478 {
1479  return std::make_unique<PeerManagerImpl>(chainparams, connman, addrman, banman, chainman, pool, ignore_incoming_txs);
1480 }
1481 
1482 PeerManagerImpl::PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
1483  BanMan* banman, ChainstateManager& chainman,
1484  CTxMemPool& pool, bool ignore_incoming_txs)
1485  : m_chainparams(chainparams),
1486  m_connman(connman),
1487  m_addrman(addrman),
1488  m_banman(banman),
1489  m_chainman(chainman),
1490  m_mempool(pool),
1491  m_ignore_incoming_txs(ignore_incoming_txs)
1492 {
1493 }
1494 
1495 void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler)
1496 {
1497  // Stale tip checking and peer eviction are on two different timers, but we
1498  // don't want them to get out of sync due to drift in the scheduler, so we
1499  // combine them in one function and schedule at the quicker (peer-eviction)
1500  // timer.
1501  static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
1502  scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL});
1503 
1504  // schedule next run for 10-15 minutes in the future
1505  const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
1506  scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1507 }
1508 
1514 void PeerManagerImpl::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex)
1515 {
1516  m_orphanage.EraseForBlock(*pblock);
1517  m_last_tip_update = GetTime<std::chrono::seconds>();
1518 
1519  {
1520  LOCK(m_recent_confirmed_transactions_mutex);
1521  for (const auto& ptx : pblock->vtx) {
1522  m_recent_confirmed_transactions.insert(ptx->GetHash());
1523  if (ptx->GetHash() != ptx->GetWitnessHash()) {
1524  m_recent_confirmed_transactions.insert(ptx->GetWitnessHash());
1525  }
1526  }
1527  }
1528  {
1529  LOCK(cs_main);
1530  for (const auto& ptx : pblock->vtx) {
1531  m_txrequest.ForgetTxHash(ptx->GetHash());
1532  m_txrequest.ForgetTxHash(ptx->GetWitnessHash());
1533  }
1534  }
1535 }
1536 
1537 void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex)
1538 {
1539  // To avoid relay problems with transactions that were previously
1540  // confirmed, clear our filter of recently confirmed transactions whenever
1541  // there's a reorg.
1542  // This means that in a 1-block reorg (where 1 block is disconnected and
1543  // then another block reconnected), our filter will drop to having only one
1544  // block's worth of transactions in it, but that should be fine, since
1545  // presumably the most common case of relaying a confirmed transaction
1546  // should be just after a new block containing it is found.
1547  LOCK(m_recent_confirmed_transactions_mutex);
1548  m_recent_confirmed_transactions.reset();
1549 }
1550 
1551 // All of the following cache a recent block, and are protected by cs_most_recent_block
1553 static std::shared_ptr<const CBlock> most_recent_block GUARDED_BY(cs_most_recent_block);
1554 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block GUARDED_BY(cs_most_recent_block);
1555 static uint256 most_recent_block_hash GUARDED_BY(cs_most_recent_block);
1556 static bool fWitnessesPresentInMostRecentCompactBlock GUARDED_BY(cs_most_recent_block);
1557 
1562 void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)
1563 {
1564  std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
1565  const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
1566 
1567  LOCK(cs_main);
1568 
1569  static int nHighestFastAnnounce = 0;
1570  if (pindex->nHeight <= nHighestFastAnnounce)
1571  return;
1572  nHighestFastAnnounce = pindex->nHeight;
1573 
1574  bool fWitnessEnabled = DeploymentActiveAt(*pindex, m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT);
1575  uint256 hashBlock(pblock->GetHash());
1576 
1577  {
1579  most_recent_block_hash = hashBlock;
1580  most_recent_block = pblock;
1581  most_recent_compact_block = pcmpctblock;
1582  fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
1583  }
1584 
1585  m_connman.ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1587 
1588  // TODO: Avoid the repeated-serialization here
1589  if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
1590  return;
1591  ProcessBlockAvailability(pnode->GetId());
1592  CNodeState &state = *State(pnode->GetId());
1593  // If the peer has, or we announced to them the previous block already,
1594  // but we don't think they have this one, go ahead and announce it
1595  if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
1596  !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
1597 
1598  LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock",
1599  hashBlock.ToString(), pnode->GetId());
1600  m_connman.PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
1601  state.pindexBestHeaderSent = pindex;
1602  }
1603  });
1604 }
1605 
1610 void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
1611 {
1612  SetBestHeight(pindexNew->nHeight);
1613  SetServiceFlagsIBDCache(!fInitialDownload);
1614 
1615  // Don't relay inventory during initial block download.
1616  if (fInitialDownload) return;
1617 
1618  // Find the hashes of all blocks that weren't previously in the best chain.
1619  std::vector<uint256> vHashes;
1620  const CBlockIndex *pindexToAnnounce = pindexNew;
1621  while (pindexToAnnounce != pindexFork) {
1622  vHashes.push_back(pindexToAnnounce->GetBlockHash());
1623  pindexToAnnounce = pindexToAnnounce->pprev;
1624  if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
1625  // Limit announcements in case of a huge reorganization.
1626  // Rely on the peer's synchronization mechanism in that case.
1627  break;
1628  }
1629  }
1630 
1631  {
1632  LOCK(m_peer_mutex);
1633  for (auto& it : m_peer_map) {
1634  Peer& peer = *it.second;
1635  LOCK(peer.m_block_inv_mutex);
1636  for (const uint256& hash : reverse_iterate(vHashes)) {
1637  peer.m_blocks_for_headers_relay.push_back(hash);
1638  }
1639  }
1640  }
1641 
1642  m_connman.WakeMessageHandler();
1643 }
1644 
1649 void PeerManagerImpl::BlockChecked(const CBlock& block, const BlockValidationState& state)
1650 {
1651  LOCK(cs_main);
1652 
1653  const uint256 hash(block.GetHash());
1654  std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
1655 
1656  // If the block failed validation, we know where it came from and we're still connected
1657  // to that peer, maybe punish.
1658  if (state.IsInvalid() &&
1659  it != mapBlockSource.end() &&
1660  State(it->second.first)) {
1661  MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second);
1662  }
1663  // Check that:
1664  // 1. The block is valid
1665  // 2. We're not in initial block download
1666  // 3. This is currently the best block we're aware of. We haven't updated
1667  // the tip yet so we have no way to check this directly here. Instead we
1668  // just check that there are currently no other blocks in flight.
1669  else if (state.IsValid() &&
1670  !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
1671  mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
1672  if (it != mapBlockSource.end()) {
1673  MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
1674  }
1675  }
1676  if (it != mapBlockSource.end())
1677  mapBlockSource.erase(it);
1678 }
1679 
1681 //
1682 // Messages
1683 //
1684 
1685 
1686 bool PeerManagerImpl::AlreadyHaveTx(const GenTxid& gtxid)
1687 {
1688  if (m_chainman.ActiveChain().Tip()->GetBlockHash() != hashRecentRejectsChainTip) {
1689  // If the chain tip has changed previously rejected transactions
1690  // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
1691  // or a double-spend. Reset the rejects filter and give those
1692  // txs a second chance.
1693  hashRecentRejectsChainTip = m_chainman.ActiveChain().Tip()->GetBlockHash();
1694  m_recent_rejects.reset();
1695  }
1696 
1697  const uint256& hash = gtxid.GetHash();
1698 
1699  if (m_orphanage.HaveTx(gtxid)) return true;
1700 
1701  {
1702  LOCK(m_recent_confirmed_transactions_mutex);
1703  if (m_recent_confirmed_transactions.contains(hash)) return true;
1704  }
1705 
1706  return m_recent_rejects.contains(hash) || m_mempool.exists(gtxid);
1707 }
1708 
1709 bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash)
1710 {
1711  return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
1712 }
1713 
1714 void PeerManagerImpl::SendPings()
1715 {
1716  LOCK(m_peer_mutex);
1717  for(auto& it : m_peer_map) it.second->m_ping_queued = true;
1718 }
1719 
1720 void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid)
1721 {
1722  WITH_LOCK(cs_main, _RelayTransaction(txid, wtxid););
1723 }
1724 
1725 void PeerManagerImpl::_RelayTransaction(const uint256& txid, const uint256& wtxid)
1726 {
1727  m_connman.ForEachNode([&txid, &wtxid](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1729 
1730  CNodeState* state = State(pnode->GetId());
1731  if (state == nullptr) return;
1732  if (state->m_wtxid_relay) {
1733  pnode->PushTxInventory(wtxid);
1734  } else {
1735  pnode->PushTxInventory(txid);
1736  }
1737  });
1738 }
1739 
1740 void PeerManagerImpl::RelayAddress(NodeId originator,
1741  const CAddress& addr,
1742  bool fReachable)
1743 {
1744  // We choose the same nodes within a given 24h window (if the list of connected
1745  // nodes does not change) and we don't relay to nodes that already know an
1746  // address. So within 24h we will likely relay a given address once. This is to
1747  // prevent a peer from unjustly giving their address better propagation by sending
1748  // it to us repeatedly.
1749 
1750  if (!fReachable && !addr.IsRelayable()) return;
1751 
1752  // Relay to a limited number of other nodes
1753  // Use deterministic randomness to send to the same nodes for 24 hours
1754  // at a time so the m_addr_knowns of the chosen nodes prevent repeats
1755  const uint64_t hashAddr{addr.GetHash()};
1756  const CSipHasher hasher{m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr).Write((GetTime() + hashAddr) / (24 * 60 * 60))};
1757  FastRandomContext insecure_rand;
1758 
1759  // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers.
1760  unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
1761 
1762  std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}};
1763  assert(nRelayNodes <= best.size());
1764 
1765  LOCK(m_peer_mutex);
1766 
1767  for (auto& [id, peer] : m_peer_map) {
1768  if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) {
1769  uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
1770  for (unsigned int i = 0; i < nRelayNodes; i++) {
1771  if (hashKey > best[i].first) {
1772  std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
1773  best[i] = std::make_pair(hashKey, peer.get());
1774  break;
1775  }
1776  }
1777  }
1778  };
1779 
1780  for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
1781  PushAddress(*best[i].second, addr, insecure_rand);
1782  }
1783 }
1784 
1785 void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
1786 {
1787  std::shared_ptr<const CBlock> a_recent_block;
1788  std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1789  bool fWitnessesPresentInARecentCompactBlock;
1790  {
1792  a_recent_block = most_recent_block;
1793  a_recent_compact_block = most_recent_compact_block;
1794  fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1795  }
1796 
1797  bool need_activate_chain = false;
1798  {
1799  LOCK(cs_main);
1800  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
1801  if (pindex) {
1802  if (pindex->HaveTxsDownloaded() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
1803  pindex->IsValid(BLOCK_VALID_TREE)) {
1804  // If we have the block and all of its parents, but have not yet validated it,
1805  // we might be in the middle of connecting it (ie in the unlock of cs_main
1806  // before ActivateBestChain but after AcceptBlock).
1807  // In this case, we need to run ActivateBestChain prior to checking the relay
1808  // conditions below.
1809  need_activate_chain = true;
1810  }
1811  }
1812  } // release cs_main before calling ActivateBestChain
1813  if (need_activate_chain) {
1814  BlockValidationState state;
1815  if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
1816  LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
1817  }
1818  }
1819 
1820  LOCK(cs_main);
1821  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
1822  if (!pindex) {
1823  return;
1824  }
1825  if (!BlockRequestAllowed(pindex)) {
1826  LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId());
1827  return;
1828  }
1829  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
1830  // disconnect node in case we have reached the outbound limit for serving historical blocks
1831  if (m_connman.OutboundTargetReached(true) &&
1832  (((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&
1833  !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target
1834  ) {
1835  LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom.GetId());
1836  pfrom.fDisconnect = true;
1837  return;
1838  }
1839  // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
1840  if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && (
1841  (((pfrom.GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom.GetLocalServices() & 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 */) )
1842  )) {
1843  LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, disconnect peer=%d\n", pfrom.GetId());
1844  //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
1845  pfrom.fDisconnect = true;
1846  return;
1847  }
1848  // Pruned nodes may have deleted the block, so check whether
1849  // it's available before trying to send.
1850  if (!(pindex->nStatus & BLOCK_HAVE_DATA)) {
1851  return;
1852  }
1853  std::shared_ptr<const CBlock> pblock;
1854  if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
1855  pblock = a_recent_block;
1856  } else if (inv.IsMsgWitnessBlk()) {
1857  // Fast-path: in this case it is possible to serve the block directly from disk,
1858  // as the network format matches the format on disk
1859  std::vector<uint8_t> block_data;
1860  if (!ReadRawBlockFromDisk(block_data, pindex, m_chainparams.MessageStart())) {
1861  assert(!"cannot load block from disk");
1862  }
1863  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCK, Span{block_data}));
1864  // Don't set pblock as we've sent the block
1865  } else {
1866  // Send block from disk
1867  std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1868  if (!ReadBlockFromDisk(*pblockRead, pindex, m_chainparams.GetConsensus())) {
1869  assert(!"cannot load block from disk");
1870  }
1871  pblock = pblockRead;
1872  }
1873  if (pblock) {
1874  if (inv.IsMsgBlk()) {
1875  m_connman.PushMessage(&pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1876  } else if (inv.IsMsgWitnessBlk()) {
1877  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1878  } else if (inv.IsMsgFilteredBlk()) {
1879  bool sendMerkleBlock = false;
1880  CMerkleBlock merkleBlock;
1881  if (pfrom.m_tx_relay != nullptr) {
1882  LOCK(pfrom.m_tx_relay->cs_filter);
1883  if (pfrom.m_tx_relay->pfilter) {
1884  sendMerkleBlock = true;
1885  merkleBlock = CMerkleBlock(*pblock, *pfrom.m_tx_relay->pfilter);
1886  }
1887  }
1888  if (sendMerkleBlock) {
1889  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1890  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1891  // This avoids hurting performance by pointlessly requiring a round-trip
1892  // Note that there is currently no way for a node to request any single transactions we didn't send here -
1893  // they must either disconnect and retry or request the full block.
1894  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1895  // however we MUST always provide at least what the remote peer needs
1896  typedef std::pair<unsigned int, uint256> PairType;
1897  for (PairType& pair : merkleBlock.vMatchedTxn)
1898  m_connman.PushMessage(&pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1899  }
1900  // else
1901  // no response
1902  } else if (inv.IsMsgCmpctBlk()) {
1903  // If a peer is asking for old blocks, we're almost guaranteed
1904  // they won't have a useful mempool to match against a compact block,
1905  // and we don't feel like constructing the object for them, so
1906  // instead we respond with the full, non-compact block.
1907  bool fPeerWantsWitness = State(pfrom.GetId())->fWantsCmpctWitness;
1908  int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1909  if (CanDirectFetch() && pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_CMPCTBLOCK_DEPTH) {
1910  if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
1911  m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1912  } else {
1913  CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1914  m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1915  }
1916  } else {
1917  m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1918  }
1919  }
1920  }
1921 
1922  {
1923  LOCK(peer.m_block_inv_mutex);
1924  // Trigger the peer node to send a getblocks request for the next batch of inventory
1925  if (inv.hash == peer.m_continuation_block) {
1926  // Send immediately. This must send even if redundant,
1927  // and we want it right after the last block so they don't
1928  // wait for other stuff first.
1929  std::vector<CInv> vInv;
1930  vInv.push_back(CInv(MSG_BLOCK, m_chainman.ActiveChain().Tip()->GetBlockHash()));
1931  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1932  peer.m_continuation_block.SetNull();
1933  }
1934  }
1935 }
1936 
1937 CTransactionRef PeerManagerImpl::FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now)
1938 {
1939  auto txinfo = m_mempool.info(gtxid);
1940  if (txinfo.tx) {
1941  // If a TX could have been INVed in reply to a MEMPOOL request,
1942  // or is older than UNCONDITIONAL_RELAY_DELAY, permit the request
1943  // unconditionally.
1944  if ((mempool_req.count() && txinfo.m_time <= mempool_req) || txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
1945  return std::move(txinfo.tx);
1946  }
1947  }
1948 
1949  {
1950  LOCK(cs_main);
1951  // Otherwise, the transaction must have been announced recently.
1952  if (State(peer.GetId())->m_recently_announced_invs.contains(gtxid.GetHash())) {
1953  // If it was, it can be relayed from either the mempool...
1954  if (txinfo.tx) return std::move(txinfo.tx);
1955  // ... or the relay pool.
1956  auto mi = mapRelay.find(gtxid.GetHash());
1957  if (mi != mapRelay.end()) return mi->second;
1958  }
1959  }
1960 
1961  return {};
1962 }
1963 
1964 void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
1965 {
1967 
1968  std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
1969  std::vector<CInv> vNotFound;
1970  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
1971 
1972  const auto now{GetTime<std::chrono::seconds>()};
1973  // Get last mempool request time
1974  const auto mempool_req = pfrom.m_tx_relay != nullptr ? pfrom.m_tx_relay->m_last_mempool_req.load() : std::chrono::seconds::min();
1975 
1976  // Process as many TX items from the front of the getdata queue as
1977  // possible, since they're common and it's efficient to batch process
1978  // them.
1979  while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) {
1980  if (interruptMsgProc) return;
1981  // The send buffer provides backpressure. If there's no space in
1982  // the buffer, pause processing until the next call.
1983  if (pfrom.fPauseSend) break;
1984 
1985  const CInv &inv = *it++;
1986 
1987  if (pfrom.m_tx_relay == nullptr) {
1988  // Ignore GETDATA requests for transactions from blocks-only peers.
1989  continue;
1990  }
1991 
1992  CTransactionRef tx = FindTxForGetData(pfrom, ToGenTxid(inv), mempool_req, now);
1993  if (tx) {
1994  // WTX and WITNESS_TX imply we serialize with witness
1995  int nSendFlags = (inv.IsMsgTx() ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1996  m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *tx));
1997  m_mempool.RemoveUnbroadcastTx(tx->GetHash());
1998  // As we're going to send tx, make sure its unconfirmed parents are made requestable.
1999  std::vector<uint256> parent_ids_to_add;
2000  {
2001  LOCK(m_mempool.cs);
2002  auto txiter = m_mempool.GetIter(tx->GetHash());
2003  if (txiter) {
2004  const CTxMemPoolEntry::Parents& parents = (*txiter)->GetMemPoolParentsConst();
2005  parent_ids_to_add.reserve(parents.size());
2006  for (const CTxMemPoolEntry& parent : parents) {
2007  if (parent.GetTime() > now - UNCONDITIONAL_RELAY_DELAY) {
2008  parent_ids_to_add.push_back(parent.GetTx().GetHash());
2009  }
2010  }
2011  }
2012  }
2013  for (const uint256& parent_txid : parent_ids_to_add) {
2014  // Relaying a transaction with a recent but unconfirmed parent.
2015  if (WITH_LOCK(pfrom.m_tx_relay->cs_tx_inventory, return !pfrom.m_tx_relay->filterInventoryKnown.contains(parent_txid))) {
2016  LOCK(cs_main);
2017  State(pfrom.GetId())->m_recently_announced_invs.insert(parent_txid);
2018  }
2019  }
2020  } else {
2021  vNotFound.push_back(inv);
2022  }
2023  }
2024 
2025  // Only process one BLOCK item per call, since they're uncommon and can be
2026  // expensive to process.
2027  if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
2028  const CInv &inv = *it++;
2029  if (inv.IsGenBlkMsg()) {
2030  ProcessGetBlockData(pfrom, peer, inv);
2031  }
2032  // else: If the first item on the queue is an unknown type, we erase it
2033  // and continue processing the queue on the next call.
2034  }
2035 
2036  peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
2037 
2038  if (!vNotFound.empty()) {
2039  // Let the peer know that we didn't find what it asked for, so it doesn't
2040  // have to wait around forever.
2041  // SPV clients care about this message: it's needed when they are
2042  // recursively walking the dependencies of relevant unconfirmed
2043  // transactions. SPV clients want to do that because they want to know
2044  // about (and store and rebroadcast and risk analyze) the dependencies
2045  // of transactions relevant to them, without having to download the
2046  // entire memory pool.
2047  // Also, other nodes can use these messages to automatically request a
2048  // transaction from some other peer that annnounced it, and stop
2049  // waiting for us to respond.
2050  // In normal operation, we often send NOTFOUND messages for parents of
2051  // transactions that we relay; if a peer is missing a parent, they may
2052  // assume we have them and request the parents from us.
2053  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
2054  }
2055 }
2056 
2057 static uint32_t GetFetchFlags(const CNode& pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
2058  uint32_t nFetchFlags = 0;
2059  if (State(pfrom.GetId())->fHaveWitness) {
2060  nFetchFlags |= MSG_WITNESS_FLAG;
2061  }
2062  return nFetchFlags;
2063 }
2064 
2065 void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, const CBlock& block, const BlockTransactionsRequest& req)
2066 {
2067  BlockTransactions resp(req);
2068  for (size_t i = 0; i < req.indexes.size(); i++) {
2069  if (req.indexes[i] >= block.vtx.size()) {
2070  Misbehaving(pfrom.GetId(), 100, "getblocktxn with out-of-bounds tx indices");
2071  return;
2072  }
2073  resp.txn[i] = block.vtx[req.indexes[i]];
2074  }
2075  LOCK(cs_main);
2076  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
2077  int nSendFlags = State(pfrom.GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
2078  m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
2079 }
2080 
2081 void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
2082  const std::vector<CBlockHeader>& headers,
2083  bool via_compact_block)
2084 {
2085  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
2086  size_t nCount = headers.size();
2087 
2088  if (nCount == 0) {
2089  // Nothing interesting. Stop asking this peers for more headers.
2090  return;
2091  }
2092 
2093  bool received_new_header = false;
2094  const CBlockIndex *pindexLast = nullptr;
2095  {
2096  LOCK(cs_main);
2097  CNodeState *nodestate = State(pfrom.GetId());
2098 
2099  // If this looks like it could be a block announcement (nCount <
2100  // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
2101  // don't connect:
2102  // - Send a getheaders message in response to try to connect the chain.
2103  // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
2104  // don't connect before giving DoS points
2105  // - Once a headers message is received that is valid and does connect,
2106  // nUnconnectingHeaders gets reset back to 0.
2107  if (!m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
2108  nodestate->nUnconnectingHeaders++;
2109  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexBestHeader), uint256()));
2110  LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2111  headers[0].GetHash().ToString(),
2112  headers[0].hashPrevBlock.ToString(),
2114  pfrom.GetId(), nodestate->nUnconnectingHeaders);
2115  // Set hashLastUnknownBlock for this peer, so that if we
2116  // eventually get the headers - even from a different peer -
2117  // we can use this peer to download.
2118  UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash());
2119 
2120  if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
2121  Misbehaving(pfrom.GetId(), 20, strprintf("%d non-connecting headers", nodestate->nUnconnectingHeaders));
2122  }
2123  return;
2124  }
2125 
2126  uint256 hashLastBlock;
2127  for (const CBlockHeader& header : headers) {
2128  if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2129  Misbehaving(pfrom.GetId(), 20, "non-continuous headers sequence");
2130  return;
2131  }
2132  hashLastBlock = header.GetHash();
2133  }
2134 
2135  // If we don't have the last header, then they'll have given us
2136  // something new (if these headers are valid).
2137  if (!m_chainman.m_blockman.LookupBlockIndex(hashLastBlock)) {
2138  received_new_header = true;
2139  }
2140  }
2141 
2142  BlockValidationState state;
2143  if (!m_chainman.ProcessNewBlockHeaders(headers, state, m_chainparams, &pindexLast)) {
2144  if (state.IsInvalid()) {
2145  MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received");
2146  return;
2147  }
2148  }
2149 
2150  {
2151  LOCK(cs_main);
2152  CNodeState *nodestate = State(pfrom.GetId());
2153  if (nodestate->nUnconnectingHeaders > 0) {
2154  LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom.GetId(), nodestate->nUnconnectingHeaders);
2155  }
2156  nodestate->nUnconnectingHeaders = 0;
2157 
2158  assert(pindexLast);
2159  UpdateBlockAvailability(pfrom.GetId(), pindexLast->GetBlockHash());
2160 
2161  // From here, pindexBestKnownBlock should be guaranteed to be non-null,
2162  // because it is set in UpdateBlockAvailability. Some nullptr checks
2163  // are still present, however, as belt-and-suspenders.
2164 
2165  if (received_new_header && pindexLast->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
2166  nodestate->m_last_block_announcement = GetTime();
2167  }
2168 
2169  if (nCount == MAX_HEADERS_RESULTS) {
2170  // Headers message had its maximum size; the peer may have more headers.
2171  // TODO: optimize: if pindexLast is an ancestor of m_chainman.ActiveChain().Tip or pindexBestHeader, continue
2172  // from there instead.
2173  LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
2174  pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
2175  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexLast), uint256()));
2176  }
2177 
2178  // If this set of headers is valid and ends in a block with at least as
2179  // much work as our tip, download as much as possible.
2180  if (CanDirectFetch() && pindexLast->IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= pindexLast->nChainWork) {
2181  std::vector<const CBlockIndex*> vToFetch;
2182  const CBlockIndex *pindexWalk = pindexLast;
2183  // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2184  while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2185  if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
2186  !IsBlockRequested(pindexWalk->GetBlockHash()) &&
2187  (!DeploymentActiveAt(*pindexWalk, m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT) || State(pfrom.GetId())->fHaveWitness)) {
2188  // We don't have this block, and it's not yet in flight.
2189  vToFetch.push_back(pindexWalk);
2190  }
2191  pindexWalk = pindexWalk->pprev;
2192  }
2193  // If pindexWalk still isn't on our main chain, we're looking at a
2194  // very large reorg at a time we think we're close to caught up to
2195  // the main chain -- this shouldn't really happen. Bail out on the
2196  // direct fetch and rely on parallel download instead.
2197  if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
2198  LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
2199  pindexLast->GetBlockHash().ToString(),
2200  pindexLast->nHeight);
2201  } else {
2202  std::vector<CInv> vGetData;
2203  // Download as much as possible, from earliest to latest.
2204  for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
2205  if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2206  // Can't download any more from this peer
2207  break;
2208  }
2209  uint32_t nFetchFlags = GetFetchFlags(pfrom);
2210  vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
2211  BlockRequested(pfrom.GetId(), *pindex);
2212  LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
2213  pindex->GetBlockHash().ToString(), pfrom.GetId());
2214  }
2215  if (vGetData.size() > 1) {
2216  LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2217  pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
2218  }
2219  if (vGetData.size() > 0) {
2220  if (!m_ignore_incoming_txs &&
2221  nodestate->fSupportsDesiredCmpctVersion &&
2222  vGetData.size() == 1 &&
2223  mapBlocksInFlight.size() == 1 &&
2224  pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
2225  // In any case, we want to download using a compact block, not a regular one
2226  vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
2227  }
2228  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2229  }
2230  }
2231  }
2232  // If we're in IBD, we want outbound peers that will serve us a useful
2233  // chain. Disconnect peers that are on chains with insufficient work.
2234  if (m_chainman.ActiveChainstate().IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
2235  // When nCount < MAX_HEADERS_RESULTS, we know we have no more
2236  // headers to fetch from this peer.
2237  if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
2238  // This peer has too little work on their headers chain to help
2239  // us sync -- disconnect if it is an outbound disconnection
2240  // candidate.
2241  // Note: We compare their tip to nMinimumChainWork (rather than
2242  // m_chainman.ActiveChain().Tip()) because we won't start block download
2243  // until we have a headers chain that has at least
2244  // nMinimumChainWork, even if a peer has a chain past our tip,
2245  // as an anti-DoS measure.
2246  if (pfrom.IsOutboundOrBlockRelayConn()) {
2247  LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom.GetId());
2248  pfrom.fDisconnect = true;
2249  }
2250  }
2251  }
2252 
2253  // If this is an outbound full-relay peer, check to see if we should protect
2254  // it from the bad/lagging chain logic.
2255  // Note that outbound block-relay peers are excluded from this protection, and
2256  // thus always subject to eviction under the bad/lagging chain logic.
2257  // See ChainSyncTimeoutState.
2258  if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) {
2259  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) {
2260  LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId());
2261  nodestate->m_chain_sync.m_protect = true;
2262  ++m_outbound_peers_with_protect_from_disconnect;
2263  }
2264  }
2265  }
2266 
2267  return;
2268 }
2269 
2278 void PeerManagerImpl::ProcessOrphanTx(std::set<uint256>& orphan_work_set)
2279 {
2282 
2283  while (!orphan_work_set.empty()) {
2284  const uint256 orphanHash = *orphan_work_set.begin();
2285  orphan_work_set.erase(orphan_work_set.begin());
2286 
2287  const auto [porphanTx, from_peer] = m_orphanage.GetTx(orphanHash);
2288  if (porphanTx == nullptr) continue;
2289 
2290  const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx);
2291  const TxValidationState& state = result.m_state;
2292 
2294  LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
2295  _RelayTransaction(orphanHash, porphanTx->GetWitnessHash());
2296  m_orphanage.AddChildrenToWorkSet(*porphanTx, orphan_work_set);
2297  m_orphanage.EraseTx(orphanHash);
2298  for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) {
2299  AddToCompactExtraTransactions(removedTx);
2300  }
2301  break;
2302  } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) {
2303  if (state.IsInvalid()) {
2304  LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s from peer=%d. %s\n",
2305  orphanHash.ToString(),
2306  from_peer,
2307  state.ToString());
2308  // Maybe punish peer that gave us an invalid orphan tx
2309  MaybePunishNodeForTx(from_peer, state);
2310  }
2311  // Has inputs but not accepted to mempool
2312  // Probably non-standard or insufficient fee
2313  LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
2315  // We can add the wtxid of this transaction to our reject filter.
2316  // Do not add txids of witness transactions or witness-stripped
2317  // transactions to the filter, as they can have been malleated;
2318  // adding such txids to the reject filter would potentially
2319  // interfere with relay of valid transactions from peers that
2320  // do not support wtxid-based relay. See
2321  // https://github.com/bitcoin/bitcoin/issues/8279 for details.
2322  // We can remove this restriction (and always add wtxids to
2323  // the filter even for witness stripped transactions) once
2324  // wtxid-based relay is broadly deployed.
2325  // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
2326  // for concerns around weakening security of unupgraded nodes
2327  // if we start doing this too early.
2328  m_recent_rejects.insert(porphanTx->GetWitnessHash());
2329  // If the transaction failed for TX_INPUTS_NOT_STANDARD,
2330  // then we know that the witness was irrelevant to the policy
2331  // failure, since this check depends only on the txid
2332  // (the scriptPubKey being spent is covered by the txid).
2333  // Add the txid to the reject filter to prevent repeated
2334  // processing of this transaction in the event that child
2335  // transactions are later received (resulting in
2336  // parent-fetching by txid via the orphan-handling logic).
2337  if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && porphanTx->GetWitnessHash() != porphanTx->GetHash()) {
2338  // We only add the txid if it differs from the wtxid, to
2339  // avoid wasting entries in the rolling bloom filter.
2340  m_recent_rejects.insert(porphanTx->GetHash());
2341  }
2342  }
2343  m_orphanage.EraseTx(orphanHash);
2344  break;
2345  }
2346  }
2347 }
2348 
2349 bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& peer,
2350  BlockFilterType filter_type, uint32_t start_height,
2351  const uint256& stop_hash, uint32_t max_height_diff,
2352  const CBlockIndex*& stop_index,
2353  BlockFilterIndex*& filter_index)
2354 {
2355  const bool supported_filter_type =
2356  (filter_type == BlockFilterType::BASIC &&
2358  if (!supported_filter_type) {
2359  LogPrint(BCLog::NET, "peer %d requested unsupported block filter type: %d\n",
2360  peer.GetId(), static_cast<uint8_t>(filter_type));
2361  peer.fDisconnect = true;
2362  return false;
2363  }
2364 
2365  {
2366  LOCK(cs_main);
2367  stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
2368 
2369  // Check that the stop block exists and the peer would be allowed to fetch it.
2370  if (!stop_index || !BlockRequestAllowed(stop_index)) {
2371  LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
2372  peer.GetId(), stop_hash.ToString());
2373  peer.fDisconnect = true;
2374  return false;
2375  }
2376  }
2377 
2378  uint32_t stop_height = stop_index->nHeight;
2379  if (start_height > stop_height) {
2380  LogPrint(BCLog::NET, "peer %d sent invalid getcfilters/getcfheaders with " /* Continued */
2381  "start height %d and stop height %d\n",
2382  peer.GetId(), start_height, stop_height);
2383  peer.fDisconnect = true;
2384  return false;
2385  }
2386  if (stop_height - start_height >= max_height_diff) {
2387  LogPrint(BCLog::NET, "peer %d requested too many cfilters/cfheaders: %d / %d\n",
2388  peer.GetId(), stop_height - start_height + 1, max_height_diff);
2389  peer.fDisconnect = true;
2390  return false;
2391  }
2392 
2393  filter_index = GetBlockFilterIndex(filter_type);
2394  if (!filter_index) {
2395  LogPrint(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type));
2396  return false;
2397  }
2398 
2399  return true;
2400 }
2401 
2402 void PeerManagerImpl::ProcessGetCFilters(CNode& peer, CDataStream& vRecv)
2403 {
2404  uint8_t filter_type_ser;
2405  uint32_t start_height;
2406  uint256 stop_hash;
2407 
2408  vRecv >> filter_type_ser >> start_height >> stop_hash;
2409 
2410  const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
2411 
2412  const CBlockIndex* stop_index;
2413  BlockFilterIndex* filter_index;
2414  if (!PrepareBlockFilterRequest(peer, filter_type, start_height, stop_hash,
2415  MAX_GETCFILTERS_SIZE, stop_index, filter_index)) {
2416  return;
2417  }
2418 
2419  std::vector<BlockFilter> filters;
2420  if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
2421  LogPrint(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
2422  BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
2423  return;
2424  }
2425 
2426  for (const auto& filter : filters) {
2428  .Make(NetMsgType::CFILTER, filter);
2429  m_connman.PushMessage(&peer, std::move(msg));
2430  }
2431 }
2432 
2433 void PeerManagerImpl::ProcessGetCFHeaders(CNode& peer, CDataStream& vRecv)
2434 {
2435  uint8_t filter_type_ser;
2436  uint32_t start_height;
2437  uint256 stop_hash;
2438 
2439  vRecv >> filter_type_ser >> start_height >> stop_hash;
2440 
2441  const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
2442 
2443  const CBlockIndex* stop_index;
2444  BlockFilterIndex* filter_index;
2445  if (!PrepareBlockFilterRequest(peer, filter_type, start_height, stop_hash,
2446  MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) {
2447  return;
2448  }
2449 
2450  uint256 prev_header;
2451  if (start_height > 0) {
2452  const CBlockIndex* const prev_block =
2453  stop_index->GetAncestor(static_cast<int>(start_height - 1));
2454  if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
2455  LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
2456  BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString());
2457  return;
2458  }
2459  }
2460 
2461  std::vector<uint256> filter_hashes;
2462  if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) {
2463  LogPrint(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
2464  BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
2465  return;
2466  }
2467 
2470  filter_type_ser,
2471  stop_index->GetBlockHash(),
2472  prev_header,
2473  filter_hashes);
2474  m_connman.PushMessage(&peer, std::move(msg));
2475 }
2476 
2477 void PeerManagerImpl::ProcessGetCFCheckPt(CNode& peer, CDataStream& vRecv)
2478 {
2479  uint8_t filter_type_ser;
2480  uint256 stop_hash;
2481 
2482  vRecv >> filter_type_ser >> stop_hash;
2483 
2484  const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
2485 
2486  const CBlockIndex* stop_index;
2487  BlockFilterIndex* filter_index;
2488  if (!PrepareBlockFilterRequest(peer, filter_type, /*start_height=*/0, stop_hash,
2489  /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
2490  stop_index, filter_index)) {
2491  return;
2492  }
2493 
2494  std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
2495 
2496  // Populate headers.
2497  const CBlockIndex* block_index = stop_index;
2498  for (int i = headers.size() - 1; i >= 0; i--) {
2499  int height = (i + 1) * CFCHECKPT_INTERVAL;
2500  block_index = block_index->GetAncestor(height);
2501 
2502  if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
2503  LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
2504  BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());
2505  return;
2506  }
2507  }
2508 
2511  filter_type_ser,
2512  stop_index->GetBlockHash(),
2513  headers);
2514  m_connman.PushMessage(&peer, std::move(msg));
2515 }
2516 
2517 void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing)
2518 {
2519  bool new_block{false};
2520  m_chainman.ProcessNewBlock(m_chainparams, block, force_processing, &new_block);
2521  if (new_block) {
2522  node.m_last_block_time = GetTime<std::chrono::seconds>();
2523  } else {
2524  LOCK(cs_main);
2525  mapBlockSource.erase(block->GetHash());
2526  }
2527 }
2528 
2529 void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
2530  const std::chrono::microseconds time_received,
2531  const std::atomic<bool>& interruptMsgProc)
2532 {
2533  LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
2534 
2535  PeerRef peer = GetPeerRef(pfrom.GetId());
2536  if (peer == nullptr) return;
2537 
2538  if (msg_type == NetMsgType::VERSION) {
2539  if (pfrom.nVersion != 0) {
2540  LogPrint(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId());
2541  return;
2542  }
2543 
2544  int64_t nTime;
2545  CService addrMe;
2546  uint64_t nNonce = 1;
2547  ServiceFlags nServices;
2548  int nVersion;
2549  std::string cleanSubVer;
2550  int starting_height = -1;
2551  bool fRelay = true;
2552 
2553  vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
2554  if (nTime < 0) {
2555  nTime = 0;
2556  }
2557  vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer
2558  vRecv >> addrMe;
2559  if (!pfrom.IsInboundConn())
2560  {
2561  m_addrman.SetServices(pfrom.addr, nServices);
2562  }
2563  if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices))
2564  {
2565  LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom.GetId(), nServices, GetDesirableServiceFlags(nServices));
2566  pfrom.fDisconnect = true;
2567  return;
2568  }
2569 
2570  if (nVersion < MIN_PEER_PROTO_VERSION) {
2571  // disconnect from peers older than this proto version
2572  LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom.GetId(), nVersion);
2573  pfrom.fDisconnect = true;
2574  return;
2575  }
2576 
2577  if (!vRecv.empty()) {
2578  // The version message includes information about the sending node which we don't use:
2579  // - 8 bytes (service bits)
2580  // - 16 bytes (ipv6 address)
2581  // - 2 bytes (port)
2582  vRecv.ignore(26);
2583  vRecv >> nNonce;
2584  }
2585  if (!vRecv.empty()) {
2586  std::string strSubVer;
2587  vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
2588  cleanSubVer = SanitizeString(strSubVer);
2589  }
2590  if (!vRecv.empty()) {
2591  vRecv >> starting_height;
2592  }
2593  if (!vRecv.empty())
2594  vRecv >> fRelay;
2595  // Disconnect if we connected to ourself
2596  if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce))
2597  {
2598  LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToString());
2599  pfrom.fDisconnect = true;
2600  return;
2601  }
2602 
2603  if (pfrom.IsInboundConn() && addrMe.IsRoutable())
2604  {
2605  SeenLocal(addrMe);
2606  }
2607 
2608  // Inbound peers send us their version message when they connect.
2609  // We send our version message in response.
2610  if (pfrom.IsInboundConn()) {
2611  PushNodeVersion(pfrom);
2612  }
2613 
2614  // Change version
2615  const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION);
2616  pfrom.SetCommonVersion(greatest_common_version);
2617  pfrom.nVersion = nVersion;
2618 
2619  const CNetMsgMaker msg_maker(greatest_common_version);
2620 
2621  if (greatest_common_version >= WTXID_RELAY_VERSION) {
2622  m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::WTXIDRELAY));
2623  }
2624 
2625  // Signal ADDRv2 support (BIP155).
2626  if (greatest_common_version >= 70016) {
2627  // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some
2628  // implementations reject messages they don't know. As a courtesy, don't send
2629  // it to nodes with a version before 70016, as no software is known to support
2630  // BIP155 that doesn't announce at least that protocol version number.
2631  m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::SENDADDRV2));
2632  }
2633 
2634  m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::VERACK));
2635 
2636  pfrom.nServices = nServices;
2637  pfrom.SetAddrLocal(addrMe);
2638  {
2639  LOCK(pfrom.m_subver_mutex);
2640  pfrom.cleanSubVer = cleanSubVer;
2641  }
2642  peer->m_starting_height = starting_height;
2643 
2644  // set nodes not relaying blocks and tx and not serving (parts) of the historical blockchain as "clients"
2645  pfrom.fClient = (!(nServices & NODE_NETWORK) && !(nServices & NODE_NETWORK_LIMITED));
2646 
2647  // set nodes not capable of serving the complete blockchain history as "limited nodes"
2648  pfrom.m_limited_node = (!(nServices & NODE_NETWORK) && (nServices & NODE_NETWORK_LIMITED));
2649 
2650  if (pfrom.m_tx_relay != nullptr) {
2651  LOCK(pfrom.m_tx_relay->cs_filter);
2652  pfrom.m_tx_relay->fRelayTxes = fRelay; // set to true after we get the first filter* message
2653  }
2654 
2655  if((nServices & NODE_WITNESS))
2656  {
2657  LOCK(cs_main);
2658  State(pfrom.GetId())->fHaveWitness = true;
2659  }
2660 
2661  // Potentially mark this peer as a preferred download peer.
2662  {
2663  LOCK(cs_main);
2664  UpdatePreferredDownload(pfrom, State(pfrom.GetId()));
2665  }
2666 
2667  // Self advertisement & GETADDR logic
2668  if (!pfrom.IsInboundConn() && SetupAddressRelay(pfrom, *peer)) {
2669  // For outbound peers, we try to relay our address (so that other
2670  // nodes can try to find us more quickly, as we have no guarantee
2671  // that an outbound peer is even aware of how to reach us) and do a
2672  // one-time address fetch (to help populate/update our addrman). If
2673  // we're starting up for the first time, our addrman may be pretty
2674  // empty and no one will know who we are, so these mechanisms are
2675  // important to help us connect to the network.
2676  //
2677  // We skip this for block-relay-only peers. We want to avoid
2678  // potentially leaking addr information and we do not want to
2679  // indicate to the peer that we will participate in addr relay.
2680  if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload())
2681  {
2682  CAddress addr = GetLocalAddress(&pfrom.addr, pfrom.GetLocalServices());
2683  FastRandomContext insecure_rand;
2684  if (addr.IsRoutable())
2685  {
2686  LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
2687  PushAddress(*peer, addr, insecure_rand);
2688  } else if (IsPeerAddrLocalGood(&pfrom)) {
2689  addr.SetIP(addrMe);
2690  LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
2691  PushAddress(*peer, addr, insecure_rand);
2692  }
2693  }
2694 
2695  // Get recent addresses
2696  m_connman.PushMessage(&pfrom, CNetMsgMaker(greatest_common_version).Make(NetMsgType::GETADDR));
2697  peer->m_getaddr_sent = true;
2698  // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response
2699  // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
2700  peer->m_addr_token_bucket += MAX_ADDR_TO_SEND;
2701  }
2702 
2703  if (!pfrom.IsInboundConn()) {
2704  // For non-inbound connections, we update the addrman to record
2705  // connection success so that addrman will have an up-to-date
2706  // notion of which peers are online and available.
2707  //
2708  // While we strive to not leak information about block-relay-only
2709  // connections via the addrman, not moving an address to the tried
2710  // table is also potentially detrimental because new-table entries
2711  // are subject to eviction in the event of addrman collisions. We
2712  // mitigate the information-leak by never calling
2713  // AddrMan::Connected() on block-relay-only peers; see
2714  // FinalizeNode().
2715  //
2716  // This moves an address from New to Tried table in Addrman,
2717  // resolves tried-table collisions, etc.
2718  m_addrman.Good(pfrom.addr);
2719  }
2720 
2721  std::string remoteAddr;
2722  if (fLogIPs)
2723  remoteAddr = ", peeraddr=" + pfrom.addr.ToString();
2724 
2725  LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s\n",
2726  cleanSubVer, pfrom.nVersion,
2727  peer->m_starting_height, addrMe.ToString(), fRelay, pfrom.GetId(),
2728  remoteAddr);
2729 
2730  int64_t nTimeOffset = nTime - GetTime();
2731  pfrom.nTimeOffset = nTimeOffset;
2732  if (!pfrom.IsInboundConn()) {
2733  // Don't use timedata samples from inbound peers to make it
2734  // harder for others to tamper with our adjusted time.
2735  AddTimeData(pfrom.addr, nTimeOffset);
2736  }
2737 
2738  // If the peer is old enough to have the old alert system, send it the final alert.
2739  if (greatest_common_version <= 70012) {
2740  CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
2741  m_connman.PushMessage(&pfrom, CNetMsgMaker(greatest_common_version).Make("alert", finalAlert));
2742  }
2743 
2744  // Feeler connections exist only to verify if address is online.
2745  if (pfrom.IsFeelerConn()) {
2746  LogPrint(BCLog::NET, "feeler connection completed peer=%d; disconnecting\n", pfrom.GetId());
2747  pfrom.fDisconnect = true;
2748  }
2749  return;
2750  }
2751 
2752  if (pfrom.nVersion == 0) {
2753  // Must have a version message before anything else
2754  LogPrint(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
2755  return;
2756  }
2757 
2758  // At this point, the outgoing message serialization version can't change.
2759  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
2760 
2761  if (msg_type == NetMsgType::VERACK) {
2762  if (pfrom.fSuccessfullyConnected) {
2763  LogPrint(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId());
2764  return;
2765  }
2766 
2767  if (!pfrom.IsInboundConn()) {
2768  LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s (%s)\n",
2769  pfrom.nVersion.load(), peer->m_starting_height,
2770  pfrom.GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToString()) : ""),
2771  pfrom.ConnectionTypeAsString());
2772  }
2773 
2774  if (pfrom.GetCommonVersion() >= SENDHEADERS_VERSION) {
2775  // Tell our peer we prefer to receive headers rather than inv's
2776  // We send this to non-NODE NETWORK peers as well, because even
2777  // non-NODE NETWORK peers can announce blocks (such as pruning
2778  // nodes)
2779  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
2780  }
2781  if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) {
2782  // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
2783  // However, we do not request new block announcements using
2784  // cmpctblock messages.
2785  // We send this to non-NODE NETWORK peers as well, because
2786  // they may wish to request compact blocks from us
2787  bool fAnnounceUsingCMPCTBLOCK = false;
2788  uint64_t nCMPCTBLOCKVersion = 2;
2789  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
2790  nCMPCTBLOCKVersion = 1;
2791  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
2792  }
2793  pfrom.fSuccessfullyConnected = true;
2794  return;
2795  }
2796 
2797  if (msg_type == NetMsgType::SENDHEADERS) {
2798  LOCK(cs_main);
2799  State(pfrom.GetId())->fPreferHeaders = true;
2800  return;
2801  }
2802 
2803  if (msg_type == NetMsgType::SENDCMPCT) {
2804  bool fAnnounceUsingCMPCTBLOCK = false;
2805  uint64_t nCMPCTBLOCKVersion = 0;
2806  vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
2807  if (nCMPCTBLOCKVersion == 1 || nCMPCTBLOCKVersion == 2) {
2808  LOCK(cs_main);
2809  // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
2810  if (!State(pfrom.GetId())->fProvidesHeaderAndIDs) {
2811  State(pfrom.GetId())->fProvidesHeaderAndIDs = true;
2812  State(pfrom.GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
2813  }
2814  if (State(pfrom.GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) { // ignore later version announces
2815  State(pfrom.GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
2816  // save whether peer selects us as BIP152 high-bandwidth peer
2817  // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth)
2818  pfrom.m_bip152_highbandwidth_from = fAnnounceUsingCMPCTBLOCK;
2819  }
2820  if (!State(pfrom.GetId())->fSupportsDesiredCmpctVersion) {
2821  State(pfrom.GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
2822  }
2823  }
2824  return;
2825  }
2826 
2827  // BIP339 defines feature negotiation of wtxidrelay, which must happen between
2828  // VERSION and VERACK to avoid relay problems from switching after a connection is up.
2829  if (msg_type == NetMsgType::WTXIDRELAY) {
2830  if (pfrom.fSuccessfullyConnected) {
2831  // Disconnect peers that send a wtxidrelay message after VERACK.
2832  LogPrint(BCLog::NET, "wtxidrelay received after verack from peer=%d; disconnecting\n", pfrom.GetId());
2833  pfrom.fDisconnect = true;
2834  return;
2835  }
2836  if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) {
2837  LOCK(cs_main);
2838  if (!State(pfrom.GetId())->m_wtxid_relay) {
2839  State(pfrom.GetId())->m_wtxid_relay = true;
2840  m_wtxid_relay_peers++;
2841  } else {
2842  LogPrint(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId());
2843  }
2844  } else {
2845  LogPrint(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId());
2846  }
2847  return;
2848  }
2849 
2850  // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen
2851  // between VERSION and VERACK.
2852  if (msg_type == NetMsgType::SENDADDRV2) {
2853  if (pfrom.fSuccessfullyConnected) {
2854  // Disconnect peers that send a SENDADDRV2 message after VERACK.
2855  LogPrint(BCLog::NET, "sendaddrv2 received after verack from peer=%d; disconnecting\n", pfrom.GetId());
2856  pfrom.fDisconnect = true;
2857  return;
2858  }
2859  peer->m_wants_addrv2 = true;
2860  return;
2861  }
2862 
2863  if (!pfrom.fSuccessfullyConnected) {
2864  LogPrint(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
2865  return;
2866  }
2867 
2868  if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
2869  int stream_version = vRecv.GetVersion();
2870  if (msg_type == NetMsgType::ADDRV2) {
2871  // Add ADDRV2_FORMAT to the version so that the CNetAddr and CAddress
2872  // unserialize methods know that an address in v2 format is coming.
2873  stream_version |= ADDRV2_FORMAT;
2874  }
2875 
2876  OverrideStream<CDataStream> s(&vRecv, vRecv.GetType(), stream_version);
2877  std::vector<CAddress> vAddr;
2878 
2879  s >> vAddr;
2880 
2881  if (!SetupAddressRelay(pfrom, *peer)) {
2882  LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
2883  return;
2884  }
2885 
2886  if (vAddr.size() > MAX_ADDR_TO_SEND)
2887  {
2888  Misbehaving(pfrom.GetId(), 20, strprintf("%s message size = %u", msg_type, vAddr.size()));
2889  return;
2890  }
2891 
2892  // Store the new addresses
2893  std::vector<CAddress> vAddrOk;
2894  int64_t nNow = GetAdjustedTime();
2895  int64_t nSince = nNow - 10 * 60;
2896 
2897  // Update/increment addr rate limiting bucket.
2898  const auto current_time{GetTime<std::chrono::microseconds>()};
2899  if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
2900  // Don't increment bucket if it's already full
2901  const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us);
2902  const double increment = CountSecondsDouble(time_diff) * MAX_ADDR_RATE_PER_SECOND;
2903  peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET);
2904  }
2905  peer->m_addr_token_timestamp = current_time;
2906 
2907  const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr);
2908  uint64_t num_proc = 0;
2909  uint64_t num_rate_limit = 0;
2910  Shuffle(vAddr.begin(), vAddr.end(), FastRandomContext());
2911  for (CAddress& addr : vAddr)
2912  {
2913  if (interruptMsgProc)
2914  return;
2915 
2916  // Apply rate limiting.
2917  if (peer->m_addr_token_bucket < 1.0) {
2918  if (rate_limited) {
2919  ++num_rate_limit;
2920  continue;
2921  }
2922  } else {
2923  peer->m_addr_token_bucket -= 1.0;
2924  }
2925  // We only bother storing full nodes, though this may include
2926  // things which we would not make an outbound connection to, in
2927  // part because we may make feeler connections to them.
2929  continue;
2930 
2931  if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2932  addr.nTime = nNow - 5 * 24 * 60 * 60;
2933  AddAddressKnown(*peer, addr);
2934  if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
2935  // Do not process banned/discouraged addresses beyond remembering we received them
2936  continue;
2937  }
2938  ++num_proc;
2939  bool fReachable = IsReachable(addr);
2940  if (addr.nTime > nSince && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) {
2941  // Relay to a limited number of other nodes
2942  RelayAddress(pfrom.GetId(), addr, fReachable);
2943  }
2944  // Do not store addresses outside our network
2945  if (fReachable)
2946  vAddrOk.push_back(addr);
2947  }
2948  peer->m_addr_processed += num_proc;
2949  peer->m_addr_rate_limited += num_rate_limit;
2950  LogPrint(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n",
2951  vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
2952 
2953  m_addrman.Add(vAddrOk, pfrom.addr, 2 * 60 * 60);
2954  if (vAddr.size() < 1000) peer->m_getaddr_sent = false;
2955 
2956  // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements
2957  if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
2958  LogPrint(BCLog::NET, "addrfetch connection completed peer=%d; disconnecting\n", pfrom.GetId());
2959  pfrom.fDisconnect = true;
2960  }
2961  return;
2962  }
2963 
2964  if (msg_type == NetMsgType::INV) {
2965  std::vector<CInv> vInv;
2966  vRecv >> vInv;
2967  if (vInv.size() > MAX_INV_SZ)
2968  {
2969  Misbehaving(pfrom.GetId(), 20, strprintf("inv message size = %u", vInv.size()));
2970  return;
2971  }
2972 
2973  // Reject tx INVs when the -blocksonly setting is enabled, or this is a
2974  // block-relay-only peer
2975  bool reject_tx_invs{m_ignore_incoming_txs || (pfrom.m_tx_relay == nullptr)};
2976 
2977  // Allow peers with relay permission to send data other than blocks in blocks only mode
2979  reject_tx_invs = false;
2980  }
2981 
2982  LOCK(cs_main);
2983 
2984  const auto current_time{GetTime<std::chrono::microseconds>()};
2985  uint256* best_block{nullptr};
2986 
2987  for (CInv& inv : vInv) {
2988  if (interruptMsgProc) return;
2989 
2990  // Ignore INVs that don't match wtxidrelay setting.
2991  // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting.
2992  // This is fine as no INV messages are involved in that process.
2993  if (State(pfrom.GetId())->m_wtxid_relay) {
2994  if (inv.IsMsgTx()) continue;
2995  } else {
2996  if (inv.IsMsgWtx()) continue;
2997  }
2998 
2999  if (inv.IsMsgBlk()) {
3000  const bool fAlreadyHave = AlreadyHaveBlock(inv.hash);
3001  LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
3002 
3003  UpdateBlockAvailability(pfrom.GetId(), inv.hash);
3004  if (!fAlreadyHave && !fImporting && !fReindex && !IsBlockRequested(inv.hash)) {
3005  // Headers-first is the primary method of announcement on
3006  // the network. If a node fell back to sending blocks by inv,
3007  // it's probably for a re-org. The final block hash
3008  // provided should be the highest, so send a getheaders and
3009  // then fetch the blocks we need to catch up.
3010  best_block = &inv.hash;
3011  }
3012  } else if (inv.IsGenTxMsg()) {
3013  if (reject_tx_invs) {
3014  LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId());
3015  pfrom.fDisconnect = true;
3016  return;
3017  }
3018  const GenTxid gtxid = ToGenTxid(inv);
3019  const bool fAlreadyHave = AlreadyHaveTx(gtxid);
3020  LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
3021 
3022  pfrom.AddKnownTx(inv.hash);
3023  if (!fAlreadyHave && !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
3024  AddTxAnnouncement(pfrom, gtxid, current_time);
3025  }
3026  } else {
3027  LogPrint(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId());
3028  }
3029  }
3030 
3031  if (best_block != nullptr) {
3032  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexBestHeader), *best_block));
3033  LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, best_block->ToString(), pfrom.GetId());
3034  }
3035 
3036  return;
3037  }
3038 
3039  if (msg_type == NetMsgType::GETDATA) {
3040  std::vector<CInv> vInv;
3041  vRecv >> vInv;
3042  if (vInv.size() > MAX_INV_SZ)
3043  {
3044  Misbehaving(pfrom.GetId(), 20, strprintf("getdata message size = %u", vInv.size()));
3045  return;
3046  }
3047 
3048  LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId());
3049 
3050  if (vInv.size() > 0) {
3051  LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
3052  }
3053 
3054  {
3055  LOCK(peer->m_getdata_requests_mutex);
3056  peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end());
3057  ProcessGetData(pfrom, *peer, interruptMsgProc);
3058  }
3059 
3060  return;
3061  }
3062 
3063  if (msg_type == NetMsgType::GETBLOCKS) {
3064  CBlockLocator locator;
3065  uint256 hashStop;
3066  vRecv >> locator >> hashStop;
3067 
3068  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
3069  LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
3070  pfrom.fDisconnect = true;
3071  return;
3072  }
3073 
3074  // We might have announced the currently-being-connected tip using a
3075  // compact block, which resulted in the peer sending a getblocks
3076  // request, which we would otherwise respond to without the new block.
3077  // To avoid this situation we simply verify that we are on our best
3078  // known chain now. This is super overkill, but we handle it better
3079  // for getheaders requests, and there are no known nodes which support
3080  // compact blocks but still use getblocks to request blocks.
3081  {
3082  std::shared_ptr<const CBlock> a_recent_block;
3083  {
3085  a_recent_block = most_recent_block;
3086  }
3087  BlockValidationState state;
3088  if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
3089  LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
3090  }
3091  }
3092 
3093  LOCK(cs_main);
3094 
3095  // Find the last block the caller has in the main chain
3096  const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
3097 
3098  // Send the rest of the chain
3099  if (pindex)
3100  pindex = m_chainman.ActiveChain().Next(pindex);
3101  int nLimit = 500;
3102  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());
3103  for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
3104  {
3105  if (pindex->GetBlockHash() == hashStop)
3106  {
3107  LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3108  break;
3109  }
3110  // If pruning, don't inv blocks unless we have on disk and are likely to still have
3111  // for some reasonable time window (1 hour) that block relay might require.
3112  const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
3113  if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave))
3114  {
3115  LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3116  break;
3117  }
3118  WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
3119  if (--nLimit <= 0) {
3120  // When this block is requested, we'll send an inv that'll
3121  // trigger the peer to getblocks the next batch of inventory.
3122  LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3123  WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();});
3124  break;
3125  }
3126  }
3127  return;
3128  }
3129 
3130  if (msg_type == NetMsgType::GETBLOCKTXN) {
3132  vRecv >> req;
3133 
3134  std::shared_ptr<const CBlock> recent_block;
3135  {
3137  if (most_recent_block_hash == req.blockhash)
3138  recent_block = most_recent_block;
3139  // Unlock cs_most_recent_block to avoid cs_main lock inversion
3140  }
3141  if (recent_block) {
3142  SendBlockTransactions(pfrom, *recent_block, req);
3143  return;
3144  }
3145 
3146  {
3147  LOCK(cs_main);
3148 
3149  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
3150  if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3151  LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId());
3152  return;
3153  }
3154 
3155  if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
3156  CBlock block;
3157  bool ret = ReadBlockFromDisk(block, pindex, m_chainparams.GetConsensus());
3158  assert(ret);
3159 
3160  SendBlockTransactions(pfrom, block, req);
3161  return;
3162  }
3163  }
3164 
3165  // If an older block is requested (should never happen in practice,
3166  // but can happen in tests) send a block response instead of a
3167  // blocktxn response. Sending a full block response instead of a
3168  // small blocktxn response is preferable in the case where a peer
3169  // might maliciously send lots of getblocktxn requests to trigger
3170  // expensive disk reads, because it will require the peer to
3171  // actually receive all the data read from disk over the network.
3172  LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
3173  CInv inv;
3174  WITH_LOCK(cs_main, inv.type = State(pfrom.GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK);
3175  inv.hash = req.blockhash;
3176  WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv));
3177  // The message processing loop will go around again (without pausing) and we'll respond then
3178  return;
3179  }
3180 
3181  if (msg_type == NetMsgType::GETHEADERS) {
3182  CBlockLocator locator;
3183  uint256 hashStop;
3184  vRecv >> locator >> hashStop;
3185 
3186  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
3187  LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
3188  pfrom.fDisconnect = true;
3189  return;
3190  }
3191 
3192  LOCK(cs_main);
3193  if (m_chainman.ActiveChainstate().IsInitialBlockDownload() && !pfrom.HasPermission(NetPermissionFlags::Download)) {
3194  LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom.GetId());
3195  return;
3196  }
3197 
3198  CNodeState *nodestate = State(pfrom.GetId());
3199  const CBlockIndex* pindex = nullptr;
3200  if (locator.IsNull())
3201  {
3202  // If locator is null, return the hashStop block
3203  pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
3204  if (!pindex) {
3205  return;
3206  }
3207 
3208  if (!BlockRequestAllowed(pindex)) {
3209  LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId());
3210  return;
3211  }
3212  }
3213  else
3214  {
3215  // Find the last block the caller has in the main chain
3216  pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
3217  if (pindex)
3218  pindex = m_chainman.ActiveChain().Next(pindex);
3219  }
3220 
3221  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3222  std::vector<CBlock> vHeaders;
3223  int nLimit = MAX_HEADERS_RESULTS;
3224  LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId());
3225  for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
3226  {
3227  vHeaders.push_back(pindex->GetBlockHeader());
3228  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3229  break;
3230  }
3231  // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR
3232  // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty
3233  // headers message). In both cases it's safe to update
3234  // pindexBestHeaderSent to be our tip.
3235  //
3236  // It is important that we simply reset the BestHeaderSent value here,
3237  // and not max(BestHeaderSent, newHeaderSent). We might have announced
3238  // the currently-being-connected tip using a compact block, which
3239  // resulted in the peer sending a headers request, which we respond to
3240  // without the new block. By resetting the BestHeaderSent, we ensure we
3241  // will re-announce the new block via headers (or compact blocks again)
3242  // in the SendMessages logic.
3243  nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip();
3244  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3245  return;
3246  }
3247 
3248  if (msg_type == NetMsgType::TX) {
3249  // Stop processing the transaction early if
3250  // 1) We are in blocks only mode and peer has no relay permission
3251  // 2) This peer is a block-relay-only peer
3252  if ((m_ignore_incoming_txs && !pfrom.HasPermission(NetPermissionFlags::Relay)) || (pfrom.m_tx_relay == nullptr))
3253  {
3254  LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom.GetId());
3255  pfrom.fDisconnect = true;
3256  return;
3257  }
3258 
3259  // Stop processing the transaction early if we are still in IBD since we don't
3260  // have enough information to validate it yet. Sending unsolicited transactions
3261  // is not considered a protocol violation, so don't punish the peer.
3262  if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) return;
3263 
3264  CTransactionRef ptx;
3265  vRecv >> ptx;
3266  const CTransaction& tx = *ptx;
3267 
3268  const uint256& txid = ptx->GetHash();
3269  const uint256& wtxid = ptx->GetWitnessHash();
3270 
3272 
3273  CNodeState* nodestate = State(pfrom.GetId());
3274 
3275  const uint256& hash = nodestate->m_wtxid_relay ? wtxid : txid;
3276  pfrom.AddKnownTx(hash);
3277  if (nodestate->m_wtxid_relay && txid != wtxid) {
3278  // Insert txid into filterInventoryKnown, even for
3279  // wtxidrelay peers. This prevents re-adding of
3280  // unconfirmed parents to the recently_announced
3281  // filter, when a child tx is requested. See
3282  // ProcessGetData().
3283  pfrom.AddKnownTx(txid);
3284  }
3285 
3286  m_txrequest.ReceivedResponse(pfrom.GetId(), txid);
3287  if (tx.HasWitness()) m_txrequest.ReceivedResponse(pfrom.GetId(), wtxid);
3288 
3289  // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the
3290  // absence of witness malleation, this is strictly better, because the
3291  // recent rejects filter may contain the wtxid but rarely contains
3292  // the txid of a segwit transaction that has been rejected.
3293  // In the presence of witness malleation, it's possible that by only
3294  // doing the check with wtxid, we could overlook a transaction which
3295  // was confirmed with a different witness, or exists in our mempool
3296  // with a different witness, but this has limited downside:
3297  // mempool validation does its own lookup of whether we have the txid
3298  // already; and an adversary can already relay us old transactions
3299  // (older than our recency filter) if trying to DoS us, without any need
3300  // for witness malleation.
3301  if (AlreadyHaveTx(GenTxid::Wtxid(wtxid))) {
3303  // Always relay transactions received from peers with forcerelay
3304  // permission, even if they were already in the mempool, allowing
3305  // the node to function as a gateway for nodes hidden behind it.
3306  if (!m_mempool.exists(GenTxid::Txid(tx.GetHash()))) {
3307  LogPrintf("Not relaying non-mempool transaction %s from forcerelay peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
3308  } else {
3309  LogPrintf("Force relaying tx %s from peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
3310  _RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
3311  }
3312  }
3313  return;
3314  }
3315 
3316  const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx);
3317  const TxValidationState& state = result.m_state;
3318 
3320  // As this version of the transaction was acceptable, we can forget about any
3321  // requests for it.
3322  m_txrequest.ForgetTxHash(tx.GetHash());
3323  m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3324  _RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
3325  m_orphanage.AddChildrenToWorkSet(tx, peer->m_orphan_work_set);
3326 
3327  pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
3328 
3329  LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
3330  pfrom.GetId(),
3331  tx.GetHash().ToString(),
3332  m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000);
3333 
3334  for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) {
3335  AddToCompactExtraTransactions(removedTx);
3336  }
3337 
3338  // Recursively process any orphan transactions that depended on this one
3339  ProcessOrphanTx(peer->m_orphan_work_set);
3340  }
3342  {
3343  bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
3344 
3345  // Deduplicate parent txids, so that we don't have to loop over
3346  // the same parent txid more than once down below.
3347  std::vector<uint256> unique_parents;
3348  unique_parents.reserve(tx.vin.size());
3349  for (const CTxIn& txin : tx.vin) {
3350  // We start with all parents, and then remove duplicates below.
3351  unique_parents.push_back(txin.prevout.hash);
3352  }
3353  std::sort(unique_parents.begin(), unique_parents.end());
3354  unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end());
3355  for (const uint256& parent_txid : unique_parents) {
3356  if (m_recent_rejects.contains(parent_txid)) {
3357  fRejectedParents = true;
3358  break;
3359  }
3360  }
3361  if (!fRejectedParents) {
3362  const auto current_time{GetTime<std::chrono::microseconds>()};
3363 
3364  for (const uint256& parent_txid : unique_parents) {
3365  // Here, we only have the txid (and not wtxid) of the
3366  // inputs, so we only request in txid mode, even for
3367  // wtxidrelay peers.
3368  // Eventually we should replace this with an improved
3369  // protocol for getting all unconfirmed parents.
3370  const auto gtxid{GenTxid::Txid(parent_txid)};
3371  pfrom.AddKnownTx(parent_txid);
3372  if (!AlreadyHaveTx(gtxid)) AddTxAnnouncement(pfrom, gtxid, current_time);
3373  }
3374 
3375  if (m_orphanage.AddTx(ptx, pfrom.GetId())) {
3376  AddToCompactExtraTransactions(ptx);
3377  }
3378 
3379  // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore.
3380  m_txrequest.ForgetTxHash(tx.GetHash());
3381  m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3382 
3383  // DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789)
3384  unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetIntArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
3385  unsigned int nEvicted = m_orphanage.LimitOrphans(nMaxOrphanTx);
3386  if (nEvicted > 0) {
3387  LogPrint(BCLog::MEMPOOL, "orphanage overflow, removed %u tx\n", nEvicted);
3388  }
3389  } else {
3390  LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
3391  // We will continue to reject this tx since it has rejected
3392  // parents so avoid re-requesting it from other peers.
3393  // Here we add both the txid and the wtxid, as we know that
3394  // regardless of what witness is provided, we will not accept
3395  // this, so we don't need to allow for redownload of this txid
3396  // from any of our non-wtxidrelay peers.
3397  m_recent_rejects.insert(tx.GetHash());
3398  m_recent_rejects.insert(tx.GetWitnessHash());
3399  m_txrequest.ForgetTxHash(tx.GetHash());
3400  m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3401  }
3402  } else {
3404  // We can add the wtxid of this transaction to our reject filter.
3405  // Do not add txids of witness transactions or witness-stripped
3406  // transactions to the filter, as they can have been malleated;
3407  // adding such txids to the reject filter would potentially
3408  // interfere with relay of valid transactions from peers that
3409  // do not support wtxid-based relay. See
3410  // https://github.com/bitcoin/bitcoin/issues/8279 for details.
3411  // We can remove this restriction (and always add wtxids to
3412  // the filter even for witness stripped transactions) once
3413  // wtxid-based relay is broadly deployed.
3414  // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
3415  // for concerns around weakening security of unupgraded nodes
3416  // if we start doing this too early.
3417  m_recent_rejects.insert(tx.GetWitnessHash());
3418  m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3419  // If the transaction failed for TX_INPUTS_NOT_STANDARD,
3420  // then we know that the witness was irrelevant to the policy
3421  // failure, since this check depends only on the txid
3422  // (the scriptPubKey being spent is covered by the txid).
3423  // Add the txid to the reject filter to prevent repeated
3424  // processing of this transaction in the event that child
3425  // transactions are later received (resulting in
3426  // parent-fetching by txid via the orphan-handling logic).
3428  m_recent_rejects.insert(tx.GetHash());
3429  m_txrequest.ForgetTxHash(tx.GetHash());
3430  }
3431  if (RecursiveDynamicUsage(*ptx) < 100000) {
3432  AddToCompactExtraTransactions(ptx);
3433  }
3434  }
3435  }
3436 
3437  // If a tx has been detected by m_recent_rejects, we will have reached
3438  // this point and the tx will have been ignored. Because we haven't
3439  // submitted the tx to our mempool, we won't have computed a DoS
3440  // score for it or determined exactly why we consider it invalid.
3441  //
3442  // This means we won't penalize any peer subsequently relaying a DoSy
3443  // tx (even if we penalized the first peer who gave it to us) because
3444  // we have to account for m_recent_rejects showing false positives. In
3445  // other words, we shouldn't penalize a peer if we aren't *sure* they
3446  // submitted a DoSy tx.
3447  //
3448  // Note that m_recent_rejects doesn't just record DoSy or invalid
3449  // transactions, but any tx not accepted by the mempool, which may be
3450  // due to node policy (vs. consensus). So we can't blanket penalize a
3451  // peer simply for relaying a tx that our m_recent_rejects has caught,
3452  // regardless of false positives.
3453 
3454  if (state.IsInvalid()) {
3455  LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
3456  pfrom.GetId(),
3457  state.ToString());
3458  MaybePunishNodeForTx(pfrom.GetId(), state);
3459  }
3460  return;
3461  }
3462 
3463  if (msg_type == NetMsgType::CMPCTBLOCK)
3464  {
3465  // Ignore cmpctblock received while importing
3466  if (fImporting || fReindex) {
3467  LogPrint(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId());
3468  return;
3469  }
3470 
3471  CBlockHeaderAndShortTxIDs cmpctblock;
3472  vRecv >> cmpctblock;
3473 
3474  bool received_new_header = false;
3475 
3476  {
3477  LOCK(cs_main);
3478 
3479  if (!m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
3480  // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
3481  if (!m_chainman.ActiveChainstate().IsInitialBlockDownload())
3482  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexBestHeader), uint256()));
3483  return;
3484  }
3485 
3486  if (!m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.GetHash())) {
3487  received_new_header = true;
3488  }
3489  }
3490 
3491  const CBlockIndex *pindex = nullptr;
3492  BlockValidationState state;
3493  if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header}, state, m_chainparams, &pindex)) {
3494  if (state.IsInvalid()) {
3495  MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block*/ true, "invalid header via cmpctblock");
3496  return;
3497  }
3498  }
3499 
3500  // When we succeed in decoding a block's txids from a cmpctblock
3501  // message we typically jump to the BLOCKTXN handling code, with a
3502  // dummy (empty) BLOCKTXN message, to re-use the logic there in
3503  // completing processing of the putative block (without cs_main).
3504  bool fProcessBLOCKTXN = false;
3506 
3507  // If we end up treating this as a plain headers message, call that as well
3508  // without cs_main.
3509  bool fRevertToHeaderProcessing = false;
3510 
3511  // Keep a CBlock for "optimistic" compactblock reconstructions (see
3512  // below)
3513  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3514  bool fBlockReconstructed = false;
3515 
3516  {
3518  // If AcceptBlockHeader returned true, it set pindex
3519  assert(pindex);
3520  UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
3521 
3522  CNodeState *nodestate = State(pfrom.GetId());
3523 
3524  // If this was a new header with more work than our tip, update the
3525  // peer's last block announcement time
3526  if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
3527  nodestate->m_last_block_announcement = GetTime();
3528  }
3529 
3530  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
3531  bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
3532 
3533  if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
3534  return;
3535 
3536  if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better
3537  pindex->nTx != 0) { // We had this block at some point, but pruned it
3538  if (fAlreadyInFlight) {
3539  // We requested this block for some reason, but our mempool will probably be useless
3540  // so we just grab the block via normal getdata
3541  std::vector<CInv> vInv(1);
3542  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
3543  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
3544  }
3545  return;
3546  }
3547 
3548  // If we're not close to tip yet, give up and let parallel block fetch work its magic
3549  if (!fAlreadyInFlight && !CanDirectFetch()) {
3550  return;
3551  }
3552 
3553  if (DeploymentActiveAt(*pindex, m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT) && !nodestate->fSupportsDesiredCmpctVersion) {
3554  // Don't bother trying to process compact blocks from v1 peers
3555  // after segwit activates.
3556  return;
3557  }
3558 
3559  // We want to be a bit conservative just to be extra careful about DoS
3560  // possibilities in compact block processing...
3561  if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
3562  if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
3563  (fAlreadyInFlight && blockInFlightIt->second.first == pfrom.GetId())) {
3564  std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
3565  if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) {
3566  if (!(*queuedBlockIt)->partialBlock)
3567  (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool));
3568  else {
3569  // The block was already in flight using compact blocks from the same peer
3570  LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
3571  return;
3572  }
3573  }
3574 
3575  PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
3576  ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
3577  if (status == READ_STATUS_INVALID) {
3578  RemoveBlockRequest(pindex->GetBlockHash()); // Reset in-flight state in case Misbehaving does not result in a disconnect
3579  Misbehaving(pfrom.GetId(), 100, "invalid compact block");
3580  return;
3581  } else if (status == READ_STATUS_FAILED) {
3582  // Duplicate txindexes, the block is now in-flight, so just request it
3583  std::vector<CInv> vInv(1);
3584  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
3585  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
3586  return;
3587  }
3588 
3590  for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
3591  if (!partialBlock.IsTxAvailable(i))
3592  req.indexes.push_back(i);
3593  }
3594  if (req.indexes.empty()) {
3595  // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
3596  BlockTransactions txn;
3597  txn.blockhash = cmpctblock.header.GetHash();
3598  blockTxnMsg << txn;
3599  fProcessBLOCKTXN = true;
3600  } else {
3601  req.blockhash = pindex->GetBlockHash();
3602  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
3603  }
3604  } else {
3605  // This block is either already in flight from a different
3606  // peer, or this peer has too many blocks outstanding to
3607  // download from.
3608  // Optimistically try to reconstruct anyway since we might be
3609  // able to without any round trips.
3610  PartiallyDownloadedBlock tempBlock(&m_mempool);
3611  ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
3612  if (status != READ_STATUS_OK) {
3613  // TODO: don't ignore failures
3614  return;
3615  }
3616  std::vector<CTransactionRef> dummy;
3617  status = tempBlock.FillBlock(*pblock, dummy);
3618  if (status == READ_STATUS_OK) {
3619  fBlockReconstructed = true;
3620  }
3621  }
3622  } else {
3623  if (fAlreadyInFlight) {
3624  // We requested this block, but its far into the future, so our
3625  // mempool will probably be useless - request the block normally
3626  std::vector<CInv> vInv(1);
3627  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
3628  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
3629  return;
3630  } else {
3631  // If this was an announce-cmpctblock, we want the same treatment as a header message
3632  fRevertToHeaderProcessing = true;
3633  }
3634  }
3635  } // cs_main
3636 
3637  if (fProcessBLOCKTXN) {
3638  return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, time_received, interruptMsgProc);
3639  }
3640 
3641  if (fRevertToHeaderProcessing) {
3642  // Headers received from HB compact block peers are permitted to be
3643  // relayed before full validation (see BIP 152), so we don't want to disconnect
3644  // the peer if the header turns out to be for an invalid block.
3645  // Note that if a peer tries to build on an invalid chain, that
3646  // will be detected and the peer will be disconnected/discouraged.
3647  return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true);
3648  }
3649 
3650  if (fBlockReconstructed) {
3651  // If we got here, we were able to optimistically reconstruct a
3652  // block that is in flight from some other peer.
3653  {
3654  LOCK(cs_main);
3655  mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false));
3656  }
3657  // Setting force_processing to true means that we bypass some of
3658  // our anti-DoS protections in AcceptBlock, which filters
3659  // unrequested blocks that might be trying to waste our resources
3660  // (eg disk space). Because we only try to reconstruct blocks when
3661  // we're close to caught up (via the CanDirectFetch() requirement
3662  // above, combined with the behavior of not requesting blocks until
3663  // we have a chain with at least nMinimumChainWork), and we ignore
3664  // compact blocks with less work than our tip, it is safe to treat
3665  // reconstructed compact blocks as having been requested.
3666  ProcessBlock(pfrom, pblock, /*force_processing=*/true);
3667  LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
3668  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
3669  // Clear download state for this block, which is in
3670  // process from some other peer. We do this after calling
3671  // ProcessNewBlock so that a malleated cmpctblock announcement
3672  // can't be used to interfere with block relay.
3673  RemoveBlockRequest(pblock->GetHash());
3674  }
3675  }
3676  return;
3677  }
3678 
3679  if (msg_type == NetMsgType::BLOCKTXN)
3680  {
3681  // Ignore blocktxn received while importing
3682  if (fImporting || fReindex) {
3683  LogPrint(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId());
3684  return;
3685  }
3686 
3687  BlockTransactions resp;
3688  vRecv >> resp;
3689 
3690  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3691  bool fBlockRead = false;
3692  {
3693  LOCK(cs_main);
3694 
3695  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
3696  if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
3697  it->second.first != pfrom.GetId()) {
3698  LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId());
3699  return;
3700  }
3701 
3702  PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
3703  ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
3704  if (status == READ_STATUS_INVALID) {
3705  RemoveBlockRequest(resp.blockhash); // Reset in-flight state in case Misbehaving does not result in a disconnect
3706  Misbehaving(pfrom.GetId(), 100, "invalid compact block/non-matching block transactions");
3707  return;
3708  } else if (status == READ_STATUS_FAILED) {
3709  // Might have collided, fall back to getdata now :(
3710  std::vector<CInv> invs;
3711  invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
3712  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
3713  } else {
3714  // Block is either okay, or possibly we received
3715  // READ_STATUS_CHECKBLOCK_FAILED.
3716  // Note that CheckBlock can only fail for one of a few reasons:
3717  // 1. bad-proof-of-work (impossible here, because we've already
3718  // accepted the header)
3719  // 2. merkleroot doesn't match the transactions given (already
3720  // caught in FillBlock with READ_STATUS_FAILED, so
3721  // impossible here)
3722  // 3. the block is otherwise invalid (eg invalid coinbase,
3723  // block is too big, too many legacy sigops, etc).
3724  // So if CheckBlock failed, #3 is the only possibility.
3725  // Under BIP 152, we don't discourage the peer unless proof of work is
3726  // invalid (we don't require all the stateless checks to have
3727  // been run). This is handled below, so just treat this as
3728  // though the block was successfully read, and rely on the
3729  // handling in ProcessNewBlock to ensure the block index is
3730  // updated, etc.
3731  RemoveBlockRequest(resp.blockhash); // it is now an empty pointer
3732  fBlockRead = true;
3733  // mapBlockSource is used for potentially punishing peers and
3734  // updating which peers send us compact blocks, so the race
3735  // between here and cs_main in ProcessNewBlock is fine.
3736  // BIP 152 permits peers to relay compact blocks after validating
3737  // the header only; we should not punish peers if the block turns
3738  // out to be invalid.
3739  mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom.GetId(), false));
3740  }
3741  } // Don't hold cs_main when we call into ProcessNewBlock
3742  if (fBlockRead) {
3743  // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
3744  // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
3745  // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
3746  // disk-space attacks), but this should be safe due to the
3747  // protections in the compact block handler -- see related comment
3748  // in compact block optimistic reconstruction handling.
3749  ProcessBlock(pfrom, pblock, /*force_processing=*/true);
3750  }
3751  return;
3752  }
3753 
3754  if (msg_type == NetMsgType::HEADERS)
3755  {
3756  // Ignore headers received while importing
3757  if (fImporting || fReindex) {
3758  LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
3759  return;
3760  }
3761 
3762  std::vector<CBlockHeader> headers;
3763 
3764  // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
3765  unsigned int nCount = ReadCompactSize(vRecv);
3766  if (nCount > MAX_HEADERS_RESULTS) {
3767  Misbehaving(pfrom.GetId(), 20, strprintf("headers message size = %u", nCount));
3768  return;
3769  }
3770  headers.resize(nCount);
3771  for (unsigned int n = 0; n < nCount; n++) {
3772  vRecv >> headers[n];
3773  ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
3774  }
3775 
3776  return ProcessHeadersMessage(pfrom, *peer, headers, /*via_compact_block=*/false);
3777  }
3778 
3779  if (msg_type == NetMsgType::BLOCK)
3780  {
3781  // Ignore block received while importing
3782  if (fImporting || fReindex) {
3783  LogPrint(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId());
3784  return;
3785  }
3786 
3787  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3788  vRecv >> *pblock;
3789 
3790  LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId());
3791 
3792  bool forceProcessing = false;
3793  const uint256 hash(pblock->GetHash());
3794  {
3795  LOCK(cs_main);
3796  // Always process the block if we requested it, since we may
3797  // need it even when it's not a candidate for a new best tip.
3798  forceProcessing = IsBlockRequested(hash);
3799  RemoveBlockRequest(hash);
3800  // mapBlockSource is only used for punishing peers and setting
3801  // which peers send us compact blocks, so the race between here and
3802  // cs_main in ProcessNewBlock is fine.
3803  mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
3804  }
3805  ProcessBlock(pfrom, pblock, forceProcessing);
3806  return;
3807  }
3808 
3809  if (msg_type == NetMsgType::GETADDR) {
3810  // This asymmetric behavior for inbound and outbound connections was introduced
3811  // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3812  // to users' AddrMan and later request them by sending getaddr messages.
3813  // Making nodes which are behind NAT and can only make outgoing connections ignore
3814  // the getaddr message mitigates the attack.
3815  if (!pfrom.IsInboundConn()) {
3816  LogPrint(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId());
3817  return;
3818  }
3819 
3820  // Since this must be an inbound connection, SetupAddressRelay will
3821  // never fail.
3822  Assume(SetupAddressRelay(pfrom, *peer));
3823 
3824  // Only send one GetAddr response per connection to reduce resource waste
3825  // and discourage addr stamping of INV announcements.
3826  if (peer->m_getaddr_recvd) {
3827  LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId());
3828  return;
3829  }
3830  peer->m_getaddr_recvd = true;
3831 
3832  peer->m_addrs_to_send.clear();
3833  std::vector<CAddress> vAddr;
3835  vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /* network */ std::nullopt);
3836  } else {
3837  vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
3838  }
3839  FastRandomContext insecure_rand;
3840  for (const CAddress &addr : vAddr) {
3841  PushAddress(*peer, addr, insecure_rand);
3842  }
3843  return;
3844  }
3845 
3846  if (msg_type == NetMsgType::MEMPOOL) {
3848  {
3850  {
3851  LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom.GetId());
3852  pfrom.fDisconnect = true;
3853  }
3854  return;
3855  }
3856 
3857  if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
3858  {
3860  {
3861  LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom.GetId());
3862  pfrom.fDisconnect = true;
3863  }
3864  return;
3865  }
3866 
3867  if (pfrom.m_tx_relay != nullptr) {
3868  LOCK(pfrom.m_tx_relay->cs_tx_inventory);
3869  pfrom.m_tx_relay->fSendMempool = true;
3870  }
3871  return;
3872  }
3873 
3874  if (msg_type == NetMsgType::PING) {
3875  if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
3876  uint64_t nonce = 0;
3877  vRecv >> nonce;
3878  // Echo the message back with the nonce. This allows for two useful features:
3879  //
3880  // 1) A remote node can quickly check if the connection is operational
3881  // 2) Remote nodes can measure the latency of the network thread. If this node
3882  // is overloaded it won't respond to pings quickly and the remote node can
3883  // avoid sending us more work, like chain download requests.
3884  //
3885  // The nonce stops the remote getting confused between different pings: without
3886  // it, if the remote node sends a ping once per second and this node takes 5
3887  // seconds to respond to each, the 5th ping the remote sends would appear to
3888  // return very quickly.
3889  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
3890  }
3891  return;
3892  }
3893 
3894  if (msg_type == NetMsgType::PONG) {
3895  const auto ping_end = time_received;
3896  uint64_t nonce = 0;
3897  size_t nAvail = vRecv.in_avail();
3898  bool bPingFinished = false;
3899  std::string sProblem;
3900 
3901  if (nAvail >= sizeof(nonce)) {
3902  vRecv >> nonce;
3903 
3904  // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
3905  if (peer->m_ping_nonce_sent != 0) {
3906  if (nonce == peer->m_ping_nonce_sent) {
3907  // Matching pong received, this ping is no longer outstanding
3908  bPingFinished = true;
3909  const auto ping_time = ping_end - peer->m_ping_start.load();
3910  if (ping_time.count() >= 0) {
3911  // Let connman know about this successful ping-pong
3912  pfrom.PongReceived(ping_time);
3913  } else {
3914  // This should never happen
3915  sProblem = "Timing mishap";
3916  }
3917  } else {
3918  // Nonce mismatches are normal when pings are overlapping
3919  sProblem = "Nonce mismatch";
3920  if (nonce == 0) {
3921  // This is most likely a bug in another implementation somewhere; cancel this ping
3922  bPingFinished = true;
3923  sProblem = "Nonce zero";
3924  }
3925  }
3926  } else {
3927  sProblem = "Unsolicited pong without ping";
3928  }
3929  } else {
3930  // This is most likely a bug in another implementation somewhere; cancel this ping
3931  bPingFinished = true;
3932  sProblem = "Short payload";
3933  }
3934 
3935  if (!(sProblem.empty())) {
3936  LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
3937  pfrom.GetId(),
3938  sProblem,
3939  peer->m_ping_nonce_sent,
3940  nonce,
3941  nAvail);
3942  }
3943  if (bPingFinished) {
3944  peer->m_ping_nonce_sent = 0;
3945  }
3946  return;
3947  }
3948 
3949  if (msg_type == NetMsgType::FILTERLOAD) {
3950  if (!(pfrom.GetLocalServices() & NODE_BLOOM)) {
3951  LogPrint(BCLog::NET, "filterload received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
3952  pfrom.fDisconnect = true;
3953  return;
3954  }
3955  CBloomFilter filter;
3956  vRecv >> filter;
3957 
3958  if (!filter.IsWithinSizeConstraints())
3959  {
3960  // There is no excuse for sending a too-large filter
3961  Misbehaving(pfrom.GetId(), 100, "too-large bloom filter");
3962  }
3963  else if (pfrom.m_tx_relay != nullptr)
3964  {
3965  LOCK(pfrom.m_tx_relay->cs_filter);
3966  pfrom.m_tx_relay->pfilter.reset(new CBloomFilter(filter));
3967  pfrom.m_tx_relay->fRelayTxes = true;
3968  }
3969  return;
3970  }
3971 
3972  if (msg_type == NetMsgType::FILTERADD) {
3973  if (!(pfrom.GetLocalServices() & NODE_BLOOM)) {
3974  LogPrint(BCLog::NET, "filteradd received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
3975  pfrom.fDisconnect = true;
3976  return;
3977  }
3978  std::vector<unsigned char> vData;
3979  vRecv >> vData;
3980 
3981  // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3982  // and thus, the maximum size any matched object can have) in a filteradd message
3983  bool bad = false;
3984  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
3985  bad = true;
3986  } else if (pfrom.m_tx_relay != nullptr) {
3987  LOCK(pfrom.m_tx_relay->cs_filter);
3988  if (pfrom.m_tx_relay->pfilter) {
3989  pfrom.m_tx_relay->pfilter->insert(vData);
3990  } else {
3991  bad = true;
3992  }
3993  }
3994  if (bad) {
3995  Misbehaving(pfrom.GetId(), 100, "bad filteradd message");
3996  }
3997  return;
3998  }
3999 
4000  if (msg_type == NetMsgType::FILTERCLEAR) {
4001  if (!(pfrom.GetLocalServices() & NODE_BLOOM)) {
4002  LogPrint(BCLog::NET, "filterclear received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
4003  pfrom.fDisconnect = true;
4004  return;
4005  }
4006  if (pfrom.m_tx_relay == nullptr) {
4007  return;
4008  }
4009  LOCK(pfrom.m_tx_relay->cs_filter);
4010  pfrom.m_tx_relay->pfilter = nullptr;
4011  pfrom.m_tx_relay->fRelayTxes = true;
4012  return;
4013  }
4014 
4015  if (msg_type == NetMsgType::FEEFILTER) {
4016  CAmount newFeeFilter = 0;
4017  vRecv >> newFeeFilter;
4018  if (MoneyRange(newFeeFilter)) {
4019  if (pfrom.m_tx_relay != nullptr) {
4020  pfrom.m_tx_relay->minFeeFilter = newFeeFilter;
4021  }
4022  LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
4023  }
4024  return;
4025  }
4026 
4027  if (msg_type == NetMsgType::GETCFILTERS) {
4028  ProcessGetCFilters(pfrom, vRecv);
4029  return;
4030  }
4031 
4032  if (msg_type == NetMsgType::GETCFHEADERS) {
4033  ProcessGetCFHeaders(pfrom, vRecv);
4034  return;
4035  }
4036 
4037  if (msg_type == NetMsgType::GETCFCHECKPT) {
4038  ProcessGetCFCheckPt(pfrom, vRecv);
4039  return;
4040  }
4041 
4042  if (msg_type == NetMsgType::NOTFOUND) {
4043  std::vector<CInv> vInv;
4044  vRecv >> vInv;
4046  LOCK(::cs_main);
4047  for (CInv &inv : vInv) {
4048  if (inv.IsGenTxMsg()) {
4049  // If we receive a NOTFOUND message for a tx we requested, mark the announcement for it as
4050  // completed in TxRequestTracker.
4051  m_txrequest.ReceivedResponse(pfrom.GetId(), inv.hash);
4052  }
4053  }
4054  }
4055  return;
4056  }
4057 
4058  // Ignore unknown commands for extensibility
4059  LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
4060  return;
4061 }
4062 
4063 bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer)
4064 {
4065  {
4066  LOCK(peer.m_misbehavior_mutex);
4067 
4068  // There's nothing to do if the m_should_discourage flag isn't set
4069  if (!peer.m_should_discourage) return false;
4070 
4071  peer.m_should_discourage = false;
4072  } // peer.m_misbehavior_mutex
4073 
4075  // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission
4076  LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id);
4077  return false;
4078  }
4079 
4080  if (pnode.IsManualConn()) {
4081  // We never disconnect or discourage manual peers for bad behavior
4082  LogPrintf("Warning: not punishing manually connected peer %d!\n", peer.m_id);
4083  return false;
4084  }
4085 
4086  if (pnode.addr.IsLocal()) {
4087  // We disconnect local peers for bad behavior but don't discourage (since that would discourage
4088  // all peers on the same local address)
4089  LogPrint(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n",
4090  pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
4091  pnode.fDisconnect = true;
4092  return true;
4093  }
4094 
4095  // Normal case: Disconnect the peer and discourage all nodes sharing the address
4096  LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id);
4097  if (m_banman) m_banman->Discourage(pnode.addr);
4098  m_connman.DisconnectNode(pnode.addr);
4099  return true;
4100 }
4101 
4102 bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
4103 {
4104  bool fMoreWork = false;
4105 
4106  PeerRef peer = GetPeerRef(pfrom->GetId());
4107  if (peer == nullptr) return false;
4108 
4109  {
4110  LOCK(peer->m_getdata_requests_mutex);
4111  if (!peer->m_getdata_requests.empty()) {
4112  ProcessGetData(*pfrom, *peer, interruptMsgProc);
4113  }
4114  }
4115 
4116  {
4118  if (!peer->m_orphan_work_set.empty()) {
4119  ProcessOrphanTx(peer->m_orphan_work_set);
4120  }
4121  }
4122 
4123  if (pfrom->fDisconnect)
4124  return false;
4125 
4126  // this maintains the order of responses
4127  // and prevents m_getdata_requests to grow unbounded
4128  {
4129  LOCK(peer->m_getdata_requests_mutex);
4130  if (!peer->m_getdata_requests.empty()) return true;
4131  }
4132 
4133  {
4134  LOCK(g_cs_orphans);
4135  if (!peer->m_orphan_work_set.empty()) return true;
4136  }
4137 
4138  // Don't bother if send buffer is too full to respond anyway
4139  if (pfrom->fPauseSend) return false;
4140 
4141  std::list<CNetMessage> msgs;
4142  {
4143  LOCK(pfrom->cs_vProcessMsg);
4144  if (pfrom->vProcessMsg.empty()) return false;
4145  // Just take one message
4146  msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
4147  pfrom->nProcessQueueSize -= msgs.front().m_raw_message_size;
4148  pfrom->fPauseRecv = pfrom->nProcessQueueSize > m_connman.GetReceiveFloodSize();
4149  fMoreWork = !pfrom->vProcessMsg.empty();
4150  }
4151  CNetMessage& msg(msgs.front());
4152 
4153  TRACE6(net, inbound_message,
4154  pfrom->GetId(),
4155  pfrom->m_addr_name.c_str(),
4156  pfrom->ConnectionTypeAsString().c_str(),
4157  msg.m_command.c_str(),
4158  msg.m_recv.size(),
4159  msg.m_recv.data()
4160  );
4161 
4162  if (gArgs.GetBoolArg("-capturemessages", false)) {
4163  CaptureMessage(pfrom->addr, msg.m_command, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true);
4164  }
4165 
4166  msg.SetVersion(pfrom->GetCommonVersion());
4167  const std::string& msg_type = msg.m_command;
4168 
4169  // Message size
4170  unsigned int nMessageSize = msg.m_message_size;
4171 
4172  try {
4173  ProcessMessage(*pfrom, msg_type, msg.m_recv, msg.m_time, interruptMsgProc);
4174  if (interruptMsgProc) return false;
4175  {
4176  LOCK(peer->m_getdata_requests_mutex);
4177  if (!peer->m_getdata_requests.empty()) fMoreWork = true;
4178  }
4179  } catch (const std::exception& e) {
4180  LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg_type), nMessageSize, e.what(), typeid(e).name());
4181  } catch (...) {
4182  LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg_type), nMessageSize);
4183  }
4184 
4185  return fMoreWork;
4186 }
4187 
4188 void PeerManagerImpl::ConsiderEviction(CNode& pto, std::chrono::seconds time_in_seconds)
4189 {
4191 
4192  CNodeState &state = *State(pto.GetId());
4193  const CNetMsgMaker msgMaker(pto.GetCommonVersion());
4194 
4195  if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) {
4196  // This is an outbound peer subject to disconnection if they don't
4197  // announce a block with as much work as the current tip within
4198  // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
4199  // their chain has more work than ours, we should sync to it,
4200  // unless it's invalid, in which case we should find that out and
4201  // disconnect from them elsewhere).
4202  if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
4203  if (state.m_chain_sync.m_timeout != 0s) {
4204  state.m_chain_sync.m_timeout = 0s;
4205  state.m_chain_sync.m_work_header = nullptr;
4206  state.m_chain_sync.m_sent_getheaders = false;
4207  }
4208  } 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)) {
4209  // Our best block known by this peer is behind our tip, and we're either noticing
4210  // that for the first time, OR this peer was able to catch up to some earlier point
4211  // where we checked against our tip.
4212  // Either way, set a new timeout based on current tip.
4213  state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
4214  state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
4215  state.m_chain_sync.m_sent_getheaders = false;
4216  } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) {
4217  // No evidence yet that our peer has synced to a chain with work equal to that
4218  // of our tip, when we first detected it was behind. Send a single getheaders
4219  // message to give the peer a chance to update us.
4220  if (state.m_chain_sync.m_sent_getheaders) {
4221  // They've run out of time to catch up!
4222  LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
4223  pto.fDisconnect = true;
4224  } else {
4225  assert(state.m_chain_sync.m_work_header);
4226  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());
4227  m_connman.PushMessage(&pto, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
4228  state.m_chain_sync.m_sent_getheaders = true;
4229  constexpr auto HEADERS_RESPONSE_TIME{2min};
4230  // Bump the timeout to allow a response, which could clear the timeout
4231  // (if the response shows the peer has synced), reset the timeout (if
4232  // the peer syncs to the required work but not to our tip), or result
4233  // in disconnect (if we advance to the timeout and pindexBestKnownBlock
4234  // has not sufficiently progressed)
4235  state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
4236  }
4237  }
4238  }
4239 }
4240 
4241 void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now)
4242 {
4243  // If we have any extra block-relay-only peers, disconnect the youngest unless
4244  // it's given us a block -- in which case, compare with the second-youngest, and
4245  // out of those two, disconnect the peer who least recently gave us a block.
4246  // The youngest block-relay-only peer would be the extra peer we connected
4247  // to temporarily in order to sync our tip; see net.cpp.
4248  // Note that we use higher nodeid as a measure for most recent connection.
4249  if (m_connman.GetExtraBlockRelayCount() > 0) {
4250  std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0};
4251 
4252  m_connman.ForEachNode([&](CNode* pnode) {
4253  if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return;
4254  if (pnode->GetId() > youngest_peer.first) {
4255  next_youngest_peer = youngest_peer;
4256  youngest_peer.first = pnode->GetId();
4257  youngest_peer.second = pnode->m_last_block_time;
4258  }
4259  });
4260  NodeId to_disconnect = youngest_peer.first;
4261  if (youngest_peer.second > next_youngest_peer.second) {
4262  // Our newest block-relay-only peer gave us a block more recently;
4263  // disconnect our second youngest.
4264  to_disconnect = next_youngest_peer.first;
4265  }
4266  m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
4268  // Make sure we're not getting a block right now, and that
4269  // we've been connected long enough for this eviction to happen
4270  // at all.
4271  // Note that we only request blocks from a peer if we learn of a
4272  // valid headers chain with at least as much work as our tip.
4273  CNodeState *node_state = State(pnode->GetId());
4274  if (node_state == nullptr ||
4275  (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->nBlocksInFlight == 0)) {
4276  pnode->fDisconnect = true;
4277  LogPrint(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n",
4278  pnode->GetId(), count_seconds(pnode->m_last_block_time));
4279  return true;
4280  } else {
4281  LogPrint(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
4282  pnode->GetId(), count_seconds(pnode->m_connected), node_state->nBlocksInFlight);
4283  }
4284  return false;
4285  });
4286  }
4287 
4288  // Check whether we have too many outbound-full-relay peers
4289  if (m_connman.GetExtraFullOutboundCount() > 0) {
4290  // If we have more outbound-full-relay peers than we target, disconnect one.
4291  // Pick the outbound-full-relay peer that least recently announced
4292  // us a new block, with ties broken by choosing the more recent
4293  // connection (higher node id)
4294  NodeId worst_peer = -1;
4295  int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
4296 
4297  m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
4299 
4300  // Only consider outbound-full-relay peers that are not already
4301  // marked for disconnection
4302  if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return;
4303  CNodeState *state = State(pnode->GetId());
4304  if (state == nullptr) return; // shouldn't be possible, but just in case
4305  // Don't evict our protected peers
4306  if (state->m_chain_sync.m_protect) return;
4307  if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
4308  worst_peer = pnode->GetId();
4309  oldest_block_announcement = state->m_last_block_announcement;
4310  }
4311  });
4312  if (worst_peer != -1) {
4313  bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
4315 
4316  // Only disconnect a peer that has been connected to us for
4317  // some reasonable fraction of our check-frequency, to give
4318  // it time for new information to have arrived.
4319  // Also don't disconnect any peer we're trying to download a
4320  // block from.
4321  CNodeState &state = *State(pnode->GetId());
4322  if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
4323  LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
4324  pnode->fDisconnect = true;
4325  return true;
4326  } else {
4327  LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
4328  pnode->GetId(), count_seconds(pnode->m_connected), state.nBlocksInFlight);
4329  return false;
4330  }
4331  });
4332  if (disconnected) {
4333  // If we disconnected an extra peer, that means we successfully
4334  // connected to at least one peer after the last time we
4335  // detected a stale tip. Don't try any more extra peers until
4336  // we next detect a stale tip, to limit the load we put on the
4337  // network from these extra connections.
4338  m_connman.SetTryNewOutboundPeer(false);
4339  }
4340  }
4341  }
4342 }
4343 
4344 void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
4345 {
4346  LOCK(cs_main);
4347 
4348  auto now{GetTime<std::chrono::seconds>()};
4349 
4350  EvictExtraOutboundPeers(now);
4351 
4352  if (now > m_stale_tip_check_time) {
4353  // Check whether our tip is stale, and if so, allow using an extra
4354  // outbound peer
4355  if (!fImporting && !fReindex && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
4356  LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
4357  count_seconds(now - m_last_tip_update.load()));
4358  m_connman.SetTryNewOutboundPeer(true);
4359  } else if (m_connman.GetTryNewOutboundPeer()) {
4360  m_connman.SetTryNewOutboundPeer(false);
4361  }
4362  m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
4363  }
4364 
4365  if (!m_initial_sync_finished && CanDirectFetch()) {
4366  m_connman.StartExtraBlockRelayPeers();
4367  m_initial_sync_finished = true;
4368  }
4369 }
4370 
4371 void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now)
4372 {
4373  if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
4374  peer.m_ping_nonce_sent &&
4375  now > peer.m_ping_start.load() + TIMEOUT_INTERVAL)
4376  {
4377  // The ping timeout is using mocktime. To disable the check during
4378  // testing, increase -peertimeout.
4379  LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), peer.m_id);
4380  node_to.fDisconnect = true;
4381  return;
4382  }
4383 
4384  const CNetMsgMaker msgMaker(node_to.GetCommonVersion());
4385  bool pingSend = false;
4386 
4387  if (peer.m_ping_queued) {
4388  // RPC ping request by user
4389  pingSend = true;
4390  }
4391 
4392  if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) {
4393  // Ping automatically sent as a latency probe & keepalive.
4394  pingSend = true;
4395  }
4396 
4397  if (pingSend) {
4398  uint64_t nonce = 0;
4399  while (nonce == 0) {
4400  GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4401  }
4402  peer.m_ping_queued = false;
4403  peer.m_ping_start = now;
4404  if (node_to.GetCommonVersion() > BIP0031_VERSION) {
4405  peer.m_ping_nonce_sent = nonce;
4406  m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING, nonce));
4407  } else {
4408  // Peer is too old to support ping command with nonce, pong will never arrive.
4409  peer.m_ping_nonce_sent = 0;
4410  m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING));
4411  }
4412  }
4413 }
4414 
4415 void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time)
4416 {
4417  // Nothing to do for non-address-relay peers
4418  if (!peer.m_addr_relay_enabled) return;
4419 
4420  LOCK(peer.m_addr_send_times_mutex);
4421  // Periodically advertise our local address to the peer.
4422  if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
4423  peer.m_next_local_addr_send < current_time) {
4424  // If we've sent before, clear the bloom filter for the peer, so that our
4425  // self-announcement will actually go out.
4426  // This might be unnecessary if the bloom filter has already rolled
4427  // over since our last self-announcement, but there is only a small
4428  // bandwidth cost that we can incur by doing this (which happens
4429  // once a day on average).
4430  if (peer.m_next_local_addr_send != 0us) {
4431  peer.m_addr_known->reset();
4432  }
4433  if (std::optional<CAddress> local_addr = GetLocalAddrForPeer(&node)) {
4434  FastRandomContext insecure_rand;
4435  PushAddress(peer, *local_addr, insecure_rand);
4436  }
4437  peer.m_next_local_addr_send = PoissonNextSend(current_time, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
4438  }
4439 
4440  // We sent an `addr` message to this peer recently. Nothing more to do.
4441  if (current_time <= peer.m_next_addr_send) return;
4442 
4443  peer.m_next_addr_send = PoissonNextSend(current_time, AVG_ADDRESS_BROADCAST_INTERVAL);
4444 
4445  if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) {
4446  // Should be impossible since we always check size before adding to
4447  // m_addrs_to_send. Recover by trimming the vector.
4448  peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND);
4449  }
4450 
4451  // Remove addr records that the peer already knows about, and add new
4452  // addrs to the m_addr_known filter on the same pass.
4453  auto addr_already_known = [&peer](const CAddress& addr) {
4454  bool ret = peer.m_addr_known->contains(addr.GetKey());
4455  if (!ret) peer.m_addr_known->insert(addr.GetKey());
4456  return ret;
4457  };
4458  peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known),
4459  peer.m_addrs_to_send.end());
4460 
4461  // No addr messages to send
4462  if (peer.m_addrs_to_send.empty()) return;
4463 
4464  const char* msg_type;
4465  int make_flags;
4466  if (peer.m_wants_addrv2) {
4467  msg_type = NetMsgType::ADDRV2;
4468  make_flags = ADDRV2_FORMAT;
4469  } else {
4470  msg_type = NetMsgType::ADDR;
4471  make_flags = 0;
4472  }
4473  m_connman.PushMessage(&node, CNetMsgMaker(node.GetCommonVersion()).Make(make_flags, msg_type, peer.m_addrs_to_send));
4474  peer.m_addrs_to_send.clear();
4475 
4476  // we only send the big addr message once
4477  if (peer.m_addrs_to_send.capacity() > 40) {
4478  peer.m_addrs_to_send.shrink_to_fit();
4479  }
4480 }
4481 
4482 void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, std::chrono::microseconds current_time)
4483 {
4485 
4486  if (m_ignore_incoming_txs) return;
4487  if (!pto.m_tx_relay) return;
4488  if (pto.GetCommonVersion() < FEEFILTER_VERSION) return;
4489  // peers with the forcerelay permission should not filter txs to us
4491 
4492  CAmount currentFilter = m_mempool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
4493  static FeeFilterRounder g_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}};
4494 
4495  if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
4496  // Received tx-inv messages are discarded when the active
4497  // chainstate is in IBD, so tell the peer to not send them.
4498  currentFilter = MAX_MONEY;
4499  } else {
4500  static const CAmount MAX_FILTER{g_filter_rounder.round(MAX_MONEY)};
4501  if (pto.m_tx_relay->lastSentFeeFilter == MAX_FILTER) {
4502  // Send the current filter if we sent MAX_FILTER previously
4503  // and made it out of IBD.
4504  pto.m_tx_relay->m_next_send_feefilter = 0us;
4505  }
4506  }
4507  if (current_time > pto.m_tx_relay->m_next_send_feefilter) {
4508  CAmount filterToSend = g_filter_rounder.round(currentFilter);
4509  // We always have a fee filter of at least minRelayTxFee
4510  filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
4511  if (filterToSend != pto.m_tx_relay->lastSentFeeFilter) {
4512  m_connman.PushMessage(&pto, CNetMsgMaker(pto.GetCommonVersion()).Make(NetMsgType::FEEFILTER, filterToSend));
4513  pto.m_tx_relay->lastSentFeeFilter = filterToSend;
4514  }
4515  pto.m_tx_relay->m_next_send_feefilter = PoissonNextSend(current_time, AVG_FEEFILTER_BROADCAST_INTERVAL);
4516  }
4517  // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
4518  // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
4519  else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < pto.m_tx_relay->m_next_send_feefilter &&
4520  (currentFilter < 3 * pto.m_tx_relay->lastSentFeeFilter / 4 || currentFilter > 4 * pto.m_tx_relay->lastSentFeeFilter / 3)) {
4521  pto.m_tx_relay->m_next_send_feefilter = current_time + GetRandomDuration<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
4522  }
4523 }
4524 
4525 namespace {
4526 class CompareInvMempoolOrder
4527 {
4528  CTxMemPool *mp;
4529  bool m_wtxid_relay;
4530 public:
4531  explicit CompareInvMempoolOrder(CTxMemPool *_mempool, bool use_wtxid)
4532  {
4533  mp = _mempool;
4534  m_wtxid_relay = use_wtxid;
4535  }
4536 
4537  bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
4538  {
4539  /* As std::make_heap produces a max-heap, we want the entries with the
4540  * fewest ancestors/highest fee to sort later. */
4541  return mp->CompareDepthAndScore(*b, *a, m_wtxid_relay);
4542  }
4543 };
4544 }
4545 
4546 bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer)
4547 {
4548  // We don't participate in addr relay with outbound block-relay-only
4549  // connections to prevent providing adversaries with the additional
4550  // information of addr traffic to infer the link.
4551  if (node.IsBlockOnlyConn()) return false;
4552 
4553  if (!peer.m_addr_relay_enabled.exchange(true)) {
4554  // First addr message we have received from the peer, initialize
4555  // m_addr_known
4556  peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
4557  }
4558 
4559  return true;
4560 }
4561 
4562 bool PeerManagerImpl::SendMessages(CNode* pto)
4563 {
4564  PeerRef peer = GetPeerRef(pto->GetId());
4565  if (!peer) return false;
4566  const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
4567 
4568  // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
4569  // disconnect misbehaving peers even before the version handshake is complete.
4570  if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true;
4571 
4572  // Don't send anything until the version handshake is complete
4573  if (!pto->fSuccessfullyConnected || pto->fDisconnect)
4574  return true;
4575 
4576  // If we get here, the outgoing message serialization version is set and can't change.
4577  const CNetMsgMaker msgMaker(pto->GetCommonVersion());
4578 
4579  const auto current_time{GetTime<std::chrono::microseconds>()};
4580 
4581  if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
4582  LogPrint(BCLog::NET, "addrfetch connection timeout; disconnecting peer=%d\n", pto->GetId());
4583  pto->fDisconnect = true;
4584  return true;
4585  }
4586 
4587  MaybeSendPing(*pto, *peer, current_time);
4588 
4589  // MaybeSendPing may have marked peer for disconnection
4590  if (pto->fDisconnect) return true;
4591 
4592  MaybeSendAddr(*pto, *peer, current_time);
4593 
4594  {
4595  LOCK(cs_main);
4596 
4597  CNodeState &state = *State(pto->GetId());
4598 
4599  // Start block sync
4600  if (pindexBestHeader == nullptr)
4601  pindexBestHeader = m_chainman.ActiveChain().Tip();
4602  bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->IsAddrFetchConn()); // Download if this is a nice peer, or we have no nice peers and this one might do.
4603  if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
4604  // Only actively request headers from a single peer, unless we're close to today.
4605  if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4606  state.fSyncStarted = true;
4607  state.m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
4608  (
4609  // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
4610  // to maintain precision
4611  std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
4613  );
4614  nSyncStarted++;
4615  const CBlockIndex *pindexStart = pindexBestHeader;
4616  /* If possible, start at the block preceding the currently
4617  best known header. This ensures that we always get a
4618  non-empty list of headers back as long as the peer
4619  is up-to-date. With a non-empty response, we can initialise
4620  the peer's known best block. This wouldn't be possible
4621  if we requested starting at pindexBestHeader and
4622  got back an empty response. */
4623  if (pindexStart->pprev)
4624  pindexStart = pindexStart->pprev;
4625  LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height);
4626  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexStart), uint256()));
4627  }
4628  }
4629 
4630  //
4631  // Try sending block announcements via headers
4632  //
4633  {
4634  // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
4635  // list of block hashes we're relaying, and our peer wants
4636  // headers announcements, then find the first header
4637  // not yet known to our peer but would connect, and send.
4638  // If no header would connect, or if we have too many
4639  // blocks, or if the peer doesn't want headers, just
4640  // add all to the inv queue.
4641  LOCK(peer->m_block_inv_mutex);
4642  std::vector<CBlock> vHeaders;
4643  bool fRevertToInv = ((!state.fPreferHeaders &&
4644  (!state.fPreferHeaderAndIDs || peer->m_blocks_for_headers_relay.size() > 1)) ||
4645  peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE);
4646  const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
4647  ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
4648 
4649  if (!fRevertToInv) {
4650  bool fFoundStartingHeader = false;
4651  // Try to find first header that our peer doesn't have, and
4652  // then send all headers past that one. If we come across any
4653  // headers that aren't on m_chainman.ActiveChain(), give up.
4654  for (const uint256& hash : peer->m_blocks_for_headers_relay) {
4655  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
4656  assert(pindex);
4657  if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
4658  // Bail out if we reorged away from this block
4659  fRevertToInv = true;
4660  break;
4661  }
4662  if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
4663  // This means that the list of blocks to announce don't
4664  // connect to each other.
4665  // This shouldn't really be possible to hit during
4666  // regular operation (because reorgs should take us to
4667  // a chain that has some block not on the prior chain,
4668  // which should be caught by the prior check), but one
4669  // way this could happen is by using invalidateblock /
4670  // reconsiderblock repeatedly on the tip, causing it to
4671  // be added multiple times to m_blocks_for_headers_relay.
4672  // Robustly deal with this rare situation by reverting
4673  // to an inv.
4674  fRevertToInv = true;
4675  break;
4676  }
4677  pBestIndex = pindex;
4678  if (fFoundStartingHeader) {
4679  // add this to the headers message
4680  vHeaders.push_back(pindex->GetBlockHeader());
4681  } else if (PeerHasHeader(&state, pindex)) {
4682  continue; // keep looking for the first new block
4683  } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
4684  // Peer doesn't have this header but they do have the prior one.
4685  // Start sending headers.
4686  fFoundStartingHeader = true;
4687  vHeaders.push_back(pindex->GetBlockHeader());
4688  } else {
4689  // Peer doesn't have this header or the prior one -- nothing will
4690  // connect, so bail out.
4691  fRevertToInv = true;
4692  break;
4693  }
4694  }
4695  }
4696  if (!fRevertToInv && !vHeaders.empty()) {
4697  if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
4698  // We only send up to 1 block as header-and-ids, as otherwise
4699  // probably means we're doing an initial-ish-sync or they're slow
4700  LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
4701  vHeaders.front().GetHash().ToString(), pto->GetId());
4702 
4703  int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
4704 
4705  bool fGotBlockFromCache = false;
4706  {
4708  if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
4709  if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
4710  m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
4711  else {
4712  CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
4713  m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
4714  }
4715  fGotBlockFromCache = true;
4716  }
4717  }
4718  if (!fGotBlockFromCache) {
4719  CBlock block;
4720  bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
4721  assert(ret);
4722  CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
4723  m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
4724  }
4725  state.pindexBestHeaderSent = pBestIndex;
4726  } else if (state.fPreferHeaders) {
4727  if (vHeaders.size() > 1) {
4728  LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
4729  vHeaders.size(),
4730  vHeaders.front().GetHash().ToString(),
4731  vHeaders.back().GetHash().ToString(), pto->GetId());
4732  } else {
4733  LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
4734  vHeaders.front().GetHash().ToString(), pto->GetId());
4735  }
4736  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
4737  state.pindexBestHeaderSent = pBestIndex;
4738  } else
4739  fRevertToInv = true;
4740  }
4741  if (fRevertToInv) {
4742  // If falling back to using an inv, just try to inv the tip.
4743  // The last entry in m_blocks_for_headers_relay was our tip at some point
4744  // in the past.
4745  if (!peer->m_blocks_for_headers_relay.empty()) {
4746  const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back();
4747  const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
4748  assert(pindex);
4749 
4750  // Warn if we're announcing a block that is not on the main chain.
4751  // This should be very rare and could be optimized out.
4752  // Just log for now.
4753  if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
4754  LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
4755  hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString());
4756  }
4757 
4758  // If the peer's chain has this block, don't inv it back.
4759  if (!PeerHasHeader(&state, pindex)) {
4760  peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
4761  LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
4762  pto->GetId(), hashToAnnounce.ToString());
4763  }
4764  }
4765  }
4766  peer->m_blocks_for_headers_relay.clear();
4767  }
4768 
4769  //
4770  // Message: inventory
4771  //
4772  std::vector<CInv> vInv;
4773  {
4774  LOCK(peer->m_block_inv_mutex);
4775  vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_MAX));
4776 
4777  // Add blocks
4778  for (const uint256& hash : peer->m_blocks_for_inv_relay) {
4779  vInv.push_back(CInv(MSG_BLOCK, hash));
4780  if (vInv.size() == MAX_INV_SZ) {
4781  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4782  vInv.clear();
4783  }
4784  }
4785  peer->m_blocks_for_inv_relay.clear();
4786  }
4787 
4788  if (pto->m_tx_relay != nullptr) {
4789  LOCK(pto->m_tx_relay->cs_tx_inventory);
4790  // Check whether periodic sends should happen
4791  bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
4792  if (pto->m_tx_relay->nNextInvSend < current_time) {
4793  fSendTrickle = true;
4794  if (pto->IsInboundConn()) {
4795  pto->m_tx_relay->nNextInvSend = m_connman.PoissonNextSendInbound(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL);
4796  } else {
4797  pto->m_tx_relay->nNextInvSend = PoissonNextSend(current_time, OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
4798  }
4799  }
4800 
4801  // Time to send but the peer has requested we not relay transactions.
4802  if (fSendTrickle) {
4803  LOCK(pto->m_tx_relay->cs_filter);
4804  if (!pto->m_tx_relay->fRelayTxes) pto->m_tx_relay->setInventoryTxToSend.clear();
4805  }
4806 
4807  // Respond to BIP35 mempool requests
4808  if (fSendTrickle && pto->m_tx_relay->fSendMempool) {
4809  auto vtxinfo = m_mempool.infoAll();
4810  pto->m_tx_relay->fSendMempool = false;
4811  const CFeeRate filterrate{pto->m_tx_relay->minFeeFilter.load()};
4812 
4813  LOCK(pto->m_tx_relay->cs_filter);
4814 
4815  for (const auto& txinfo : vtxinfo) {
4816  const uint256& hash = state.m_wtxid_relay ? txinfo.tx->GetWitnessHash() : txinfo.tx->GetHash();
4817  CInv inv(state.m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
4818  pto->m_tx_relay->setInventoryTxToSend.erase(hash);
4819  // Don't send transactions that peers will not put into their mempool
4820  if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
4821  continue;
4822  }
4823  if (pto->m_tx_relay->pfilter) {
4824  if (!pto->m_tx_relay->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
4825  }
4826  pto->m_tx_relay->filterInventoryKnown.insert(hash);
4827  // Responses to MEMPOOL requests bypass the m_recently_announced_invs filter.
4828  vInv.push_back(inv);
4829  if (vInv.size() == MAX_INV_SZ) {
4830  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4831  vInv.clear();
4832  }
4833  }
4834  pto->m_tx_relay->m_last_mempool_req = std::chrono::duration_cast<std::chrono::seconds>(current_time);
4835  }
4836 
4837  // Determine transactions to relay
4838  if (fSendTrickle) {
4839  // Produce a vector with all candidates for sending
4840  std::vector<std::set<uint256>::iterator> vInvTx;
4841  vInvTx.reserve(pto->m_tx_relay->setInventoryTxToSend.size());
4842  for (std::set<uint256>::iterator it = pto->m_tx_relay->setInventoryTxToSend.begin(); it != pto->m_tx_relay->setInventoryTxToSend.end(); it++) {
4843  vInvTx.push_back(it);
4844  }
4845  const CFeeRate filterrate{pto->m_tx_relay->minFeeFilter.load()};
4846  // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
4847  // A heap is used so that not all items need sorting if only a few are being sent.
4848  CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, state.m_wtxid_relay);
4849  std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
4850  // No reason to drain out at many times the network's capacity,
4851  // especially since we have many peers and some will draw much shorter delays.
4852  unsigned int nRelayedTransactions = 0;
4853  LOCK(pto->m_tx_relay->cs_filter);
4854  while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
4855  // Fetch the top element from the heap
4856  std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
4857  std::set<uint256>::iterator it = vInvTx.back();
4858  vInvTx.pop_back();
4859  uint256 hash = *it;
4860  CInv inv(state.m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
4861  // Remove it from the to-be-sent set
4862  pto->m_tx_relay->setInventoryTxToSend.erase(it);
4863  // Check if not in the filter already
4864  if (pto->m_tx_relay->filterInventoryKnown.contains(hash)) {
4865  continue;
4866  }
4867  // Not in the mempool anymore? don't bother sending it.
4868  auto txinfo = m_mempool.info(ToGenTxid(inv));
4869  if (!txinfo.tx) {
4870  continue;
4871  }
4872  auto txid = txinfo.tx->GetHash();
4873  auto wtxid = txinfo.tx->GetWitnessHash();
4874  // Peer told you to not send transactions at that feerate? Don't bother sending it.
4875  if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
4876  continue;
4877  }
4878  if (pto->m_tx_relay->pfilter && !pto->m_tx_relay->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
4879  // Send
4880  State(pto->GetId())->m_recently_announced_invs.insert(hash);
4881  vInv.push_back(inv);
4882  nRelayedTransactions++;
4883  {
4884  // Expire old relay messages
4885  while (!g_relay_expiration.empty() && g_relay_expiration.front().first < current_time)
4886  {
4887  mapRelay.erase(g_relay_expiration.front().second);
4888  g_relay_expiration.pop_front();
4889  }
4890 
4891  auto ret = mapRelay.emplace(txid, std::move(txinfo.tx));
4892  if (ret.second) {
4893  g_relay_expiration.emplace_back(current_time + RELAY_TX_CACHE_TIME, ret.first);
4894  }
4895  // Add wtxid-based lookup into mapRelay as well, so that peers can request by wtxid
4896  auto ret2 = mapRelay.emplace(wtxid, ret.first->second);
4897  if (ret2.second) {
4898  g_relay_expiration.emplace_back(current_time + RELAY_TX_CACHE_TIME, ret2.first);
4899  }
4900  }
4901  if (vInv.size() == MAX_INV_SZ) {
4902  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4903  vInv.clear();
4904  }
4905  pto->m_tx_relay->filterInventoryKnown.insert(hash);
4906  if (hash != txid) {
4907  // Insert txid into filterInventoryKnown, even for
4908  // wtxidrelay peers. This prevents re-adding of
4909  // unconfirmed parents to the recently_announced
4910  // filter, when a child tx is requested. See
4911  // ProcessGetData().
4912  pto->m_tx_relay->filterInventoryKnown.insert(txid);
4913  }
4914  }
4915  }
4916  }
4917  if (!vInv.empty())
4918  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4919 
4920  // Detect whether we're stalling
4921  if (state.m_stalling_since.count() && state.m_stalling_since < current_time - BLOCK_STALLING_TIMEOUT) {
4922  // Stalling only triggers when the block download window cannot move. During normal steady state,
4923  // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
4924  // should only happen during initial block download.
4925  LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
4926  pto->fDisconnect = true;
4927  return true;
4928  }
4929  // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N)
4930  // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
4931  // We compensate for other peers to prevent killing off peers due to our own downstream link
4932  // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
4933  // to unreasonably increase our timeout.
4934  if (state.vBlocksInFlight.size() > 0) {
4935  QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
4936  int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1;
4937  if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
4938  LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->GetId());
4939  pto->fDisconnect = true;
4940  return true;
4941  }
4942  }
4943  // Check for headers sync timeouts
4944  if (state.fSyncStarted && state.m_headers_sync_timeout < std::chrono::microseconds::max()) {
4945  // Detect whether this is a stalling initial-headers-sync peer
4946  if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24 * 60 * 60) {
4947  if (current_time > state.m_headers_sync_timeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
4948  // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
4949  // and we have others we could be using instead.
4950  // Note: If all our peers are inbound, then we won't
4951  // disconnect our sync peer for stalling; we have bigger
4952  // problems if we can't get any outbound peers.
4954  LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
4955  pto->fDisconnect = true;
4956  return true;
4957  } else {
4958  LogPrintf("Timeout downloading headers from noban peer=%d, not disconnecting\n", pto->GetId());
4959  // Reset the headers sync state so that we have a
4960  // chance to try downloading from a different peer.
4961  // Note: this will also result in at least one more
4962  // getheaders message to be sent to
4963  // this peer (eventually).
4964  state.fSyncStarted = false;
4965  nSyncStarted--;
4966  state.m_headers_sync_timeout = 0us;
4967  }
4968  }
4969  } else {
4970  // After we've caught up once, reset the timeout so we can't trigger
4971  // disconnect later.
4972  state.m_headers_sync_timeout = std::chrono::microseconds::max();
4973  }
4974  }
4975 
4976  // Check that outbound peers have reasonable chains
4977  // GetTime() is used by this anti-DoS logic so we can test this using mocktime
4978  ConsiderEviction(*pto, GetTime<std::chrono::seconds>());
4979 
4980  //
4981  // Message: getdata (blocks)
4982  //
4983  std::vector<CInv> vGetData;
4984  if (!pto->fClient && ((fFetch && !pto->m_limited_node) || !m_chainman.ActiveChainstate().IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4985  std::vector<const CBlockIndex*> vToDownload;
4986  NodeId staller = -1;
4987  FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
4988  for (const CBlockIndex *pindex : vToDownload) {
4989  uint32_t nFetchFlags = GetFetchFlags(*pto);
4990  vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
4991  BlockRequested(pto->GetId(), *pindex);
4992  LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
4993  pindex->nHeight, pto->GetId());
4994  }
4995  if (state.nBlocksInFlight == 0 && staller != -1) {
4996  if (State(staller)->m_stalling_since == 0us) {
4997  State(staller)->m_stalling_since = current_time;
4998  LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
4999  }
5000  }
5001  }
5002 
5003  //
5004  // Message: getdata (transactions)
5005  //
5006  std::vector<std::pair<NodeId, GenTxid>> expired;
5007  auto requestable = m_txrequest.GetRequestable(pto->GetId(), current_time, &expired);
5008  for (const auto& entry : expired) {
5009  LogPrint(BCLog::NET, "timeout of inflight %s %s from peer=%d\n", entry.second.IsWtxid() ? "wtx" : "tx",
5010  entry.second.GetHash().ToString(), entry.first);
5011  }
5012  for (const GenTxid& gtxid : requestable) {
5013  if (!AlreadyHaveTx(gtxid)) {
5014  LogPrint(BCLog::NET, "Requesting %s %s peer=%d\n", gtxid.IsWtxid() ? "wtx" : "tx",
5015  gtxid.GetHash().ToString(), pto->GetId());
5016  vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*pto)), gtxid.GetHash());
5017  if (vGetData.size() >= MAX_GETDATA_SZ) {
5018  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
5019  vGetData.clear();
5020  }
5021  m_txrequest.RequestedTx(pto->GetId(), gtxid.GetHash(), current_time + GETDATA_TX_INTERVAL);
5022  } else {
5023  // We have already seen this transaction, no need to download. This is just a belt-and-suspenders, as
5024  // this should already be called whenever a transaction becomes AlreadyHaveTx().
5025  m_txrequest.ForgetTxHash(gtxid.GetHash());
5026  }
5027  }
5028 
5029 
5030  if (!vGetData.empty())
5031  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
5032 
5033  MaybeSendFeefilter(*pto, current_time);
5034  } // release cs_main
5035  return true;
5036 }
CChainState::FindForkInGlobalIndex
CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
Definition: validation.cpp:155
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: chain.h:273
ADDRV2_FORMAT
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
Definition: netaddress.h:34
MAX_UNCONNECTING_HEADERS
static const int MAX_UNCONNECTING_HEADERS
Maximum number of unconnecting headers announcements before DoS score.
Definition: net_processing.cpp:130
CConnman::SetTryNewOutboundPeer
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1813
RELAY_TX_CACHE_TIME
static constexpr auto RELAY_TX_CACHE_TIME
How long to cache transactions in mapRelay for normal relay.
Definition: net_processing.cpp:55
CTxIn
An input of a transaction.
Definition: transaction.h:65
NodeId
int64_t NodeId
Definition: net.h:88
MAX_BLOCKS_IN_TRANSIT_PER_PEER
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
Definition: net_processing.cpp:107
node::fPruneMode
bool fPruneMode
True if we're running in -prune mode.
Definition: blockstorage.cpp:28
BlockValidationResult::BLOCK_CACHED_INVALID
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
block.h
GETDATA_TX_INTERVAL
static constexpr auto GETDATA_TX_INTERVAL
How long to wait before downloading a transaction from an additional peer.
Definition: net_processing.cpp:103
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:227
PeerManager::GetNodeStateStats
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
CConnman::DisconnectNode
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2829
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:528
policy.h
MSG_BLOCK
@ MSG_BLOCK
Definition: protocol.h:463
MAX_BLOCKTXN_DEPTH
static const int MAX_BLOCKTXN_DEPTH
Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for.
Definition: net_processing.cpp:117
PeerManager::SendPings
virtual void SendPings()=0
Send ping message to all peers.
MempoolAcceptResult::m_replaced_transactions
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx per BIP 125 rules.
Definition: validation.h:172
CNode::IsOutboundOrBlockRelayConn
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:461
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:270
CNodeStateStats::vHeightInFlight
std::vector< int > vHeightInFlight
Definition: net_processing.h:31
merkleblock.h
CTxMemPool::GetMinFee
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1096
BlockFilterTypeName
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
Definition: blockfilter.cpp:147
CScheduler
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:33
FEEFILTER_VERSION
static const int FEEFILTER_VERSION
"feefilter" tells peers to filter invs to you by fee starts with this version
Definition: version.h:30
CDataStream::in_avail
int in_avail() const
Definition: streams.h:338
CInv::IsMsgWitnessBlk
bool IsMsgWitnessBlk() const
Definition: protocol.h:495
SetServiceFlagsIBDCache
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:134
fLogIPs
bool fLogIPs
Definition: logging.cpp:38
BlockValidationResult::BLOCK_CONSENSUS
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:602
CNodeStateStats::nCommonHeight
int nCommonHeight
Definition: net_processing.h:28
BanMan::IsBanned
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
Definition: banman.cpp:75
MakeUCharSpan
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span
Like the Span constructor, but for (const) unsigned char member types only.
Definition: span.h:280
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: strencodings.cpp:84
CTxMemPool::info
TxMempoolInfo info(const GenTxid &gtxid) const
Definition: txmempool.cpp:907
ToString
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
CValidationInterface::NewPoWValidBlock
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
Notifies listeners that a block which builds directly on our current tip has been received and connec...
Definition: validationinterface.h:175
BlockValidationResult::BLOCK_MUTATED
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
PeerManager::IgnoresIncomingTxs
virtual bool IgnoresIncomingTxs()=0
Whether this node ignores txs received over p2p.
CBlockIndex::GetAncestor
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:114
count
static int count
Definition: tests.c:31
CNode::IsFeelerConn
bool IsFeelerConn() const
Definition: net.h:488
CTxMemPool::GetUnbroadcastTxs
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:771
assert
assert(!tx.IsCoinBase())
ChainstateManager::ProcessNewBlockHeaders
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
Definition: validation.cpp:3525
node::BlockManager::LookupBlockIndex
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: blockstorage.cpp:35
BanMan::IsDiscouraged
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
Definition: banman.cpp:69
check.h
if
if(na.IsAddrV1Compatible())
Definition: deserialize.cpp:227
CNode::m_last_tx_time
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:572
PoissonNextSend
std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3072
TIMEOUT_INTERVAL
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:52
PartiallyDownloadedBlock::FillBlock
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
Definition: blockencodings.cpp:176
CNode::GetId
NodeId GetId() const
Definition: net.h:586
GenTxid
A generic txid reference (txid or wtxid).
Definition: transaction.h:390
TxValidationResult::TX_WITNESS_STRIPPED
@ TX_WITNESS_STRIPPED
Transaction is missing a witness.
MempoolAcceptResult::m_state
const TxValidationState m_state
Definition: validation.h:168
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
BlockValidationState
Definition: validation.h:141
CNode::PongReceived
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:665
ChainstateManager::ProcessTransaction
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
Definition: validation.cpp:3677
streams.h
CBloomFilter
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:44
UpdateLastBlockAnnounceTime
void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
Definition: net_processing.cpp:1158
CSerializedNetMsg::data
std::vector< unsigned char > data
Definition: net.h:110
MAX_ADDR_PROCESSING_TOKEN_BUCKET
static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET
The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND based inc...
Definition: net_processing.cpp:174
CConnman::StartExtraBlockRelayPeers
void StartExtraBlockRelayPeers()
Definition: net.h:865
CBlockIndex::nTx
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:180
PeerManager::Misbehaving
virtual void Misbehaving(const NodeId pnode, const int howmuch, const std::string &message)=0
Increment peer's misbehavior score.
BLOCK_VALID_TREE
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:104
CConnman::WakeMessageHandler
void WakeMessageHandler()
Definition: net.cpp:1661
CNode::m_bip152_highbandwidth_from
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:530
CNode::nProcessQueueSize
size_t nProcessQueueSize
Definition: net.h:418
sync.h
node::ReadRawBlockFromDisk
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
Definition: blockstorage.cpp:786
blockfilterindex.h
transaction.h
CValidationInterface::BlockDisconnected
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
Definition: validationinterface.h:147
MempoolAcceptResult::m_result_type
const ResultType m_result_type
Definition: validation.h:167
COutPoint::hash
uint256 hash
Definition: transaction.h:29
MINIMUM_CONNECT_TIME
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict.
Definition: net_processing.cpp:73
BlockTransactions
Definition: blockencodings.h:51
CNode::m_limited_node
bool m_limited_node
Definition: net.h:448
CNodeStateStats::m_addr_rate_limited
uint64_t m_addr_rate_limited
Definition: net_processing.h:33
MSG_CMPCT_BLOCK
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:467
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:429
CMerkleBlock
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:124
GetFetchFlags
static uint32_t GetFetchFlags(const CNode &pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: net_processing.cpp:2057
CConnman::OutboundTargetReached
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:2918
CBlockIndex::pprev
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:155
NetPermissionFlags::NoBan
@ NoBan
RANDOMIZER_ID_ADDRESS_RELAY
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY
SHA256("main address relay")[0:8].
Definition: net_processing.cpp:75
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:161
CNode
Information about a peer.
Definition: net.h:394
NetMsgType::PING
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:28
SHORT_IDS_BLOCKS_VERSION
static const int SHORT_IDS_BLOCKS_VERSION
short-id-based block download starts with this version
Definition: version.h:33
CBlockLocator::IsNull
bool IsNull() const
Definition: block.h:135
NetMsgType::FILTERLOAD
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:31
validation.h
BlockFilterIndex
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
Definition: blockfilterindex.h:24
GetDesirableServiceFlags
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:127
AddrMan
Stochastic address manager.
Definition: addrman.h:79
GenTxid::Wtxid
static GenTxid Wtxid(const uint256 &hash)
Definition: transaction.h:398
CNode::m_last_block_time
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:566
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:69
txrequest.h
NetMsgType::SENDADDRV2
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:17
SeenLocal
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:311
MAX_CMPCTBLOCK_DEPTH
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested.
Definition: net_processing.cpp:115
MAX_ADDR_RATE_PER_SECOND
static constexpr double MAX_ADDR_RATE_PER_SECOND
The maximum rate of address records we're willing to process on average.
Definition: net_processing.cpp:170
minRelayTxFee
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:153
MAX_BLOCKS_TO_ANNOUNCE
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
Definition: net_processing.cpp:128
GetTime
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
CBlockIndex::nChainWork
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:173
trace.h
MoneyRange
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
LastCommonAncestor
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:159
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
CNodeStateStats::nSyncHeight
int nSyncHeight
Definition: net_processing.h:27
CChainParams::GetConsensus
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
AnnotatedMixin< std::mutex >
CountSecondsDouble
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
Definition: time.h:38
PeerManager::make
static std::unique_ptr< PeerManager > make(const CChainParams &chainparams, CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
Definition: net_processing.cpp:1475
MIN_PEER_PROTO_VERSION
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
Definition: version.h:18
node::fImporting
std::atomic_bool fImporting
CNode::PushTxInventory
void PushTxInventory(const uint256 &hash)
Definition: net.h:644
MAX_LOCATOR_SZ
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
Definition: net_processing.cpp:85
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:271
CAddress::nServices
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:442
CNode::ExpectServicesFromConn
bool ExpectServicesFromConn() const
Definition: net.h:500
NODE_NETWORK_LIMITED
@ NODE_NETWORK_LIMITED
Definition: protocol.h:291
CTxMemPoolEntry::Parents
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Parents
Definition: txmempool.h:90
CNode::nTimeOffset
std::atomic< int64_t > nTimeOffset
Definition: net.h:428
NODE_NETWORK
@ NODE_NETWORK
Definition: protocol.h:277
BlockValidationResult::BLOCK_RECENT_CONSENSUS_CHANGE
@ BLOCK_RECENT_CONSENSUS_CHANGE
Invalid by a change to consensus rules more recent than SegWit.
MIN_BLOCKS_TO_KEEP
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:91
NetMsgType::CFHEADERS
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:43
ReadCompactSize
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:282
CNode::nServices
std::atomic< ServiceFlags > nServices
Definition: net.h:404
CNode::m_connected
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:427
CInv
inv message data
Definition: protocol.h:476
chainparams.h
GenTxid::Txid
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:397
CConnman::PoissonNextSendInbound
std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3061
ChainstateManager::ActiveChainstate
CChainState & ActiveChainstate() const
The most-work chain.
Definition: validation.cpp:4960
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
NetMsgType::PONG
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition: protocol.cpp:29
CChainState::ActivateBestChain
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(cs_main)
Find the best known block, and make it the tip of the block chain.
Definition: validation.cpp:2827
MAX_GETCFHEADERS_SIZE
static constexpr uint32_t MAX_GETCFHEADERS_SIZE
Maximum number of cf hashes that may be requested with one getcfheaders.
Definition: net_processing.cpp:163
CNetAddr::IsRelayable
bool IsRelayable() const
Whether this address should be relayed to other peers even if we can't reach it ourselves.
Definition: netaddress.h:225
AddrMan::Connected
void Connected(const CService &addr, int64_t nTime=GetAdjustedTime())
We have successfully connected to this peer.
Definition: addrman.cpp:1222
BlockValidationResult::BLOCK_TIME_FUTURE
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
node::ReadBlockFromDisk
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
Definition: blockstorage.cpp:742
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:434
NODE_COMPACT_FILTERS
@ NODE_COMPACT_FILTERS
Definition: protocol.h:287
CNodeStateStats::m_addr_relay_enabled
bool m_addr_relay_enabled
Definition: net_processing.h:34
CAddress::nTime
uint32_t nTime
Always included in serialization.
Definition: protocol.h:440
TxValidationResult::TX_CONFLICT
@ TX_CONFLICT
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
CConnman::GetTryNewOutboundPeer
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1808
TxValidationResult::TX_NOT_STANDARD
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
MayHaveUsefulAddressDB
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
Definition: protocol.h:352
PeerManager::SetBestHeight
virtual void SetBestHeight(int height)=0
Set the best height.
HasAllDesirableServiceFlags
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition: protocol.h:343
CNode::fDisconnect
std::atomic_bool fDisconnect
Definition: net.h:453
PartiallyDownloadedBlock::IsTxAvailable
bool IsTxAvailable(size_t index) const
Definition: blockencodings.cpp:170
CSipHasher
SipHash-2-4.
Definition: siphash.h:13
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:11
BLOCK_DOWNLOAD_TIMEOUT_BASE
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in multiples of the block interval (i.e.
Definition: net_processing.cpp:124
scheduler.h
NetMsgType::SENDCMPCT
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:36
CInv::IsGenTxMsg
bool IsGenTxMsg() const
Definition: protocol.h:498
NetMsgType::ADDRV2
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:16
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
cs_most_recent_block
static RecursiveMutex cs_most_recent_block
Definition: net_processing.cpp:1552
AssertLockHeld
AssertLockHeld(pool.cs)
DEFAULT_MAX_ORPHAN_TRANSACTIONS
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
Definition: net_processing.h:18
MSG_TX
@ MSG_TX
Definition: protocol.h:462
NODE_NETWORK_LIMITED_MIN_BLOCKS
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS
Minimum blocks required to signal NODE_NETWORK_LIMITED.
Definition: net_processing.cpp:132
BCLog::MEMPOOLREJ
@ MEMPOOLREJ
Definition: logging.h:54
tinyformat.h
ValidationState::ToString
std::string ToString() const
Definition: validation.h:126
ChainstateManager::ActiveChain
CChain & ActiveChain() const
Definition: validation.h:895
txmempool.h
CNode::addr
const CAddress addr
Definition: net.h:430
Consensus::Params::nPowTargetSpacing
int64_t nPowTargetSpacing
Definition: params.h:103
HEADERS_DOWNLOAD_TIMEOUT_BASE
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE
Headers download timeout.
Definition: net_processing.cpp:60
CDataStream::GetType
int GetType() const
Definition: streams.h:341
CNode::SetCommonVersion
void SetCommonVersion(int greatest_common_version)
Definition: net.h:611
CNode::GetLocalServices
ServiceFlags GetLocalServices() const
Definition: net.h:657
deploymentstatus.h
ValidationState::IsValid
bool IsValid() const
Definition: validation.h:120
GenTxid::IsWtxid
bool IsWtxid() const
Definition: transaction.h:399
TxValidationState
Definition: validation.h:140
Span
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:96
INVENTORY_MAX_RECENT_RELAY
static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY
The number of most recently announced transactions a peer can request.
Definition: net_processing.cpp:150
Assume
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
NetEventsInterface::InitializeNode
virtual void InitializeNode(CNode *pnode)=0
Initialize a peer (setup state, queue any initial messages)
IsProxy
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:647
CBlockIndex::GetBlockHeader
CBlockHeader GetBlockHeader() const
Definition: chain.h:246
strencodings.h
Consensus::Params
Parameters that influence chain consensus.
Definition: params.h:70
PartiallyDownloadedBlock::InitData
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< std::pair< uint256, CTransactionRef >> &extra_txn)
Definition: blockencodings.cpp:49
TxValidationResult::TX_NO_MEMPOOL
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
nMinimumChainWork
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:151
CValidationInterface::BlockConnected
virtual void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
Definition: validationinterface.h:141
random.h
banman.h
BlockTransactionsRequest
Definition: blockencodings.h:39
AVG_ADDRESS_BROADCAST_INTERVAL
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL
Average delay between peer address broadcasts.
Definition: net_processing.cpp:136
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1048
AddrMan::Good
bool Good(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an address record as accessible and attempt to move it to addrman's tried table.
Definition: addrman.cpp:1192
RecursiveDynamicUsage
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
Consensus::DEPLOYMENT_SEGWIT
@ DEPLOYMENT_SEGWIT
Definition: params.h:24
GUARDED_BY
static std::shared_ptr< const CBlock > most_recent_block GUARDED_BY(cs_most_recent_block)
NetMsgType::INV
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:18
CNode::AddKnownTx
void AddKnownTx(const uint256 &hash)
Definition: net.h:636
CTxMemPool::cs
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:517
node::fReindex
std::atomic_bool fReindex
NetMsgType::GETHEADERS
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:22
BlockValidationResult::BLOCK_INVALID_PREV
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
IsPeerAddrLocalGood
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:202
CTxMemPool::get
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:898
blockfilter.h
AssertLockNotHeld
#define AssertLockNotHeld(cs)
Definition: sync.h:84
PeerManager::StartScheduledTasks
virtual void StartScheduledTasks(CScheduler &scheduler)=0
Begin running background tasks, should only be called once.
INBOUND_INVENTORY_BROADCAST_INTERVAL
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for inbound peers.
Definition: net_processing.cpp:139
CBlockIndex::nStatus
uint32_t nStatus
Verification status of this block.
Definition: chain.h:198
NetPermissionFlags::Download
@ Download
READ_STATUS_OK
@ READ_STATUS_OK
Definition: blockencodings.h:79
AddrMan::Add
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, int64_t nTimePenalty=0)
Attempt to add one or more addresses to addrman's new table.
Definition: addrman.cpp:1187
IsReachable
bool IsReachable(enum Network net)
Definition: net.cpp:299
CNode::GetCommonVersion
int GetCommonVersion() const
Definition: net.h:616
AVG_FEEFILTER_BROADCAST_INTERVAL
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL
Verify that INVENTORY_MAX_RECENT_RELAY is enough to cache everything typically relayed before uncondi...
Definition: net_processing.cpp:157
NetMsgType::CFILTER
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:41
UNCONDITIONAL_RELAY_DELAY
static constexpr auto UNCONDITIONAL_RELAY_DELAY
How long a transaction has to be in the mempool before it can unconditionally be relayed (even when n...
Definition: net_processing.cpp:57
CSipHasher::Finalize
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:76
BLOCK_VALID_SCRIPTS
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:118
reverse_iterator.h
INVALID_CB_NO_BAN_VERSION
static const int INVALID_CB_NO_BAN_VERSION
not banning for invalid compact blocks starts with this version
Definition: version.h:36
STALE_RELAY_AGE_LIMIT
static constexpr int STALE_RELAY_AGE_LIMIT
Age after which a stale block will no longer be served if requested as protection against fingerprint...
Definition: net_processing.cpp:78
NetMsgType::FEEFILTER
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition: protocol.cpp:35
NetEventsInterface::SendMessages
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
CNetAddr::IsRoutable
bool IsRoutable() const
Definition: netaddress.cpp:490
CNetAddr::GetHash
uint64_t GetHash() const
Definition: netaddress.cpp:836
CNode::m_tx_relay
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:559
CConnman::ShouldRunInactivityChecks
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1318
NetMsgType::HEADERS
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:24
CBlockIndex::IsValid
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:308
BLOCK_VALID_TRANSACTIONS
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:111
CConnman::ForNode
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3048
NetMsgType::GETCFCHECKPT
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:44
blockencodings.h
CSerializedNetMsg
Definition: net.h:101
CChain::GetLocator
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:26
CNode::fSuccessfullyConnected
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:450
GetRandBytes
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:584
pindexBestHeader
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:140
NetMsgType::WTXIDRELAY
const char * WTXIDRELAY
Indicates that a node prefers to relay transactions via wtxid, rather than txid.
Definition: protocol.cpp:46
DeploymentActiveAt
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for this block.
Definition: deploymentstatus.h:30
MAX_SCRIPT_ELEMENT_SIZE
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
MAX_PEER_TX_ANNOUNCEMENTS
static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS
Maximum number of transactions to consider for requesting, per peer.
Definition: net_processing.cpp:95
BlockFilterIndex::LookupFilterRange
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.
Definition: blockfilterindex.cpp:417
PeerManager::ProcessMessage
virtual void ProcessMessage(CNode &pfrom, const std::string &msg_type, CDataStream &vRecv, const std::chrono::microseconds time_received, const std::atomic< bool > &interruptMsgProc)=0
Process a single message from a peer.
NODE_BLOOM
@ NODE_BLOOM
Definition: protocol.h:281
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
LogPrintf
#define LogPrintf(...)
Definition: logging.h:187
CNode::m_bip152_highbandwidth_to
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:528
SERIALIZE_TRANSACTION_NO_WITNESS
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
Definition: transaction.h:23
FeeFilterRounder
Definition: fees.h:288
DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
Definition: net_processing.h:20
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:451
Shuffle
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:231
CScheduler::scheduleEvery
void scheduleEvery(Function f, std::chrono::milliseconds delta)
Repeat f until the scheduler is stopped.
Definition: scheduler.cpp:112
NetPermissionFlags::ForceRelay
@ ForceRelay
id
static NodeId id
Definition: denialofservice_tests.cpp:37
CNode::IsAddrFetchConn
bool IsAddrFetchConn() const
Definition: net.h:492
NetMsgType::GETCFHEADERS
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.cpp:42
MAX_PCT_ADDR_TO_SEND
static constexpr size_t MAX_PCT_ADDR_TO_SEND
the maximum percentage of addresses from our addrman to return in response to a getaddr message.
Definition: net_processing.cpp:165
CNode::cs_vProcessMsg
RecursiveMutex cs_vProcessMsg
Definition: net.h:416
ChainstateManager::ProcessNewBlock
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > &block, bool force_processing, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
Definition: validation.cpp:3638
CInv::IsMsgTx
bool IsMsgTx() const
Definition: protocol.h:490
HISTORICAL_BLOCK_AGE
static constexpr int HISTORICAL_BLOCK_AGE
Age after which a block is considered historical for purposes of rate limiting block relay.
Definition: net_processing.cpp:81
CNetMsgMaker
Definition: netmessagemaker.h:12
PING_INTERVAL
static constexpr auto PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive.
Definition: net_processing.cpp:83
NetMsgType::FILTERCLEAR
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:33
CTxMemPool::RemoveUnbroadcastTx
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1031
PeerManager
Definition: net_processing.h:37
base_blob::ToString
std::string ToString() const
Definition: uint256.cpp:64
uint256
256-bit opaque blob.
Definition: uint256.h:124
PeerManager::CheckForStaleTipAndEvictPeers
virtual void CheckForStaleTipAndEvictPeers()=0
Evict extra outbound peers.
NetMsgType::SENDHEADERS
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:34
LogPrint
#define LogPrint(category,...)
Definition: logging.h:191
CNode::IsBlockOnlyConn
bool IsBlockOnlyConn() const
Definition: net.h:484
STALE_CHECK_INTERVAL
static constexpr auto STALE_CHECK_INTERVAL
How frequently to check for stale tips.
Definition: net_processing.cpp:69
NetPermissionFlags::Relay
@ Relay
CNodeStateStats::m_addr_processed
uint64_t m_addr_processed
Definition: net_processing.h:32
AddTimeData
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
Definition: timedata.cpp:42
BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
Additional block download timeout per parallel downloading peer (i.e.
Definition: net_processing.cpp:126
net_processing.h
NetMsgType::GETBLOCKS
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:21
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:259
CConnman::GetReceiveFloodSize
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2963
MAX_GETCFILTERS_SIZE
static constexpr uint32_t MAX_GETCFILTERS_SIZE
Maximum number of compact filters that may be requested with one getcfilters.
Definition: net_processing.cpp:161
CNodeStateStats::m_starting_height
int m_starting_height
Definition: net_processing.h:29
gArgs
ArgsManager gArgs
Definition: system.cpp:85
ValidationState::GetResult
Result GetResult() const
Definition: validation.h:123
CTxMemPool::GetIter
std::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:968
DEFAULT_MIN_RELAY_TX_FEE
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
NetMsgType::GETDATA
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:19
TxValidationResult::TX_MEMPOOL_POLICY
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
CDataStream::size
size_type size() const
Definition: streams.h:235
BlockFilterType::BASIC
@ BASIC
CInv::IsMsgFilteredBlk
bool IsMsgFilteredBlk() const
Definition: protocol.h:493
NetEventsInterface::ProcessMessages
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.