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