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