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