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