Bitcoin ABC  0.26.3
P2P Digital Currency
net_processing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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>
10 #include <avalanche/peermanager.h>
11 #include <avalanche/processor.h>
12 #include <avalanche/proof.h>
13 #include <avalanche/statistics.h>
14 #include <avalanche/validation.h>
15 #include <banman.h>
16 #include <blockencodings.h>
17 #include <blockfilter.h>
18 #include <blockvalidity.h>
19 #include <chain.h>
20 #include <chainparams.h>
21 #include <config.h>
22 #include <consensus/amount.h>
23 #include <consensus/validation.h>
24 #include <hash.h>
25 #include <headerssync.h>
26 #include <index/blockfilterindex.h>
27 #include <invrequest.h>
28 #include <kernel/mempool_entry.h>
29 #include <merkleblock.h>
30 #include <netbase.h>
31 #include <netmessagemaker.h>
32 #include <node/blockstorage.h>
33 #include <policy/fees.h>
34 #include <policy/policy.h>
35 #include <policy/settings.h>
36 #include <primitives/block.h>
37 #include <primitives/transaction.h>
38 #include <random.h>
39 #include <reverse_iterator.h>
40 #include <scheduler.h>
41 #include <streams.h>
42 #include <tinyformat.h>
43 #include <txmempool.h>
44 #include <txorphanage.h>
45 #include <util/check.h> // For NDEBUG compile time check
46 #include <util/strencodings.h>
47 #include <util/trace.h>
48 #include <validation.h>
49 
50 #include <algorithm>
51 #include <atomic>
52 #include <chrono>
53 #include <functional>
54 #include <future>
55 #include <memory>
56 #include <numeric>
57 #include <typeinfo>
58 
60 static constexpr auto RELAY_TX_CACHE_TIME = 15min;
65 static constexpr auto UNCONDITIONAL_RELAY_DELAY = 2min;
70 static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min;
71 static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;
73 static constexpr auto HEADERS_RESPONSE_TIME{2min};
78 static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
80 static constexpr auto CHAIN_SYNC_TIMEOUT{20min};
82 static constexpr auto STALE_CHECK_INTERVAL{10min};
84 static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};
89 static constexpr auto MINIMUM_CONNECT_TIME{30s};
91 static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
94 static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
97 static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
101 static constexpr auto PING_INTERVAL{2min};
103 static const unsigned int MAX_LOCATOR_SZ = 101;
105 static const unsigned int MAX_INV_SZ = 50000;
106 static_assert(MAX_PROTOCOL_MESSAGE_LENGTH > MAX_INV_SZ * sizeof(CInv),
107  "Max protocol message length must be greater than largest "
108  "possible INV message");
109 
111 static constexpr auto GETAVAADDR_INTERVAL{2min};
112 
117 static constexpr auto AVALANCHE_AVAPROOFS_TIMEOUT{2min};
118 
126 
136 
138  const std::chrono::seconds nonpref_peer_delay;
139 
144  const std::chrono::seconds overloaded_peer_delay;
145 
150  const std::chrono::microseconds getdata_interval;
151 
157 };
158 
160  100, // max_peer_request_in_flight
161  5000, // max_peer_announcements
162  std::chrono::seconds(2), // nonpref_peer_delay
163  std::chrono::seconds(2), // overloaded_peer_delay
164  std::chrono::seconds(60), // getdata_interval
165  NetPermissionFlags::Relay, // bypass_request_limits_permissions
166 };
167 
169  100, // max_peer_request_in_flight
170  5000, // max_peer_announcements
171  std::chrono::seconds(2), // nonpref_peer_delay
172  std::chrono::seconds(2), // overloaded_peer_delay
173  std::chrono::seconds(60), // getdata_interval
175  BypassProofRequestLimits, // bypass_request_limits_permissions
176 };
177 
182 static const unsigned int MAX_GETDATA_SZ = 1000;
186 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
192 static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT{2s};
194 static constexpr auto BLOCK_STALLING_TIMEOUT_MAX{64s};
199 static const int MAX_CMPCTBLOCK_DEPTH = 5;
204 static const int MAX_BLOCKTXN_DEPTH = 10;
212 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
217 static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1;
221 static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5;
226 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
228 static const int MAX_NUM_UNCONNECTING_HEADERS_MSGS = 10;
230 static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
234 static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h};
238 static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s};
240 static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h};
245 static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s};
250 static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7;
252 static constexpr unsigned int INVENTORY_BROADCAST_MAX_PER_MB =
256 static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY = 3500;
265  std::chrono::seconds{1},
266  "INVENTORY_RELAY_MAX too low");
267 
271 static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min};
275 static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min};
280 static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
285 static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;
290 static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
295 static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
303 static constexpr uint64_t CMPCTBLOCKS_VERSION{1};
304 
305 // Internal stuff
306 namespace {
310 struct QueuedBlock {
315  const CBlockIndex *pindex;
317  std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
318 };
319 
333 struct Peer {
335  const NodeId m_id{0};
336 
352  const ServiceFlags m_our_services;
353 
355  std::atomic<ServiceFlags> m_their_services{NODE_NONE};
356 
358  Mutex m_misbehavior_mutex;
360  int m_misbehavior_score GUARDED_BY(m_misbehavior_mutex){0};
363  bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false};
364 
366  Mutex m_block_inv_mutex;
372  std::vector<BlockHash> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex);
378  std::vector<BlockHash>
379  m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex);
380 
387  BlockHash m_continuation_block GUARDED_BY(m_block_inv_mutex){};
388 
390  std::atomic<int> m_starting_height{-1};
391 
393  std::atomic<uint64_t> m_ping_nonce_sent{0};
395  std::atomic<std::chrono::microseconds> m_ping_start{0us};
397  std::atomic<bool> m_ping_queued{false};
398 
406  Amount::zero()};
407  std::chrono::microseconds m_next_send_feefilter
409 
410  struct TxRelay {
411  mutable RecursiveMutex m_bloom_filter_mutex;
420  bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false};
425  std::unique_ptr<CBloomFilter>
426  m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex)
427  GUARDED_BY(m_bloom_filter_mutex){nullptr};
428 
430  CRollingBloomFilter m_recently_announced_invs GUARDED_BY(
432  0.000001};
433 
434  mutable RecursiveMutex m_tx_inventory_mutex;
440  CRollingBloomFilter m_tx_inventory_known_filter
441  GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
447  std::set<TxId> m_tx_inventory_to_send GUARDED_BY(m_tx_inventory_mutex);
453  bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};
455  std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
460  std::chrono::microseconds m_next_inv_send_time
462 
467  std::atomic<Amount> m_fee_filter_received{Amount::zero()};
468  };
469 
470  /*
471  * Initializes a TxRelay struct for this peer. Can be called at most once
472  * for a peer.
473  */
474  TxRelay *SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) {
475  LOCK(m_tx_relay_mutex);
476  Assume(!m_tx_relay);
477  m_tx_relay = std::make_unique<Peer::TxRelay>();
478  return m_tx_relay.get();
479  };
480 
481  TxRelay *GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) {
482  return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get());
483  };
484  const TxRelay *GetTxRelay() const
485  EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) {
486  return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get());
487  };
488 
489  struct ProofRelay {
490  mutable RecursiveMutex m_proof_inventory_mutex;
491  std::set<avalanche::ProofId>
492  m_proof_inventory_to_send GUARDED_BY(m_proof_inventory_mutex);
493  // Prevent sending proof invs if the peer already knows about them
494  CRollingBloomFilter m_proof_inventory_known_filter
495  GUARDED_BY(m_proof_inventory_mutex){10000, 0.000001};
499  CRollingBloomFilter m_recently_announced_proofs GUARDED_BY(
501  0.000001};
502  std::chrono::microseconds m_next_inv_send_time{0};
503 
505  sharedProofs;
506  std::atomic<std::chrono::seconds> lastSharedProofsUpdate{0s};
507  std::atomic<bool> compactproofs_requested{false};
508  };
509 
514  const std::unique_ptr<ProofRelay> m_proof_relay;
515 
519  std::vector<CAddress>
531  std::unique_ptr<CRollingBloomFilter>
549  std::atomic_bool m_addr_relay_enabled{false};
551  bool m_getaddr_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
553  mutable Mutex m_addr_send_times_mutex;
555  std::chrono::microseconds
556  m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
558  std::chrono::microseconds
559  m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
564  std::atomic_bool m_wants_addrv2{false};
566  bool m_getaddr_recvd GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};
568  mutable Mutex m_addr_token_bucket_mutex;
573  double m_addr_token_bucket GUARDED_BY(m_addr_token_bucket_mutex){1.0};
575  std::chrono::microseconds
576  m_addr_token_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){
577  GetTime<std::chrono::microseconds>()};
579  std::atomic<uint64_t> m_addr_rate_limited{0};
584  std::atomic<uint64_t> m_addr_processed{0};
585 
590  bool m_inv_triggered_getheaders_before_sync
592 
594  Mutex m_getdata_requests_mutex;
596  std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);
597 
599  NodeClock::time_point m_last_getheaders_timestamp
601 
603  Mutex m_headers_sync_mutex;
608  std::unique_ptr<HeadersSyncState>
609  m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex)
610  GUARDED_BY(m_headers_sync_mutex){};
611 
613  std::atomic<bool> m_sent_sendheaders{false};
614 
616  int m_num_unconnecting_headers_msgs
618 
620  std::chrono::microseconds m_headers_sync_timeout
622 
627  bool m_prefers_headers GUARDED_BY(NetEventsInterface::g_msgproc_mutex){
628  false};
629 
630  explicit Peer(NodeId id, ServiceFlags our_services, bool fRelayProofs)
631  : m_id(id), m_our_services{our_services},
632  m_proof_relay(fRelayProofs ? std::make_unique<ProofRelay>()
633  : nullptr) {}
634 
635 private:
636  mutable Mutex m_tx_relay_mutex;
637 
643  std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex);
644 };
645 
646 using PeerRef = std::shared_ptr<Peer>;
647 
654 struct CNodeState {
656  const CBlockIndex *pindexBestKnownBlock{nullptr};
658  BlockHash hashLastUnknownBlock{};
660  const CBlockIndex *pindexLastCommonBlock{nullptr};
662  const CBlockIndex *pindexBestHeaderSent{nullptr};
664  bool fSyncStarted{false};
667  std::chrono::microseconds m_stalling_since{0us};
668  std::list<QueuedBlock> vBlocksInFlight;
671  std::chrono::microseconds m_downloading_since{0us};
672  int nBlocksInFlight{0};
674  bool fPreferredDownload{false};
679  bool m_requested_hb_cmpctblocks{false};
681  bool m_provides_cmpctblocks{false};
682 
709  struct ChainSyncTimeoutState {
712  std::chrono::seconds m_timeout{0s};
714  const CBlockIndex *m_work_header{nullptr};
716  bool m_sent_getheaders{false};
719  bool m_protect{false};
720  };
721 
722  ChainSyncTimeoutState m_chain_sync;
723 
725  int64_t m_last_block_announcement{0};
726 
728  const bool m_is_inbound;
729 
730  CNodeState(bool is_inbound) : m_is_inbound(is_inbound) {}
731 };
732 
733 class PeerManagerImpl final : public PeerManager {
734 public:
735  PeerManagerImpl(CConnman &connman, AddrMan &addrman, BanMan *banman,
736  ChainstateManager &chainman, CTxMemPool &pool,
737  avalanche::Processor *const avalanche, Options opts);
738 
740  void BlockConnected(const std::shared_ptr<const CBlock> &pblock,
741  const CBlockIndex *pindexConnected) override
742  EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex);
743  void BlockDisconnected(const std::shared_ptr<const CBlock> &block,
744  const CBlockIndex *pindex) override
745  EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex);
746  void UpdatedBlockTip(const CBlockIndex *pindexNew,
747  const CBlockIndex *pindexFork,
748  bool fInitialDownload) override
749  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
750  void BlockChecked(const CBlock &block,
751  const BlockValidationState &state) override
752  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
753  void NewPoWValidBlock(const CBlockIndex *pindex,
754  const std::shared_ptr<const CBlock> &pblock) override
755  EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);
756 
758  void InitializeNode(const Config &config, CNode &node,
759  ServiceFlags our_services) override
760  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
761  void FinalizeNode(const Config &config, const CNode &node) override
762  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !cs_proofrequest,
763  !m_headers_presync_mutex);
764  bool ProcessMessages(const Config &config, CNode *pfrom,
765  std::atomic<bool> &interrupt) override
766  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex,
767  !m_recent_confirmed_transactions_mutex,
768  !m_most_recent_block_mutex, !cs_proofrequest,
769  !m_headers_presync_mutex, g_msgproc_mutex);
770  bool SendMessages(const Config &config, CNode *pto) override
771  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex,
772  !m_recent_confirmed_transactions_mutex,
773  !m_most_recent_block_mutex, !cs_proofrequest,
774  g_msgproc_mutex);
775 
777  void StartScheduledTasks(CScheduler &scheduler) override;
778  void CheckForStaleTipAndEvictPeers() override;
779  std::optional<std::string>
780  FetchBlock(const Config &config, NodeId peer_id,
781  const CBlockIndex &block_index) override;
782  bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const override
783  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
784  bool IgnoresIncomingTxs() override { return m_opts.ignore_incoming_txs; }
785  void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
786  void RelayTransaction(const TxId &txid) override
787  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
788  void RelayProof(const avalanche::ProofId &proofid) override
789  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
790  void SetBestHeight(int height) override { m_best_height = height; };
791  void UnitTestMisbehaving(NodeId peer_id, const int howmuch) override
792  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) {
793  Misbehaving(*Assert(GetPeerRef(peer_id)), howmuch, "");
794  }
795  void ProcessMessage(const Config &config, CNode &pfrom,
796  const std::string &msg_type, CDataStream &vRecv,
797  const std::chrono::microseconds time_received,
798  const std::atomic<bool> &interruptMsgProc) override
799  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex,
800  !m_recent_confirmed_transactions_mutex,
801  !m_most_recent_block_mutex, !cs_proofrequest,
802  !m_headers_presync_mutex, g_msgproc_mutex);
804  int64_t time_in_seconds) override;
805 
806 private:
811  void ConsiderEviction(CNode &pto, Peer &peer,
812  std::chrono::seconds time_in_seconds)
813  EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_msgproc_mutex);
814 
819  void EvictExtraOutboundPeers(std::chrono::seconds now)
821 
826  void ReattemptInitialBroadcast(CScheduler &scheduler)
827  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
828 
832  void UpdateAvalancheStatistics() const;
833 
837  void AvalanchePeriodicNetworking(CScheduler &scheduler) const;
838 
843  PeerRef GetPeerRef(NodeId id) const EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
844 
849  PeerRef RemovePeer(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
850 
856  void Misbehaving(Peer &peer, int howmuch, const std::string &message);
857 
870  bool MaybePunishNodeForBlock(NodeId nodeid,
871  const BlockValidationState &state,
872  bool via_compact_block,
873  const std::string &message = "")
874  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
875 
882  bool MaybePunishNodeForTx(NodeId nodeid, const TxValidationState &state,
883  const std::string &message = "")
884  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
885 
895  bool MaybeDiscourageAndDisconnect(CNode &pnode, Peer &peer);
896 
910  void ProcessInvalidTx(NodeId nodeid, const CTransactionRef &tx,
911  const TxValidationState &result,
912  bool maybe_add_extra_compact_tx)
913  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main);
914 
915  struct PackageToValidate {
916  const Package m_txns;
917  const std::vector<NodeId> m_senders;
919  explicit PackageToValidate(const CTransactionRef &parent,
920  const CTransactionRef &child,
921  NodeId parent_sender, NodeId child_sender)
922  : m_txns{parent, child}, m_senders{parent_sender, child_sender} {}
923 
924  std::string ToString() const {
925  Assume(m_txns.size() == 2);
926  return strprintf(
927  "parent %s (sender=%d) + child %s (sender=%d)",
928  m_txns.front()->GetId().ToString(), m_senders.front(),
929  m_txns.back()->GetId().ToString(), m_senders.back());
930  }
931  };
932 
938  void ProcessPackageResult(const PackageToValidate &package_to_validate,
939  const PackageMempoolAcceptResult &package_result)
940  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main);
941 
948  std::optional<PackageToValidate> Find1P1CPackage(const CTransactionRef &ptx,
949  NodeId nodeid)
950  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main);
951 
957  void ProcessValidTx(NodeId nodeid, const CTransactionRef &tx)
958  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex, cs_main);
959 
975  bool ProcessOrphanTx(const Config &config, Peer &peer)
976  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex);
977 
988  void ProcessHeadersMessage(const Config &config, CNode &pfrom, Peer &peer,
989  std::vector<CBlockHeader> &&headers,
990  bool via_compact_block)
991  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex,
992  g_msgproc_mutex);
993 
994  // Various helpers for headers processing, invoked by
995  // ProcessHeadersMessage()
1000  bool CheckHeadersPoW(const std::vector<CBlockHeader> &headers,
1001  const Consensus::Params &consensusParams, Peer &peer);
1003  arith_uint256 GetAntiDoSWorkThreshold();
1010  void HandleFewUnconnectingHeaders(CNode &pfrom, Peer &peer,
1011  const std::vector<CBlockHeader> &headers)
1012  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1014  bool
1015  CheckHeadersAreContinuous(const std::vector<CBlockHeader> &headers) const;
1035  bool IsContinuationOfLowWorkHeadersSync(Peer &peer, CNode &pfrom,
1036  std::vector<CBlockHeader> &headers)
1037  EXCLUSIVE_LOCKS_REQUIRED(peer.m_headers_sync_mutex,
1038  !m_headers_presync_mutex, g_msgproc_mutex);
1053  bool TryLowWorkHeadersSync(Peer &peer, CNode &pfrom,
1054  const CBlockIndex *chain_start_header,
1055  std::vector<CBlockHeader> &headers)
1056  EXCLUSIVE_LOCKS_REQUIRED(!peer.m_headers_sync_mutex, !m_peer_mutex,
1057  !m_headers_presync_mutex, g_msgproc_mutex);
1058 
1063  bool IsAncestorOfBestHeaderOrTip(const CBlockIndex *header)
1065 
1071  bool MaybeSendGetHeaders(CNode &pfrom, const CBlockLocator &locator,
1072  Peer &peer)
1073  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1077  void HeadersDirectFetchBlocks(const Config &config, CNode &pfrom,
1078  const CBlockIndex *pindexLast);
1080  void UpdatePeerStateForReceivedHeaders(CNode &pfrom, Peer &peer,
1081  const CBlockIndex *pindexLast,
1082  bool received_new_header,
1083  bool may_have_more_headers)
1084  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1085 
1086  void SendBlockTransactions(CNode &pfrom, Peer &peer, const CBlock &block,
1087  const BlockTransactionsRequest &req);
1088 
1094  void AddTxAnnouncement(const CNode &node, const TxId &txid,
1095  std::chrono::microseconds current_time)
1097 
1103  void
1104  AddProofAnnouncement(const CNode &node, const avalanche::ProofId &proofid,
1105  std::chrono::microseconds current_time, bool preferred)
1106  EXCLUSIVE_LOCKS_REQUIRED(cs_proofrequest);
1107 
1109  void PushNodeVersion(const Config &config, CNode &pnode, const Peer &peer);
1110 
1117  void MaybeSendPing(CNode &node_to, Peer &peer,
1118  std::chrono::microseconds now);
1119 
1121  void MaybeSendAddr(CNode &node, Peer &peer,
1122  std::chrono::microseconds current_time)
1123  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1124 
1129  void MaybeSendSendHeaders(CNode &node, Peer &peer)
1130  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1131 
1133  void MaybeSendFeefilter(CNode &node, Peer &peer,
1134  std::chrono::microseconds current_time)
1135  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1136 
1146  void RelayAddress(NodeId originator, const CAddress &addr, bool fReachable)
1147  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex);
1148 
1150 
1152  m_fee_filter_rounder GUARDED_BY(NetEventsInterface::g_msgproc_mutex);
1153 
1154  const CChainParams &m_chainparams;
1155  CConnman &m_connman;
1156  AddrMan &m_addrman;
1161  BanMan *const m_banman;
1162  ChainstateManager &m_chainman;
1163  CTxMemPool &m_mempool;
1164  avalanche::Processor *const m_avalanche;
1166 
1167  Mutex cs_proofrequest;
1169  m_proofrequest GUARDED_BY(cs_proofrequest);
1170 
1172  std::atomic<int> m_best_height{-1};
1173 
1175  std::chrono::seconds m_stale_tip_check_time{0s};
1176 
1177  const Options m_opts;
1178 
1183  bool m_initial_sync_finished{false};
1184 
1189  mutable Mutex m_peer_mutex;
1196  std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex);
1197 
1199  std::map<NodeId, CNodeState> m_node_states GUARDED_BY(cs_main);
1200 
1205  const CNodeState *State(NodeId pnode) const
1208  CNodeState *State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1209 
1210  std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us};
1211 
1213  int nSyncStarted GUARDED_BY(cs_main) = 0;
1214 
1216  BlockHash
1217  m_last_block_inv_triggering_headers_sync GUARDED_BY(g_msgproc_mutex){};
1218 
1225  std::map<BlockHash, std::pair<NodeId, bool>>
1226  mapBlockSource GUARDED_BY(cs_main);
1227 
1229  int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
1230 
1232  int m_num_preferred_download_peers GUARDED_BY(cs_main){0};
1233 
1235  std::atomic<std::chrono::seconds> m_block_stalling_timeout{
1237 
1248  bool AlreadyHaveTx(const TxId &txid, bool include_reconsiderable)
1250  !m_recent_confirmed_transactions_mutex);
1251 
1271  CRollingBloomFilter m_recent_rejects GUARDED_BY(::cs_main){120'000,
1272  0.000'001};
1273 
1279  uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main);
1280 
1305  CRollingBloomFilter m_recent_rejects_reconsiderable GUARDED_BY(::cs_main){
1306  120'000, 0.000'001};
1307 
1313  mutable Mutex m_recent_confirmed_transactions_mutex;
1314  CRollingBloomFilter m_recent_confirmed_transactions
1315  GUARDED_BY(m_recent_confirmed_transactions_mutex){24'000, 0.000'001};
1316 
1324  std::chrono::microseconds
1325  NextInvToInbounds(std::chrono::microseconds now,
1326  std::chrono::seconds average_interval);
1327 
1328  // All of the following cache a recent block, and are protected by
1329  // m_most_recent_block_mutex
1330  mutable Mutex m_most_recent_block_mutex;
1331  std::shared_ptr<const CBlock>
1332  m_most_recent_block GUARDED_BY(m_most_recent_block_mutex);
1333  std::shared_ptr<const CBlockHeaderAndShortTxIDs>
1334  m_most_recent_compact_block GUARDED_BY(m_most_recent_block_mutex);
1335  BlockHash m_most_recent_block_hash GUARDED_BY(m_most_recent_block_mutex);
1336 
1337  // Data about the low-work headers synchronization, aggregated from all
1338  // peers' HeadersSyncStates.
1340  Mutex m_headers_presync_mutex;
1351  using HeadersPresyncStats =
1352  std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>;
1354  std::map<NodeId, HeadersPresyncStats>
1355  m_headers_presync_stats GUARDED_BY(m_headers_presync_mutex){};
1357  NodeId m_headers_presync_bestpeer GUARDED_BY(m_headers_presync_mutex){-1};
1359  std::atomic_bool m_headers_presync_should_signal{false};
1360 
1364  int m_highest_fast_announce GUARDED_BY(::cs_main){0};
1365 
1367  bool IsBlockRequested(const BlockHash &hash)
1369 
1375  void RemoveBlockRequest(const BlockHash &hash)
1377 
1384  bool BlockRequested(const Config &config, NodeId nodeid,
1385  const CBlockIndex &block,
1386  std::list<QueuedBlock>::iterator **pit = nullptr)
1388 
1389  bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1390 
1395  void FindNextBlocksToDownload(NodeId nodeid, unsigned int count,
1396  std::vector<const CBlockIndex *> &vBlocks,
1397  NodeId &nodeStaller)
1399 
1400  std::map<BlockHash, std::pair<NodeId, std::list<QueuedBlock>::iterator>>
1401  mapBlocksInFlight GUARDED_BY(cs_main);
1402 
1404  std::atomic<std::chrono::seconds> m_last_tip_update{0s};
1405 
1410  CTransactionRef FindTxForGetData(const Peer &peer, const TxId &txid,
1411  const std::chrono::seconds mempool_req,
1412  const std::chrono::seconds now)
1415 
1416  void ProcessGetData(const Config &config, CNode &pfrom, Peer &peer,
1417  const std::atomic<bool> &interruptMsgProc)
1418  EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex,
1419  peer.m_getdata_requests_mutex,
1422 
1424  void ProcessBlock(const Config &config, CNode &node,
1425  const std::shared_ptr<const CBlock> &block,
1426  bool force_processing, bool min_pow_checked);
1427 
1429  typedef std::map<TxId, CTransactionRef> MapRelay;
1430  MapRelay mapRelay GUARDED_BY(cs_main);
1431 
1436  std::deque<std::pair<std::chrono::microseconds, MapRelay::iterator>>
1437  g_relay_expiration GUARDED_BY(cs_main);
1438 
1445  void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid)
1447 
1449  std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
1450 
1452  int m_peers_downloading_from GUARDED_BY(cs_main) = 0;
1453 
1455  TxOrphanage m_orphanage;
1456 
1457  void AddToCompactExtraTransactions(const CTransactionRef &tx)
1458  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1459 
1467  std::vector<std::pair<TxHash, CTransactionRef>>
1468  vExtraTxnForCompact GUARDED_BY(g_msgproc_mutex);
1470  size_t vExtraTxnForCompactIt GUARDED_BY(g_msgproc_mutex) = 0;
1471 
1475  void ProcessBlockAvailability(NodeId nodeid)
1480  void UpdateBlockAvailability(NodeId nodeid, const BlockHash &hash)
1482  bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1483 
1490  bool BlockRequestAllowed(const CBlockIndex *pindex)
1492  bool AlreadyHaveBlock(const BlockHash &block_hash)
1494  bool AlreadyHaveProof(const avalanche::ProofId &proofid);
1495  void ProcessGetBlockData(const Config &config, CNode &pfrom, Peer &peer,
1496  const CInv &inv)
1497  EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);
1498 
1518  bool PrepareBlockFilterRequest(CNode &node, Peer &peer,
1519  BlockFilterType filter_type,
1520  uint32_t start_height,
1521  const BlockHash &stop_hash,
1522  uint32_t max_height_diff,
1523  const CBlockIndex *&stop_index,
1524  BlockFilterIndex *&filter_index);
1525 
1535  void ProcessGetCFilters(CNode &node, Peer &peer, CDataStream &vRecv);
1545  void ProcessGetCFHeaders(CNode &node, Peer &peer, CDataStream &vRecv);
1555  void ProcessGetCFCheckPt(CNode &node, Peer &peer, CDataStream &vRecv);
1556 
1563  uint32_t GetAvalancheVoteForBlock(const BlockHash &hash) const
1565 
1572  uint32_t GetAvalancheVoteForTx(const TxId &id) const
1574  !m_recent_confirmed_transactions_mutex);
1575 
1583  bool SetupAddressRelay(const CNode &node, Peer &peer)
1584  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1585 
1586  void AddAddressKnown(Peer &peer, const CAddress &addr)
1587  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1588  void PushAddress(Peer &peer, const CAddress &addr)
1589  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex);
1590 
1596  bool ReceivedAvalancheProof(CNode &node, Peer &peer,
1597  const avalanche::ProofRef &proof)
1598  EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !cs_proofrequest);
1599 
1600  avalanche::ProofRef FindProofForGetData(const Peer &peer,
1601  const avalanche::ProofId &proofid,
1602  const std::chrono::seconds now)
1603  EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex);
1604 
1605  bool isPreferredDownloadPeer(const CNode &pfrom);
1606 };
1607 
1608 const CNodeState *PeerManagerImpl::State(NodeId pnode) const
1610  std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
1611  if (it == m_node_states.end()) {
1612  return nullptr;
1613  }
1614 
1615  return &it->second;
1616 }
1617 
1618 CNodeState *PeerManagerImpl::State(NodeId pnode)
1620  return const_cast<CNodeState *>(std::as_const(*this).State(pnode));
1621 }
1622 
1628 static bool IsAddrCompatible(const Peer &peer, const CAddress &addr) {
1629  return peer.m_wants_addrv2 || addr.IsAddrV1Compatible();
1630 }
1631 
1632 void PeerManagerImpl::AddAddressKnown(Peer &peer, const CAddress &addr) {
1633  assert(peer.m_addr_known);
1634  peer.m_addr_known->insert(addr.GetKey());
1635 }
1636 
1637 void PeerManagerImpl::PushAddress(Peer &peer, const CAddress &addr) {
1638  // Known checking here is only to save space from duplicates.
1639  // Before sending, we'll filter it again for known addresses that were
1640  // added after addresses were pushed.
1641  assert(peer.m_addr_known);
1642  if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) &&
1643  IsAddrCompatible(peer, addr)) {
1644  if (peer.m_addrs_to_send.size() >= m_opts.max_addr_to_send) {
1645  peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] =
1646  addr;
1647  } else {
1648  peer.m_addrs_to_send.push_back(addr);
1649  }
1650  }
1651 }
1652 
1653 static void AddKnownTx(Peer &peer, const TxId &txid) {
1654  auto tx_relay = peer.GetTxRelay();
1655  if (!tx_relay) {
1656  return;
1657  }
1658 
1659  LOCK(tx_relay->m_tx_inventory_mutex);
1660  tx_relay->m_tx_inventory_known_filter.insert(txid);
1661 }
1662 
1663 static void AddKnownProof(Peer &peer, const avalanche::ProofId &proofid) {
1664  if (peer.m_proof_relay != nullptr) {
1665  LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
1666  peer.m_proof_relay->m_proof_inventory_known_filter.insert(proofid);
1667  }
1668 }
1669 
1670 bool PeerManagerImpl::isPreferredDownloadPeer(const CNode &pfrom) {
1671  LOCK(cs_main);
1672  const CNodeState *state = State(pfrom.GetId());
1673  return state && state->fPreferredDownload;
1674 }
1676 static bool CanServeBlocks(const Peer &peer) {
1677  return peer.m_their_services & (NODE_NETWORK | NODE_NETWORK_LIMITED);
1678 }
1679 
1684 static bool IsLimitedPeer(const Peer &peer) {
1685  return (!(peer.m_their_services & NODE_NETWORK) &&
1686  (peer.m_their_services & NODE_NETWORK_LIMITED));
1687 }
1688 
1689 std::chrono::microseconds
1690 PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
1691  std::chrono::seconds average_interval) {
1692  if (m_next_inv_to_inbounds.load() < now) {
1693  // If this function were called from multiple threads simultaneously
1694  // it would possible that both update the next send variable, and return
1695  // a different result to their caller. This is not possible in practice
1696  // as only the net processing thread invokes this function.
1697  m_next_inv_to_inbounds = GetExponentialRand(now, average_interval);
1698  }
1699  return m_next_inv_to_inbounds;
1700 }
1701 
1702 bool PeerManagerImpl::IsBlockRequested(const BlockHash &hash) {
1703  return mapBlocksInFlight.find(hash) != mapBlocksInFlight.end();
1704 }
1705 
1706 void PeerManagerImpl::RemoveBlockRequest(const BlockHash &hash) {
1707  auto it = mapBlocksInFlight.find(hash);
1708 
1709  if (it == mapBlocksInFlight.end()) {
1710  // Block was not requested
1711  return;
1712  }
1713 
1714  auto [node_id, list_it] = it->second;
1715  CNodeState *state = State(node_id);
1716  assert(state != nullptr);
1717 
1718  if (state->vBlocksInFlight.begin() == list_it) {
1719  // First block on the queue was received, update the start download time
1720  // for the next one
1721  state->m_downloading_since = std::max(
1722  state->m_downloading_since, GetTime<std::chrono::microseconds>());
1723  }
1724  state->vBlocksInFlight.erase(list_it);
1725 
1726  state->nBlocksInFlight--;
1727  if (state->nBlocksInFlight == 0) {
1728  // Last validated block on the queue was received.
1729  m_peers_downloading_from--;
1730  }
1731  state->m_stalling_since = 0us;
1732  mapBlocksInFlight.erase(it);
1733 }
1734 
1735 bool PeerManagerImpl::BlockRequested(const Config &config, NodeId nodeid,
1736  const CBlockIndex &block,
1737  std::list<QueuedBlock>::iterator **pit) {
1738  const BlockHash &hash{block.GetBlockHash()};
1739 
1740  CNodeState *state = State(nodeid);
1741  assert(state != nullptr);
1742 
1743  // Short-circuit most stuff in case it is from the same node.
1744  std::map<BlockHash,
1745  std::pair<NodeId, std::list<QueuedBlock>::iterator>>::iterator
1746  itInFlight = mapBlocksInFlight.find(hash);
1747  if (itInFlight != mapBlocksInFlight.end() &&
1748  itInFlight->second.first == nodeid) {
1749  if (pit) {
1750  *pit = &itInFlight->second.second;
1751  }
1752  return false;
1753  }
1754 
1755  // Make sure it's not listed somewhere already.
1756  RemoveBlockRequest(hash);
1757 
1758  std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(
1759  state->vBlocksInFlight.end(),
1760  {&block, std::unique_ptr<PartiallyDownloadedBlock>(
1761  pit ? new PartiallyDownloadedBlock(config, &m_mempool)
1762  : nullptr)});
1763  state->nBlocksInFlight++;
1764  if (state->nBlocksInFlight == 1) {
1765  // We're starting a block download (batch) from this peer.
1766  state->m_downloading_since = GetTime<std::chrono::microseconds>();
1767  m_peers_downloading_from++;
1768  }
1769 
1770  itInFlight = mapBlocksInFlight
1771  .insert(std::make_pair(hash, std::make_pair(nodeid, it)))
1772  .first;
1773 
1774  if (pit) {
1775  *pit = &itInFlight->second.second;
1776  }
1777 
1778  return true;
1779 }
1780 
1781 void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) {
1783 
1784  // Never request high-bandwidth mode from peers if we're blocks-only. Our
1785  // mempool will not contain the transactions necessary to reconstruct the
1786  // compact block.
1787  if (m_opts.ignore_incoming_txs) {
1788  return;
1789  }
1790 
1791  CNodeState *nodestate = State(nodeid);
1792  if (!nodestate) {
1793  LogPrint(BCLog::NET, "node state unavailable: peer=%d\n", nodeid);
1794  return;
1795  }
1796  if (!nodestate->m_provides_cmpctblocks) {
1797  return;
1798  }
1799  int num_outbound_hb_peers = 0;
1800  for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin();
1801  it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
1802  if (*it == nodeid) {
1803  lNodesAnnouncingHeaderAndIDs.erase(it);
1804  lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
1805  return;
1806  }
1807  CNodeState *state = State(*it);
1808  if (state != nullptr && !state->m_is_inbound) {
1809  ++num_outbound_hb_peers;
1810  }
1811  }
1812  if (nodestate->m_is_inbound) {
1813  // If we're adding an inbound HB peer, make sure we're not removing
1814  // our last outbound HB peer in the process.
1815  if (lNodesAnnouncingHeaderAndIDs.size() >= 3 &&
1816  num_outbound_hb_peers == 1) {
1817  CNodeState *remove_node =
1818  State(lNodesAnnouncingHeaderAndIDs.front());
1819  if (remove_node != nullptr && !remove_node->m_is_inbound) {
1820  // Put the HB outbound peer in the second slot, so that it
1821  // doesn't get removed.
1822  std::swap(lNodesAnnouncingHeaderAndIDs.front(),
1823  *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
1824  }
1825  }
1826  }
1827  m_connman.ForNode(nodeid, [this](CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(
1828  ::cs_main) {
1830  if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
1831  // As per BIP152, we only get 3 of our peers to announce
1832  // blocks using compact encodings.
1833  m_connman.ForNode(
1834  lNodesAnnouncingHeaderAndIDs.front(), [this](CNode *pnodeStop) {
1835  m_connman.PushMessage(
1836  pnodeStop, CNetMsgMaker(pnodeStop->GetCommonVersion())
1837  .Make(NetMsgType::SENDCMPCT,
1838  /*high_bandwidth=*/false,
1839  /*version=*/CMPCTBLOCKS_VERSION));
1840  // save BIP152 bandwidth state: we select peer to be
1841  // low-bandwidth
1842  pnodeStop->m_bip152_highbandwidth_to = false;
1843  return true;
1844  });
1845  lNodesAnnouncingHeaderAndIDs.pop_front();
1846  }
1847  m_connman.PushMessage(pfrom,
1848  CNetMsgMaker(pfrom->GetCommonVersion())
1850  /*high_bandwidth=*/true,
1851  /*version=*/CMPCTBLOCKS_VERSION));
1852  // save BIP152 bandwidth state: we select peer to be high-bandwidth
1853  pfrom->m_bip152_highbandwidth_to = true;
1854  lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
1855  return true;
1856  });
1857 }
1858 
1859 bool PeerManagerImpl::TipMayBeStale() {
1861  const Consensus::Params &consensusParams = m_chainparams.GetConsensus();
1862  if (m_last_tip_update.load() == 0s) {
1863  m_last_tip_update = GetTime<std::chrono::seconds>();
1864  }
1865  return m_last_tip_update.load() <
1866  GetTime<std::chrono::seconds>() -
1867  std::chrono::seconds{consensusParams.nPowTargetSpacing *
1868  3} &&
1869  mapBlocksInFlight.empty();
1870 }
1871 
1872 bool PeerManagerImpl::CanDirectFetch() {
1873  return m_chainman.ActiveChain().Tip()->Time() >
1874  GetAdjustedTime() -
1875  m_chainparams.GetConsensus().PowTargetSpacing() * 20;
1876 }
1877 
1878 static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
1880  if (state->pindexBestKnownBlock &&
1881  pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) {
1882  return true;
1883  }
1884  if (state->pindexBestHeaderSent &&
1885  pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) {
1886  return true;
1887  }
1888  return false;
1889 }
1890 
1891 void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) {
1892  CNodeState *state = State(nodeid);
1893  assert(state != nullptr);
1894 
1895  if (!state->hashLastUnknownBlock.IsNull()) {
1896  const CBlockIndex *pindex =
1897  m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
1898  if (pindex && pindex->nChainWork > 0) {
1899  if (state->pindexBestKnownBlock == nullptr ||
1900  pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1901  state->pindexBestKnownBlock = pindex;
1902  }
1903  state->hashLastUnknownBlock.SetNull();
1904  }
1905  }
1906 }
1907 
1908 void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid,
1909  const BlockHash &hash) {
1910  CNodeState *state = State(nodeid);
1911  assert(state != nullptr);
1912 
1913  ProcessBlockAvailability(nodeid);
1914 
1915  const CBlockIndex *pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
1916  if (pindex && pindex->nChainWork > 0) {
1917  // An actually better block was announced.
1918  if (state->pindexBestKnownBlock == nullptr ||
1919  pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1920  state->pindexBestKnownBlock = pindex;
1921  }
1922  } else {
1923  // An unknown block was announced; just assume that the latest one is
1924  // the best one.
1925  state->hashLastUnknownBlock = hash;
1926  }
1927 }
1928 
1929 void PeerManagerImpl::FindNextBlocksToDownload(
1930  NodeId nodeid, unsigned int count,
1931  std::vector<const CBlockIndex *> &vBlocks, NodeId &nodeStaller) {
1932  if (count == 0) {
1933  return;
1934  }
1935 
1936  vBlocks.reserve(vBlocks.size() + count);
1937  CNodeState *state = State(nodeid);
1938  assert(state != nullptr);
1939 
1940  // Make sure pindexBestKnownBlock is up to date, we'll need it.
1941  ProcessBlockAvailability(nodeid);
1942 
1943  if (state->pindexBestKnownBlock == nullptr ||
1944  state->pindexBestKnownBlock->nChainWork <
1945  m_chainman.ActiveChain().Tip()->nChainWork ||
1946  state->pindexBestKnownBlock->nChainWork <
1947  m_chainman.MinimumChainWork()) {
1948  // This peer has nothing interesting.
1949  return;
1950  }
1951 
1952  if (state->pindexLastCommonBlock == nullptr) {
1953  // Bootstrap quickly by guessing a parent of our best tip is the forking
1954  // point. Guessing wrong in either direction is not a problem.
1955  state->pindexLastCommonBlock =
1956  m_chainman
1957  .ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight,
1958  m_chainman.ActiveChain().Height())];
1959  }
1960 
1961  // If the peer reorganized, our previous pindexLastCommonBlock may not be an
1962  // ancestor of its current tip anymore. Go back enough to fix that.
1963  state->pindexLastCommonBlock = LastCommonAncestor(
1964  state->pindexLastCommonBlock, state->pindexBestKnownBlock);
1965  if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) {
1966  return;
1967  }
1968 
1969  std::vector<const CBlockIndex *> vToFetch;
1970  const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
1971  // Never fetch further than the best block we know the peer has, or more
1972  // than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last linked block we have in
1973  // common with this peer. The +1 is so we can detect stalling, namely if we
1974  // would be able to download that next block if the window were 1 larger.
1975  int nWindowEnd =
1976  state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1977  int nMaxHeight =
1978  std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1979  NodeId waitingfor = -1;
1980  while (pindexWalk->nHeight < nMaxHeight) {
1981  // Read up to 128 (or more, if more blocks than that are needed)
1982  // successors of pindexWalk (towards pindexBestKnownBlock) into
1983  // vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as
1984  // expensive as iterating over ~100 CBlockIndex* entries anyway.
1985  int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight,
1986  std::max<int>(count - vBlocks.size(), 128));
1987  vToFetch.resize(nToFetch);
1988  pindexWalk = state->pindexBestKnownBlock->GetAncestor(
1989  pindexWalk->nHeight + nToFetch);
1990  vToFetch[nToFetch - 1] = pindexWalk;
1991  for (unsigned int i = nToFetch - 1; i > 0; i--) {
1992  vToFetch[i - 1] = vToFetch[i]->pprev;
1993  }
1994 
1995  // Iterate over those blocks in vToFetch (in forward direction), adding
1996  // the ones that are not yet downloaded and not in flight to vBlocks. In
1997  // the meantime, update pindexLastCommonBlock as long as all ancestors
1998  // are already downloaded, or if it's already part of our chain (and
1999  // therefore don't need it even if pruned).
2000  for (const CBlockIndex *pindex : vToFetch) {
2001  if (!pindex->IsValid(BlockValidity::TREE)) {
2002  // We consider the chain that this peer is on invalid.
2003  return;
2004  }
2005  if (pindex->nStatus.hasData() ||
2006  m_chainman.ActiveChain().Contains(pindex)) {
2007  if (pindex->HaveTxsDownloaded()) {
2008  state->pindexLastCommonBlock = pindex;
2009  }
2010  } else if (!IsBlockRequested(pindex->GetBlockHash())) {
2011  // The block is not already downloaded, and not yet in flight.
2012  if (pindex->nHeight > nWindowEnd) {
2013  // We reached the end of the window.
2014  if (vBlocks.size() == 0 && waitingfor != nodeid) {
2015  // We aren't able to fetch anything, but we would be if
2016  // the download window was one larger.
2017  nodeStaller = waitingfor;
2018  }
2019  return;
2020  }
2021  vBlocks.push_back(pindex);
2022  if (vBlocks.size() == count) {
2023  return;
2024  }
2025  } else if (waitingfor == -1) {
2026  // This is the first already-in-flight block.
2027  waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
2028  }
2029  }
2030  }
2031 }
2032 
2033 } // namespace
2034 
2035 template <class InvId>
2036 static bool TooManyAnnouncements(const CNode &node,
2037  const InvRequestTracker<InvId> &requestTracker,
2038  const DataRequestParameters &requestParams) {
2039  return !node.HasPermission(
2040  requestParams.bypass_request_limits_permissions) &&
2041  requestTracker.Count(node.GetId()) >=
2042  requestParams.max_peer_announcements;
2043 }
2044 
2052 template <class InvId>
2053 static std::chrono::microseconds
2055  const InvRequestTracker<InvId> &requestTracker,
2056  const DataRequestParameters &requestParams,
2057  std::chrono::microseconds current_time, bool preferred) {
2058  auto delay = std::chrono::microseconds{0};
2059 
2060  if (!preferred) {
2061  delay += requestParams.nonpref_peer_delay;
2062  }
2063 
2064  if (!node.HasPermission(requestParams.bypass_request_limits_permissions) &&
2065  requestTracker.CountInFlight(node.GetId()) >=
2066  requestParams.max_peer_request_in_flight) {
2067  delay += requestParams.overloaded_peer_delay;
2068  }
2069 
2070  return current_time + delay;
2071 }
2072 
2073 void PeerManagerImpl::PushNodeVersion(const Config &config, CNode &pnode,
2074  const Peer &peer) {
2075  uint64_t my_services{peer.m_our_services};
2076  const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())};
2077  uint64_t nonce = pnode.GetLocalNonce();
2078  const int nNodeStartingHeight{m_best_height};
2079  NodeId nodeid = pnode.GetId();
2080  CAddress addr = pnode.addr;
2081  uint64_t extraEntropy = pnode.GetLocalExtraEntropy();
2082 
2083  CService addr_you =
2084  addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible()
2085  ? addr
2086  : CService();
2087  uint64_t your_services{addr.nServices};
2088 
2089  const bool tx_relay = !m_opts.ignore_incoming_txs &&
2090  !pnode.IsBlockOnlyConn() && !pnode.IsFeelerConn();
2091  m_connman.PushMessage(
2092  // your_services, addr_you: Together the pre-version-31402 serialization
2093  // of CAddress "addrYou" (without nTime)
2094  // my_services, CService(): Together the pre-version-31402 serialization
2095  // of CAddress "addrMe" (without nTime)
2097  .Make(NetMsgType::VERSION, PROTOCOL_VERSION, my_services,
2098  nTime, your_services, addr_you, my_services,
2099  CService(), nonce, userAgent(config),
2100  nNodeStartingHeight, tx_relay, extraEntropy));
2101 
2102  if (fLogIPs) {
2104  "send version message: version %d, blocks=%d, them=%s, "
2105  "txrelay=%d, peer=%d\n",
2106  PROTOCOL_VERSION, nNodeStartingHeight, addr_you.ToString(),
2107  tx_relay, nodeid);
2108  } else {
2110  "send version message: version %d, blocks=%d, "
2111  "txrelay=%d, peer=%d\n",
2112  PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid);
2113  }
2114 }
2115 
2116 void PeerManagerImpl::AddTxAnnouncement(
2117  const CNode &node, const TxId &txid,
2118  std::chrono::microseconds current_time) {
2119  // For m_txrequest and state
2121 
2122  if (TooManyAnnouncements(node, m_txrequest, TX_REQUEST_PARAMS)) {
2123  return;
2124  }
2125 
2126  const bool preferred = isPreferredDownloadPeer(node);
2127  auto reqtime = ComputeRequestTime(node, m_txrequest, TX_REQUEST_PARAMS,
2128  current_time, preferred);
2129 
2130  m_txrequest.ReceivedInv(node.GetId(), txid, preferred, reqtime);
2131 }
2132 
2133 void PeerManagerImpl::AddProofAnnouncement(
2134  const CNode &node, const avalanche::ProofId &proofid,
2135  std::chrono::microseconds current_time, bool preferred) {
2136  // For m_proofrequest
2137  AssertLockHeld(cs_proofrequest);
2138 
2139  if (TooManyAnnouncements(node, m_proofrequest, PROOF_REQUEST_PARAMS)) {
2140  return;
2141  }
2142 
2143  auto reqtime = ComputeRequestTime(
2144  node, m_proofrequest, PROOF_REQUEST_PARAMS, current_time, preferred);
2145 
2146  m_proofrequest.ReceivedInv(node.GetId(), proofid, preferred, reqtime);
2147 }
2148 
2149 void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node,
2150  int64_t time_in_seconds) {
2151  LOCK(cs_main);
2152  CNodeState *state = State(node);
2153  if (state) {
2154  state->m_last_block_announcement = time_in_seconds;
2155  }
2156 }
2157 
2158 void PeerManagerImpl::InitializeNode(const Config &config, CNode &node,
2159  ServiceFlags our_services) {
2160  NodeId nodeid = node.GetId();
2161  {
2162  LOCK(cs_main);
2163  m_node_states.emplace_hint(m_node_states.end(),
2164  std::piecewise_construct,
2165  std::forward_as_tuple(nodeid),
2166  std::forward_as_tuple(node.IsInboundConn()));
2167  assert(m_txrequest.Count(nodeid) == 0);
2168  }
2169  PeerRef peer = std::make_shared<Peer>(nodeid, our_services, !!m_avalanche);
2170  {
2171  LOCK(m_peer_mutex);
2172  m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
2173  }
2174  if (!node.IsInboundConn()) {
2175  PushNodeVersion(config, node, *peer);
2176  }
2177 }
2178 
2179 void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler &scheduler) {
2180  std::set<TxId> unbroadcast_txids = m_mempool.GetUnbroadcastTxs();
2181 
2182  for (const TxId &txid : unbroadcast_txids) {
2183  // Sanity check: all unbroadcast txns should exist in the mempool
2184  if (m_mempool.exists(txid)) {
2185  RelayTransaction(txid);
2186  } else {
2187  m_mempool.RemoveUnbroadcastTx(txid, true);
2188  }
2189  }
2190 
2191  if (m_avalanche) {
2192  // Get and sanitize the list of proofids to broadcast. The RelayProof
2193  // call is done in a second loop to avoid locking cs_vNodes while
2194  // cs_peerManager is locked which would cause a potential deadlock due
2195  // to reversed lock order.
2196  auto unbroadcasted_proofids =
2197  m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2198  auto unbroadcasted_proofids = pm.getUnbroadcastProofs();
2199 
2200  auto it = unbroadcasted_proofids.begin();
2201  while (it != unbroadcasted_proofids.end()) {
2202  // Sanity check: all unbroadcast proofs should be bound to a
2203  // peer in the peermanager
2204  if (!pm.isBoundToPeer(*it)) {
2205  pm.removeUnbroadcastProof(*it);
2206  it = unbroadcasted_proofids.erase(it);
2207  continue;
2208  }
2209 
2210  ++it;
2211  }
2212 
2213  return unbroadcasted_proofids;
2214  });
2215 
2216  // Remaining proofids are the ones to broadcast
2217  for (const auto &proofid : unbroadcasted_proofids) {
2218  RelayProof(proofid);
2219  }
2220  }
2221 
2222  // Schedule next run for 10-15 minutes in the future.
2223  // We add randomness on every cycle to avoid the possibility of P2P
2224  // fingerprinting.
2225  const auto reattemptBroadcastInterval = 10min + GetRandMillis(5min);
2226  scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2227  reattemptBroadcastInterval);
2228 }
2229 
2230 void PeerManagerImpl::UpdateAvalancheStatistics() const {
2231  m_connman.ForEachNode([](CNode *pnode) {
2233  });
2234 
2235  if (!m_avalanche) {
2236  // Not enabled or not ready yet
2237  return;
2238  }
2239 
2240  // Generate a peer availability score by computing an exponentially
2241  // weighted moving average of the average of node availability scores.
2242  // This ensures the peer score is bound to the lifetime of its proof which
2243  // incentivizes stable network activity.
2244  m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2246  AVALANCHE_STATISTICS_DECAY_FACTOR, [&](NodeId nodeid) -> double {
2247  double score{0.0};
2248  m_connman.ForNode(nodeid, [&](CNode *pavanode) {
2249  score = pavanode->getAvailabilityScore();
2250  return true;
2251  });
2252  return score;
2253  });
2254  });
2255 }
2256 
2257 void PeerManagerImpl::AvalanchePeriodicNetworking(CScheduler &scheduler) const {
2258  const auto now = GetTime<std::chrono::seconds>();
2259  std::vector<NodeId> avanode_ids;
2260  bool fQuorumEstablished;
2261  bool fShouldRequestMoreNodes;
2262 
2263  if (!m_avalanche) {
2264  // Not enabled or not ready yet, retry later
2265  goto scheduleLater;
2266  }
2267 
2268  m_avalanche->sendDelayedAvahello();
2269 
2270  fQuorumEstablished = m_avalanche->isQuorumEstablished();
2271  fShouldRequestMoreNodes =
2272  m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2273  return pm.shouldRequestMoreNodes();
2274  });
2275 
2276  m_connman.ForEachNode([&](CNode *pnode) {
2277  // Build a list of the avalanche peers nodeids
2278  if (pnode->m_avalanche_enabled) {
2279  avanode_ids.push_back(pnode->GetId());
2280  }
2281 
2282  PeerRef peer = GetPeerRef(pnode->GetId());
2283  if (peer == nullptr) {
2284  return;
2285  }
2286  // If a proof radix tree timed out, cleanup
2287  if (peer->m_proof_relay &&
2288  now > (peer->m_proof_relay->lastSharedProofsUpdate.load() +
2290  peer->m_proof_relay->sharedProofs = {};
2291  }
2292  });
2293 
2294  if (avanode_ids.empty()) {
2295  // No node is available for messaging, retry later
2296  goto scheduleLater;
2297  }
2298 
2299  Shuffle(avanode_ids.begin(), avanode_ids.end(), FastRandomContext());
2300 
2301  // Request avalanche addresses from our peers
2302  for (NodeId avanodeId : avanode_ids) {
2303  const bool sentGetavaaddr =
2304  m_connman.ForNode(avanodeId, [&](CNode *pavanode) {
2305  if (!fQuorumEstablished || !pavanode->IsInboundConn()) {
2306  m_connman.PushMessage(
2307  pavanode, CNetMsgMaker(pavanode->GetCommonVersion())
2308  .Make(NetMsgType::GETAVAADDR));
2309  PeerRef peer = GetPeerRef(avanodeId);
2310  WITH_LOCK(peer->m_addr_token_bucket_mutex,
2311  peer->m_addr_token_bucket +=
2312  m_opts.max_addr_to_send);
2313  return true;
2314  }
2315  return false;
2316  });
2317 
2318  // If we have no reason to believe that we need more nodes, only request
2319  // addresses from one of our peers.
2320  if (sentGetavaaddr && fQuorumEstablished && !fShouldRequestMoreNodes) {
2321  break;
2322  }
2323  }
2324 
2325  if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
2326  // Don't request proofs while in IBD. We're likely to orphan them
2327  // because we don't have the UTXOs.
2328  goto scheduleLater;
2329  }
2330 
2331  // If we never had an avaproofs message yet, be kind and only request to a
2332  // subset of our peers as we expect a ton of avaproofs message in the
2333  // process.
2334  if (m_avalanche->getAvaproofsNodeCounter() == 0) {
2335  avanode_ids.resize(std::min<size_t>(avanode_ids.size(), 3));
2336  }
2337 
2338  for (NodeId nodeid : avanode_ids) {
2339  // Send a getavaproofs to all of our peers
2340  m_connman.ForNode(nodeid, [&](CNode *pavanode) {
2341  PeerRef peer = GetPeerRef(nodeid);
2342  if (peer->m_proof_relay) {
2343  m_connman.PushMessage(pavanode,
2344  CNetMsgMaker(pavanode->GetCommonVersion())
2346 
2347  peer->m_proof_relay->compactproofs_requested = true;
2348  }
2349  return true;
2350  });
2351  }
2352 
2353 scheduleLater:
2354  // Schedule next run for 2-5 minutes in the future.
2355  // We add randomness on every cycle to avoid the possibility of P2P
2356  // fingerprinting.
2357  const auto avalanchePeriodicNetworkingInterval = 2min + GetRandMillis(3min);
2358  scheduler.scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2359  avalanchePeriodicNetworkingInterval);
2360 }
2361 
2362 void PeerManagerImpl::FinalizeNode(const Config &config, const CNode &node) {
2363  NodeId nodeid = node.GetId();
2364  int misbehavior{0};
2365  {
2366  LOCK(cs_main);
2367  {
2368  // We remove the PeerRef from g_peer_map here, but we don't always
2369  // destruct the Peer. Sometimes another thread is still holding a
2370  // PeerRef, so the refcount is >= 1. Be careful not to do any
2371  // processing here that assumes Peer won't be changed before it's
2372  // destructed.
2373  PeerRef peer = RemovePeer(nodeid);
2374  assert(peer != nullptr);
2375  misbehavior = WITH_LOCK(peer->m_misbehavior_mutex,
2376  return peer->m_misbehavior_score);
2377  LOCK(m_peer_mutex);
2378  m_peer_map.erase(nodeid);
2379  }
2380  CNodeState *state = State(nodeid);
2381  assert(state != nullptr);
2382 
2383  if (state->fSyncStarted) {
2384  nSyncStarted--;
2385  }
2386 
2387  for (const QueuedBlock &entry : state->vBlocksInFlight) {
2388  mapBlocksInFlight.erase(entry.pindex->GetBlockHash());
2389  }
2390  m_orphanage.EraseForPeer(nodeid);
2391  m_txrequest.DisconnectedPeer(nodeid);
2392  m_num_preferred_download_peers -= state->fPreferredDownload;
2393  m_peers_downloading_from -= (state->nBlocksInFlight != 0);
2394  assert(m_peers_downloading_from >= 0);
2395  m_outbound_peers_with_protect_from_disconnect -=
2396  state->m_chain_sync.m_protect;
2397  assert(m_outbound_peers_with_protect_from_disconnect >= 0);
2398 
2399  m_node_states.erase(nodeid);
2400 
2401  if (m_node_states.empty()) {
2402  // Do a consistency check after the last peer is removed.
2403  assert(mapBlocksInFlight.empty());
2404  assert(m_num_preferred_download_peers == 0);
2405  assert(m_peers_downloading_from == 0);
2406  assert(m_outbound_peers_with_protect_from_disconnect == 0);
2407  assert(m_txrequest.Size() == 0);
2408  assert(m_orphanage.Size() == 0);
2409  }
2410  }
2411 
2412  if (node.fSuccessfullyConnected && misbehavior == 0 &&
2413  !node.IsBlockOnlyConn() && !node.IsInboundConn()) {
2414  // Only change visible addrman state for full outbound peers. We don't
2415  // call Connected() for feeler connections since they don't have
2416  // fSuccessfullyConnected set.
2417  m_addrman.Connected(node.addr);
2418  }
2419  {
2420  LOCK(m_headers_presync_mutex);
2421  m_headers_presync_stats.erase(nodeid);
2422  }
2423 
2424  WITH_LOCK(cs_proofrequest, m_proofrequest.DisconnectedPeer(nodeid));
2425 
2426  LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
2427 }
2428 
2429 PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const {
2430  LOCK(m_peer_mutex);
2431  auto it = m_peer_map.find(id);
2432  return it != m_peer_map.end() ? it->second : nullptr;
2433 }
2434 
2435 PeerRef PeerManagerImpl::RemovePeer(NodeId id) {
2436  PeerRef ret;
2437  LOCK(m_peer_mutex);
2438  auto it = m_peer_map.find(id);
2439  if (it != m_peer_map.end()) {
2440  ret = std::move(it->second);
2441  m_peer_map.erase(it);
2442  }
2443  return ret;
2444 }
2445 
2446 bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid,
2447  CNodeStateStats &stats) const {
2448  {
2449  LOCK(cs_main);
2450  const CNodeState *state = State(nodeid);
2451  if (state == nullptr) {
2452  return false;
2453  }
2454  stats.nSyncHeight = state->pindexBestKnownBlock
2455  ? state->pindexBestKnownBlock->nHeight
2456  : -1;
2457  stats.nCommonHeight = state->pindexLastCommonBlock
2458  ? state->pindexLastCommonBlock->nHeight
2459  : -1;
2460  for (const QueuedBlock &queue : state->vBlocksInFlight) {
2461  if (queue.pindex) {
2462  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
2463  }
2464  }
2465  }
2466 
2467  PeerRef peer = GetPeerRef(nodeid);
2468  if (peer == nullptr) {
2469  return false;
2470  }
2471  stats.their_services = peer->m_their_services;
2472  stats.m_starting_height = peer->m_starting_height;
2473  // It is common for nodes with good ping times to suddenly become lagged,
2474  // due to a new block arriving or other large transfer.
2475  // Merely reporting pingtime might fool the caller into thinking the node
2476  // was still responsive, since pingtime does not update until the ping is
2477  // complete, which might take a while. So, if a ping is taking an unusually
2478  // long time in flight, the caller can immediately detect that this is
2479  // happening.
2480  auto ping_wait{0us};
2481  if ((0 != peer->m_ping_nonce_sent) &&
2482  (0 != peer->m_ping_start.load().count())) {
2483  ping_wait =
2484  GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
2485  }
2486 
2487  if (auto tx_relay = peer->GetTxRelay()) {
2488  stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex,
2489  return tx_relay->m_relay_txs);
2490  stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load();
2491  } else {
2492  stats.m_relay_txs = false;
2494  }
2495 
2496  stats.m_ping_wait = ping_wait;
2497  stats.m_addr_processed = peer->m_addr_processed.load();
2498  stats.m_addr_rate_limited = peer->m_addr_rate_limited.load();
2499  stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load();
2500  {
2501  LOCK(peer->m_headers_sync_mutex);
2502  if (peer->m_headers_sync) {
2503  stats.presync_height = peer->m_headers_sync->GetPresyncHeight();
2504  }
2505  }
2506 
2507  return true;
2508 }
2509 
2510 void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef &tx) {
2511  if (m_opts.max_extra_txs <= 0) {
2512  return;
2513  }
2514 
2515  if (!vExtraTxnForCompact.size()) {
2516  vExtraTxnForCompact.resize(m_opts.max_extra_txs);
2517  }
2518 
2519  vExtraTxnForCompact[vExtraTxnForCompactIt] =
2520  std::make_pair(tx->GetHash(), tx);
2521  vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs;
2522 }
2523 
2524 void PeerManagerImpl::Misbehaving(Peer &peer, int howmuch,
2525  const std::string &message) {
2526  assert(howmuch > 0);
2527 
2528  LOCK(peer.m_misbehavior_mutex);
2529  const int score_before{peer.m_misbehavior_score};
2530  peer.m_misbehavior_score += howmuch;
2531  const int score_now{peer.m_misbehavior_score};
2532 
2533  const std::string message_prefixed =
2534  message.empty() ? "" : (": " + message);
2535  std::string warning;
2536 
2537  if (score_now >= DISCOURAGEMENT_THRESHOLD &&
2538  score_before < DISCOURAGEMENT_THRESHOLD) {
2539  warning = " DISCOURAGE THRESHOLD EXCEEDED";
2540  peer.m_should_discourage = true;
2541  }
2542 
2543  LogPrint(BCLog::NET, "Misbehaving: peer=%d (%d -> %d)%s%s\n", peer.m_id,
2544  score_before, score_now, warning, message_prefixed);
2545 }
2546 
2547 bool PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid,
2548  const BlockValidationState &state,
2549  bool via_compact_block,
2550  const std::string &message) {
2551  PeerRef peer{GetPeerRef(nodeid)};
2552  switch (state.GetResult()) {
2554  break;
2556  // We didn't try to process the block because the header chain may
2557  // have too little work.
2558  break;
2559  // The node is providing invalid data:
2562  if (!via_compact_block) {
2563  if (peer) {
2564  Misbehaving(*peer, 100, message);
2565  }
2566  return true;
2567  }
2568  break;
2570  LOCK(cs_main);
2571  CNodeState *node_state = State(nodeid);
2572  if (node_state == nullptr) {
2573  break;
2574  }
2575 
2576  // Ban outbound (but not inbound) peers if on an invalid chain.
2577  // Exempt HB compact block peers. Manual connections are always
2578  // protected from discouragement.
2579  if (!via_compact_block && !node_state->m_is_inbound) {
2580  if (peer) {
2581  Misbehaving(*peer, 100, message);
2582  }
2583  return true;
2584  }
2585  break;
2586  }
2590  if (peer) {
2591  Misbehaving(*peer, 100, message);
2592  }
2593  return true;
2594  // Conflicting (but not necessarily invalid) data or different policy:
2596  // TODO: Handle this much more gracefully (10 DoS points is super
2597  // arbitrary)
2598  if (peer) {
2599  Misbehaving(*peer, 10, message);
2600  }
2601  return true;
2603  break;
2604  }
2605  if (message != "") {
2606  LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
2607  }
2608  return false;
2609 }
2610 
2611 bool PeerManagerImpl::MaybePunishNodeForTx(NodeId nodeid,
2612  const TxValidationState &state,
2613  const std::string &message) {
2614  PeerRef peer{GetPeerRef(nodeid)};
2615  switch (state.GetResult()) {
2617  break;
2618  // The node is providing invalid data:
2620  if (peer) {
2621  Misbehaving(*peer, 100, message);
2622  }
2623  return true;
2624  // Conflicting (but not necessarily invalid) data or different policy:
2636  break;
2637  }
2638  if (message != "") {
2639  LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
2640  }
2641  return false;
2642 }
2643 
2644 bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex *pindex) {
2646  if (m_chainman.ActiveChain().Contains(pindex)) {
2647  return true;
2648  }
2649  return pindex->IsValid(BlockValidity::SCRIPTS) &&
2650  (m_chainman.m_best_header != nullptr) &&
2651  (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() <
2654  *m_chainman.m_best_header, *pindex, *m_chainman.m_best_header,
2655  m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
2656 }
2657 
2658 std::optional<std::string>
2659 PeerManagerImpl::FetchBlock(const Config &config, NodeId peer_id,
2660  const CBlockIndex &block_index) {
2661  if (m_chainman.m_blockman.LoadingBlocks()) {
2662  return "Loading blocks ...";
2663  }
2664 
2665  LOCK(cs_main);
2666  // Ensure this peer exists and hasn't been disconnected
2667  CNodeState *state = State(peer_id);
2668  if (state == nullptr) {
2669  return "Peer does not exist";
2670  }
2671  // Mark block as in-flight unless it already is (for this peer).
2672  // If a block was already in-flight for a different peer, its BLOCKTXN
2673  // response will be dropped.
2674  if (!BlockRequested(config, peer_id, block_index)) {
2675  return "Already requested from this peer";
2676  }
2677 
2678  // Construct message to request the block
2679  const BlockHash &hash{block_index.GetBlockHash()};
2680  const std::vector<CInv> invs{CInv(MSG_BLOCK, hash)};
2681 
2682  // Send block request message to the peer
2683  if (!m_connman.ForNode(peer_id, [this, &invs](CNode *node) {
2684  const CNetMsgMaker msgMaker(node->GetCommonVersion());
2685  this->m_connman.PushMessage(
2686  node, msgMaker.Make(NetMsgType::GETDATA, invs));
2687  return true;
2688  })) {
2689  return "Node not fully connected";
2690  }
2691 
2692  LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n", hash.ToString(),
2693  peer_id);
2694  return std::nullopt;
2695 }
2696 
2697 std::unique_ptr<PeerManager>
2698 PeerManager::make(CConnman &connman, AddrMan &addrman, BanMan *banman,
2699  ChainstateManager &chainman, CTxMemPool &pool,
2700  avalanche::Processor *const avalanche, Options opts) {
2701  return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman,
2702  pool, avalanche, opts);
2703 }
2704 
2705 PeerManagerImpl::PeerManagerImpl(CConnman &connman, AddrMan &addrman,
2706  BanMan *banman, ChainstateManager &chainman,
2707  CTxMemPool &pool,
2709  Options opts)
2710  : m_rng{opts.deterministic_rng},
2711  m_fee_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE_PER_KB}, m_rng},
2712  m_chainparams(chainman.GetParams()), m_connman(connman),
2713  m_addrman(addrman), m_banman(banman), m_chainman(chainman),
2714  m_mempool(pool), m_avalanche(avalanche), m_opts{opts} {}
2715 
2716 void PeerManagerImpl::StartScheduledTasks(CScheduler &scheduler) {
2717  // Stale tip checking and peer eviction are on two different timers, but we
2718  // don't want them to get out of sync due to drift in the scheduler, so we
2719  // combine them in one function and schedule at the quicker (peer-eviction)
2720  // timer.
2721  static_assert(
2723  "peer eviction timer should be less than stale tip check timer");
2724  scheduler.scheduleEvery(
2725  [this]() {
2726  this->CheckForStaleTipAndEvictPeers();
2727  return true;
2728  },
2729  std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL});
2730 
2731  // schedule next run for 10-15 minutes in the future
2732  const auto reattemptBroadcastInterval = 10min + GetRandMillis(5min);
2733  scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2734  reattemptBroadcastInterval);
2735 
2736  // Update the avalanche statistics on a schedule
2737  scheduler.scheduleEvery(
2738  [this]() {
2739  UpdateAvalancheStatistics();
2740  return true;
2741  },
2743 
2744  // schedule next run for 2-5 minutes in the future
2745  const auto avalanchePeriodicNetworkingInterval = 2min + GetRandMillis(3min);
2746  scheduler.scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2747  avalanchePeriodicNetworkingInterval);
2748 }
2749 
2756 void PeerManagerImpl::BlockConnected(
2757  const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
2758  m_orphanage.EraseForBlock(*pblock);
2759  m_last_tip_update = GetTime<std::chrono::seconds>();
2760 
2761  {
2762  LOCK(m_recent_confirmed_transactions_mutex);
2763  for (const CTransactionRef &ptx : pblock->vtx) {
2764  m_recent_confirmed_transactions.insert(ptx->GetId());
2765  }
2766  }
2767  {
2768  LOCK(cs_main);
2769  for (const auto &ptx : pblock->vtx) {
2770  m_txrequest.ForgetInvId(ptx->GetId());
2771  }
2772  }
2773 
2774  // In case the dynamic timeout was doubled once or more, reduce it slowly
2775  // back to its default value
2776  auto stalling_timeout = m_block_stalling_timeout.load();
2777  Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT);
2778  if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) {
2779  const auto new_timeout =
2780  std::max(std::chrono::duration_cast<std::chrono::seconds>(
2781  stalling_timeout * 0.85),
2783  if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout,
2784  new_timeout)) {
2785  LogPrint(BCLog::NET, "Decreased stalling timeout to %d seconds\n",
2786  count_seconds(new_timeout));
2787  }
2788  }
2789 }
2790 
2791 void PeerManagerImpl::BlockDisconnected(
2792  const std::shared_ptr<const CBlock> &block, const CBlockIndex *pindex) {
2793  // To avoid relay problems with transactions that were previously
2794  // confirmed, clear our filter of recently confirmed transactions whenever
2795  // there's a reorg.
2796  // This means that in a 1-block reorg (where 1 block is disconnected and
2797  // then another block reconnected), our filter will drop to having only one
2798  // block's worth of transactions in it, but that should be fine, since
2799  // presumably the most common case of relaying a confirmed transaction
2800  // should be just after a new block containing it is found.
2801  LOCK(m_recent_confirmed_transactions_mutex);
2802  m_recent_confirmed_transactions.reset();
2803 }
2804 
2809 void PeerManagerImpl::NewPoWValidBlock(
2810  const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &pblock) {
2811  std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock =
2812  std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock);
2813  const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
2814 
2815  LOCK(cs_main);
2816 
2817  if (pindex->nHeight <= m_highest_fast_announce) {
2818  return;
2819  }
2820  m_highest_fast_announce = pindex->nHeight;
2821 
2822  BlockHash hashBlock(pblock->GetHash());
2823  const std::shared_future<CSerializedNetMsg> lazy_ser{
2824  std::async(std::launch::deferred, [&] {
2825  return msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock);
2826  })};
2827 
2828  {
2829  LOCK(m_most_recent_block_mutex);
2830  m_most_recent_block_hash = hashBlock;
2831  m_most_recent_block = pblock;
2832  m_most_recent_compact_block = pcmpctblock;
2833  }
2834 
2835  m_connman.ForEachNode(
2836  [this, pindex, &lazy_ser, &hashBlock](CNode *pnode)
2839 
2841  pnode->fDisconnect) {
2842  return;
2843  }
2844  ProcessBlockAvailability(pnode->GetId());
2845  CNodeState &state = *State(pnode->GetId());
2846  // If the peer has, or we announced to them the previous block
2847  // already, but we don't think they have this one, go ahead and
2848  // announce it.
2849  if (state.m_requested_hb_cmpctblocks &&
2850  !PeerHasHeader(&state, pindex) &&
2851  PeerHasHeader(&state, pindex->pprev)) {
2853  "%s sending header-and-ids %s to peer=%d\n",
2854  "PeerManager::NewPoWValidBlock",
2855  hashBlock.ToString(), pnode->GetId());
2856 
2857  const CSerializedNetMsg &ser_cmpctblock{lazy_ser.get()};
2858  m_connman.PushMessage(pnode, ser_cmpctblock.Copy());
2859  state.pindexBestHeaderSent = pindex;
2860  }
2861  });
2862 }
2863 
2868 void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew,
2869  const CBlockIndex *pindexFork,
2870  bool fInitialDownload) {
2871  SetBestHeight(pindexNew->nHeight);
2872  SetServiceFlagsIBDCache(!fInitialDownload);
2873 
2874  // Don't relay inventory during initial block download.
2875  if (fInitialDownload) {
2876  return;
2877  }
2878 
2879  // Find the hashes of all blocks that weren't previously in the best chain.
2880  std::vector<BlockHash> vHashes;
2881  const CBlockIndex *pindexToAnnounce = pindexNew;
2882  while (pindexToAnnounce != pindexFork) {
2883  vHashes.push_back(pindexToAnnounce->GetBlockHash());
2884  pindexToAnnounce = pindexToAnnounce->pprev;
2885  if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
2886  // Limit announcements in case of a huge reorganization. Rely on the
2887  // peer's synchronization mechanism in that case.
2888  break;
2889  }
2890  }
2891 
2892  {
2893  LOCK(m_peer_mutex);
2894  for (auto &it : m_peer_map) {
2895  Peer &peer = *it.second;
2896  LOCK(peer.m_block_inv_mutex);
2897  for (const BlockHash &hash : reverse_iterate(vHashes)) {
2898  peer.m_blocks_for_headers_relay.push_back(hash);
2899  }
2900  }
2901  }
2902 
2903  m_connman.WakeMessageHandler();
2904 }
2905 
2910 void PeerManagerImpl::BlockChecked(const CBlock &block,
2911  const BlockValidationState &state) {
2912  LOCK(cs_main);
2913 
2914  const BlockHash hash = block.GetHash();
2915  std::map<BlockHash, std::pair<NodeId, bool>>::iterator it =
2916  mapBlockSource.find(hash);
2917 
2918  // If the block failed validation, we know where it came from and we're
2919  // still connected to that peer, maybe punish.
2920  if (state.IsInvalid() && it != mapBlockSource.end() &&
2921  State(it->second.first)) {
2922  MaybePunishNodeForBlock(/*nodeid=*/it->second.first, state,
2923  /*via_compact_block=*/!it->second.second);
2924  }
2925  // Check that:
2926  // 1. The block is valid
2927  // 2. We're not in initial block download
2928  // 3. This is currently the best block we're aware of. We haven't updated
2929  // the tip yet so we have no way to check this directly here. Instead we
2930  // just check that there are currently no other blocks in flight.
2931  else if (state.IsValid() &&
2932  !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
2933  mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
2934  if (it != mapBlockSource.end()) {
2935  MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
2936  }
2937  }
2938 
2939  if (it != mapBlockSource.end()) {
2940  mapBlockSource.erase(it);
2941  }
2942 }
2943 
2945 //
2946 // Messages
2947 //
2948 
2949 bool PeerManagerImpl::AlreadyHaveTx(const TxId &txid,
2950  bool include_reconsiderable) {
2951  if (m_chainman.ActiveChain().Tip()->GetBlockHash() !=
2952  hashRecentRejectsChainTip) {
2953  // If the chain tip has changed previously rejected transactions
2954  // might be now valid, e.g. due to a nLockTime'd tx becoming
2955  // valid, or a double-spend. Reset the rejects filter and give
2956  // those txs a second chance.
2957  hashRecentRejectsChainTip =
2958  m_chainman.ActiveChain().Tip()->GetBlockHash();
2959  m_recent_rejects.reset();
2960  m_recent_rejects_reconsiderable.reset();
2961  }
2962 
2963  if (m_orphanage.HaveTx(txid)) {
2964  return true;
2965  }
2966 
2967  if (include_reconsiderable &&
2968  m_recent_rejects_reconsiderable.contains(txid)) {
2969  return true;
2970  }
2971 
2972  {
2973  LOCK(m_recent_confirmed_transactions_mutex);
2974  if (m_recent_confirmed_transactions.contains(txid)) {
2975  return true;
2976  }
2977  }
2978 
2979  return m_recent_rejects.contains(txid) || m_mempool.exists(txid);
2980 }
2981 
2982 bool PeerManagerImpl::AlreadyHaveBlock(const BlockHash &block_hash) {
2983  return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
2984 }
2985 
2986 bool PeerManagerImpl::AlreadyHaveProof(const avalanche::ProofId &proofid) {
2987  assert(m_avalanche);
2988 
2989  auto localProof = m_avalanche->getLocalProof();
2990  if (localProof && localProof->getId() == proofid) {
2991  return true;
2992  }
2993 
2994  return m_avalanche->withPeerManager([&proofid](avalanche::PeerManager &pm) {
2995  return pm.exists(proofid) || pm.isInvalid(proofid);
2996  });
2997 }
2998 
2999 void PeerManagerImpl::SendPings() {
3000  LOCK(m_peer_mutex);
3001  for (auto &it : m_peer_map) {
3002  it.second->m_ping_queued = true;
3003  }
3004 }
3005 
3006 void PeerManagerImpl::RelayTransaction(const TxId &txid) {
3007  LOCK(m_peer_mutex);
3008  for (auto &it : m_peer_map) {
3009  Peer &peer = *it.second;
3010  auto tx_relay = peer.GetTxRelay();
3011  if (!tx_relay) {
3012  continue;
3013  }
3014  LOCK(tx_relay->m_tx_inventory_mutex);
3015  if (!tx_relay->m_tx_inventory_known_filter.contains(txid)) {
3016  tx_relay->m_tx_inventory_to_send.insert(txid);
3017  }
3018  }
3019 }
3020 
3021 void PeerManagerImpl::RelayProof(const avalanche::ProofId &proofid) {
3022  LOCK(m_peer_mutex);
3023  for (auto &it : m_peer_map) {
3024  Peer &peer = *it.second;
3025 
3026  if (!peer.m_proof_relay) {
3027  continue;
3028  }
3029  LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
3030  if (!peer.m_proof_relay->m_proof_inventory_known_filter.contains(
3031  proofid)) {
3032  peer.m_proof_relay->m_proof_inventory_to_send.insert(proofid);
3033  }
3034  }
3035 }
3036 
3037 void PeerManagerImpl::RelayAddress(NodeId originator, const CAddress &addr,
3038  bool fReachable) {
3039  // We choose the same nodes within a given 24h window (if the list of
3040  // connected nodes does not change) and we don't relay to nodes that already
3041  // know an address. So within 24h we will likely relay a given address once.
3042  // This is to prevent a peer from unjustly giving their address better
3043  // propagation by sending it to us repeatedly.
3044 
3045  if (!fReachable && !addr.IsRelayable()) {
3046  return;
3047  }
3048 
3049  // Relay to a limited number of other nodes
3050  // Use deterministic randomness to send to the same nodes for 24 hours
3051  // at a time so the m_addr_knowns of the chosen nodes prevent repeats
3052  const uint64_t hash_addr{CServiceHash(0, 0)(addr)};
3053  const auto current_time{GetTime<std::chrono::seconds>()};
3054  // Adding address hash makes exact rotation time different per address,
3055  // while preserving periodicity.
3056  const uint64_t time_addr{
3057  (static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) /
3059 
3060  const CSipHasher hasher{
3062  .Write(hash_addr)
3063  .Write(time_addr)};
3064 
3065  // Relay reachable addresses to 2 peers. Unreachable addresses are relayed
3066  // randomly to 1 or 2 peers.
3067  unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
3068  std::array<std::pair<uint64_t, Peer *>, 2> best{
3069  {{0, nullptr}, {0, nullptr}}};
3070  assert(nRelayNodes <= best.size());
3071 
3072  LOCK(m_peer_mutex);
3073 
3074  for (auto &[id, peer] : m_peer_map) {
3075  if (peer->m_addr_relay_enabled && id != originator &&
3076  IsAddrCompatible(*peer, addr)) {
3077  uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
3078  for (unsigned int i = 0; i < nRelayNodes; i++) {
3079  if (hashKey > best[i].first) {
3080  std::copy(best.begin() + i, best.begin() + nRelayNodes - 1,
3081  best.begin() + i + 1);
3082  best[i] = std::make_pair(hashKey, peer.get());
3083  break;
3084  }
3085  }
3086  }
3087  };
3088 
3089  for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
3090  PushAddress(*best[i].second, addr);
3091  }
3092 }
3093 
3094 void PeerManagerImpl::ProcessGetBlockData(const Config &config, CNode &pfrom,
3095  Peer &peer, const CInv &inv) {
3096  const BlockHash hash(inv.hash);
3097 
3098  std::shared_ptr<const CBlock> a_recent_block;
3099  std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
3100  {
3101  LOCK(m_most_recent_block_mutex);
3102  a_recent_block = m_most_recent_block;
3103  a_recent_compact_block = m_most_recent_compact_block;
3104  }
3105 
3106  bool need_activate_chain = false;
3107  {
3108  LOCK(cs_main);
3109  const CBlockIndex *pindex =
3110  m_chainman.m_blockman.LookupBlockIndex(hash);
3111  if (pindex) {
3112  if (pindex->HaveTxsDownloaded() &&
3113  !pindex->IsValid(BlockValidity::SCRIPTS) &&
3114  pindex->IsValid(BlockValidity::TREE)) {
3115  // If we have the block and all of its parents, but have not yet
3116  // validated it, we might be in the middle of connecting it (ie
3117  // in the unlock of cs_main before ActivateBestChain but after
3118  // AcceptBlock). In this case, we need to run ActivateBestChain
3119  // prior to checking the relay conditions below.
3120  need_activate_chain = true;
3121  }
3122  }
3123  } // release cs_main before calling ActivateBestChain
3124  if (need_activate_chain) {
3125  BlockValidationState state;
3126  if (!m_chainman.ActiveChainstate().ActivateBestChain(
3127  state, a_recent_block, m_avalanche)) {
3128  LogPrint(BCLog::NET, "failed to activate chain (%s)\n",
3129  state.ToString());
3130  }
3131  }
3132 
3133  LOCK(cs_main);
3134  const CBlockIndex *pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
3135  if (!pindex) {
3136  return;
3137  }
3138  if (!BlockRequestAllowed(pindex)) {
3140  "%s: ignoring request from peer=%i for old "
3141  "block that isn't in the main chain\n",
3142  __func__, pfrom.GetId());
3143  return;
3144  }
3145  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3146  // Disconnect node in case we have reached the outbound limit for serving
3147  // historical blocks.
3148  if (m_connman.OutboundTargetReached(true) &&
3149  (((m_chainman.m_best_header != nullptr) &&
3150  (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() >
3152  inv.IsMsgFilteredBlk()) &&
3153  // nodes with the download permission may exceed target
3156  "historical block serving limit reached, disconnect peer=%d\n",
3157  pfrom.GetId());
3158  pfrom.fDisconnect = true;
3159  return;
3160  }
3161  // Avoid leaking prune-height by never sending blocks below the
3162  // NODE_NETWORK_LIMITED threshold.
3163  // Add two blocks buffer extension for possible races
3165  ((((peer.m_our_services & NODE_NETWORK_LIMITED) ==
3167  ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) &&
3168  (m_chainman.ActiveChain().Tip()->nHeight - pindex->nHeight >
3169  (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2)))) {
3171  "Ignore block request below NODE_NETWORK_LIMITED "
3172  "threshold, disconnect peer=%d\n",
3173  pfrom.GetId());
3174 
3175  // disconnect node and prevent it from stalling (would otherwise wait
3176  // for the missing block)
3177  pfrom.fDisconnect = true;
3178  return;
3179  }
3180  // Pruned nodes may have deleted the block, so check whether it's available
3181  // before trying to send.
3182  if (!pindex->nStatus.hasData()) {
3183  return;
3184  }
3185  std::shared_ptr<const CBlock> pblock;
3186  if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
3187  pblock = a_recent_block;
3188  } else {
3189  // Send block from disk
3190  std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
3191  if (!m_chainman.m_blockman.ReadBlockFromDisk(*pblockRead, *pindex)) {
3192  assert(!"cannot load block from disk");
3193  }
3194  pblock = pblockRead;
3195  }
3196  if (inv.IsMsgBlk()) {
3197  m_connman.PushMessage(&pfrom,
3198  msgMaker.Make(NetMsgType::BLOCK, *pblock));
3199  } else if (inv.IsMsgFilteredBlk()) {
3200  bool sendMerkleBlock = false;
3201  CMerkleBlock merkleBlock;
3202  if (auto tx_relay = peer.GetTxRelay()) {
3203  LOCK(tx_relay->m_bloom_filter_mutex);
3204  if (tx_relay->m_bloom_filter) {
3205  sendMerkleBlock = true;
3206  merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
3207  }
3208  }
3209  if (sendMerkleBlock) {
3210  m_connman.PushMessage(
3211  &pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
3212  // CMerkleBlock just contains hashes, so also push any
3213  // transactions in the block the client did not see. This avoids
3214  // hurting performance by pointlessly requiring a round-trip.
3215  // Note that there is currently no way for a node to request any
3216  // single transactions we didn't send here - they must either
3217  // disconnect and retry or request the full block. Thus, the
3218  // protocol spec specified allows for us to provide duplicate
3219  // txn here, however we MUST always provide at least what the
3220  // remote peer needs.
3221  typedef std::pair<size_t, uint256> PairType;
3222  for (PairType &pair : merkleBlock.vMatchedTxn) {
3223  m_connman.PushMessage(
3224  &pfrom,
3225  msgMaker.Make(NetMsgType::TX, *pblock->vtx[pair.first]));
3226  }
3227  }
3228  // else
3229  // no response
3230  } else if (inv.IsMsgCmpctBlk()) {
3231  // If a peer is asking for old blocks, we're almost guaranteed they
3232  // won't have a useful mempool to match against a compact block, and
3233  // we don't feel like constructing the object for them, so instead
3234  // we respond with the full, non-compact block.
3235  int nSendFlags = 0;
3236  if (CanDirectFetch() &&
3237  pindex->nHeight >=
3238  m_chainman.ActiveChain().Height() - MAX_CMPCTBLOCK_DEPTH) {
3239  if (a_recent_compact_block &&
3240  a_recent_compact_block->header.GetHash() ==
3241  pindex->GetBlockHash()) {
3242  m_connman.PushMessage(&pfrom,
3243  msgMaker.Make(NetMsgType::CMPCTBLOCK,
3244  *a_recent_compact_block));
3245  } else {
3246  CBlockHeaderAndShortTxIDs cmpctblock(*pblock);
3247  m_connman.PushMessage(
3248  &pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK,
3249  cmpctblock));
3250  }
3251  } else {
3252  m_connman.PushMessage(
3253  &pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
3254  }
3255  }
3256 
3257  {
3258  LOCK(peer.m_block_inv_mutex);
3259  // Trigger the peer node to send a getblocks request for the next
3260  // batch of inventory.
3261  if (hash == peer.m_continuation_block) {
3262  // Send immediately. This must send even if redundant, and
3263  // we want it right after the last block so they don't wait for
3264  // other stuff first.
3265  std::vector<CInv> vInv;
3266  vInv.push_back(CInv(
3267  MSG_BLOCK, m_chainman.ActiveChain().Tip()->GetBlockHash()));
3268  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::INV, vInv));
3269  peer.m_continuation_block = BlockHash();
3270  }
3271  }
3272 }
3273 
3275 PeerManagerImpl::FindTxForGetData(const Peer &peer, const TxId &txid,
3276  const std::chrono::seconds mempool_req,
3277  const std::chrono::seconds now) {
3278  auto txinfo = m_mempool.info(txid);
3279  if (txinfo.tx) {
3280  // If a TX could have been INVed in reply to a MEMPOOL request,
3281  // or is older than UNCONDITIONAL_RELAY_DELAY, permit the request
3282  // unconditionally.
3283  if ((mempool_req.count() && txinfo.m_time <= mempool_req) ||
3284  txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
3285  return std::move(txinfo.tx);
3286  }
3287  }
3288 
3289  {
3290  LOCK(cs_main);
3291 
3292  // Otherwise, the transaction must have been announced recently.
3293  if (Assume(peer.GetTxRelay())
3294  ->m_recently_announced_invs.contains(txid)) {
3295  // If it was, it can be relayed from either the mempool...
3296  if (txinfo.tx) {
3297  return std::move(txinfo.tx);
3298  }
3299  // ... or the relay pool.
3300  auto mi = mapRelay.find(txid);
3301  if (mi != mapRelay.end()) {
3302  return mi->second;
3303  }
3304  }
3305  }
3306 
3307  return {};
3308 }
3309 
3313 PeerManagerImpl::FindProofForGetData(const Peer &peer,
3314  const avalanche::ProofId &proofid,
3315  const std::chrono::seconds now) {
3316  avalanche::ProofRef proof;
3317 
3318  bool send_unconditionally =
3319  m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
3320  return pm.forPeer(proofid, [&](const avalanche::Peer &peer) {
3321  proof = peer.proof;
3322 
3323  // If we know that proof for long enough, allow for requesting
3324  // it.
3325  return peer.registration_time <=
3327  });
3328  });
3329 
3330  if (!proof) {
3331  // Always send our local proof if it gets requested, assuming it's
3332  // valid. This will make it easier to bind with peers upon startup where
3333  // the status of our proof is unknown pending for a block. Note that it
3334  // still needs to have been announced first (presumably via an avahello
3335  // message).
3336  proof = m_avalanche->getLocalProof();
3337  }
3338 
3339  // We don't have this proof
3340  if (!proof) {
3341  return avalanche::ProofRef();
3342  }
3343 
3344  if (send_unconditionally) {
3345  return proof;
3346  }
3347 
3348  // Otherwise, the proofs must have been announced recently.
3349  if (peer.m_proof_relay->m_recently_announced_proofs.contains(proofid)) {
3350  return proof;
3351  }
3352 
3353  return avalanche::ProofRef();
3354 }
3355 
3356 void PeerManagerImpl::ProcessGetData(
3357  const Config &config, CNode &pfrom, Peer &peer,
3358  const std::atomic<bool> &interruptMsgProc) {
3360 
3361  auto tx_relay = peer.GetTxRelay();
3362 
3363  std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
3364  std::vector<CInv> vNotFound;
3365  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3366 
3367  const auto now{GetTime<std::chrono::seconds>()};
3368  // Get last mempool request time
3369  const auto mempool_req = tx_relay != nullptr
3370  ? tx_relay->m_last_mempool_req.load()
3371  : std::chrono::seconds::min();
3372 
3373  // Process as many TX or AVA_PROOF items from the front of the getdata
3374  // queue as possible, since they're common and it's efficient to batch
3375  // process them.
3376  while (it != peer.m_getdata_requests.end()) {
3377  if (interruptMsgProc) {
3378  return;
3379  }
3380  // The send buffer provides backpressure. If there's no space in
3381  // the buffer, pause processing until the next call.
3382  if (pfrom.fPauseSend) {
3383  break;
3384  }
3385 
3386  const CInv &inv = *it;
3387 
3388  if (it->IsMsgProof()) {
3389  if (!m_avalanche) {
3390  vNotFound.push_back(inv);
3391  ++it;
3392  continue;
3393  }
3394  const avalanche::ProofId proofid(inv.hash);
3395  auto proof = FindProofForGetData(peer, proofid, now);
3396  if (proof) {
3397  m_connman.PushMessage(
3398  &pfrom, msgMaker.Make(NetMsgType::AVAPROOF, *proof));
3399  m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
3400  pm.removeUnbroadcastProof(proofid);
3401  });
3402  } else {
3403  vNotFound.push_back(inv);
3404  }
3405 
3406  ++it;
3407  continue;
3408  }
3409 
3410  if (it->IsMsgTx()) {
3411  if (tx_relay == nullptr) {
3412  // Ignore GETDATA requests for transactions from
3413  // block-relay-only peers and peers that asked us not to
3414  // announce transactions.
3415  continue;
3416  }
3417 
3418  const TxId txid(inv.hash);
3419  CTransactionRef tx = FindTxForGetData(peer, txid, mempool_req, now);
3420  if (tx) {
3421  int nSendFlags = 0;
3422  m_connman.PushMessage(
3423  &pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *tx));
3424  m_mempool.RemoveUnbroadcastTx(txid);
3425  // As we're going to send tx, make sure its unconfirmed parents
3426  // are made requestable.
3427  std::vector<TxId> parent_ids_to_add;
3428  {
3429  LOCK(m_mempool.cs);
3430  auto txiter = m_mempool.GetIter(tx->GetId());
3431  if (txiter) {
3432  auto &pentry = *txiter;
3433  const CTxMemPoolEntry::Parents &parents =
3434  (*pentry)->GetMemPoolParentsConst();
3435  parent_ids_to_add.reserve(parents.size());
3436  for (const auto &parent : parents) {
3437  if (parent.get()->GetTime() >
3438  now - UNCONDITIONAL_RELAY_DELAY) {
3439  parent_ids_to_add.push_back(
3440  parent.get()->GetTx().GetId());
3441  }
3442  }
3443  }
3444  }
3445  for (const TxId &parent_txid : parent_ids_to_add) {
3446  // Relaying a transaction with a recent but unconfirmed
3447  // parent.
3448  if (WITH_LOCK(tx_relay->m_tx_inventory_mutex,
3449  return !tx_relay->m_tx_inventory_known_filter
3450  .contains(parent_txid))) {
3451  tx_relay->m_recently_announced_invs.insert(parent_txid);
3452  }
3453  }
3454  } else {
3455  vNotFound.push_back(inv);
3456  }
3457 
3458  ++it;
3459  continue;
3460  }
3461 
3462  // It's neither a proof nor a transaction
3463  break;
3464  }
3465 
3466  // Only process one BLOCK item per call, since they're uncommon and can be
3467  // expensive to process.
3468  if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
3469  const CInv &inv = *it++;
3470  if (inv.IsGenBlkMsg()) {
3471  ProcessGetBlockData(config, pfrom, peer, inv);
3472  }
3473  // else: If the first item on the queue is an unknown type, we erase it
3474  // and continue processing the queue on the next call.
3475  }
3476 
3477  peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
3478 
3479  if (!vNotFound.empty()) {
3480  // Let the peer know that we didn't find what it asked for, so it
3481  // doesn't have to wait around forever. SPV clients care about this
3482  // message: it's needed when they are recursively walking the
3483  // dependencies of relevant unconfirmed transactions. SPV clients want
3484  // to do that because they want to know about (and store and rebroadcast
3485  // and risk analyze) the dependencies of transactions relevant to them,
3486  // without having to download the entire memory pool. Also, other nodes
3487  // can use these messages to automatically request a transaction from
3488  // some other peer that annnounced it, and stop waiting for us to
3489  // respond. In normal operation, we often send NOTFOUND messages for
3490  // parents of transactions that we relay; if a peer is missing a parent,
3491  // they may assume we have them and request the parents from us.
3492  m_connman.PushMessage(&pfrom,
3493  msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
3494  }
3495 }
3496 
3497 void PeerManagerImpl::SendBlockTransactions(
3498  CNode &pfrom, Peer &peer, const CBlock &block,
3499  const BlockTransactionsRequest &req) {
3500  BlockTransactions resp(req);
3501  for (size_t i = 0; i < req.indices.size(); i++) {
3502  if (req.indices[i] >= block.vtx.size()) {
3503  Misbehaving(peer, 100, "getblocktxn with out-of-bounds tx indices");
3504  return;
3505  }
3506  resp.txn[i] = block.vtx[req.indices[i]];
3507  }
3508  LOCK(cs_main);
3509  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3510  int nSendFlags = 0;
3511  m_connman.PushMessage(
3512  &pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
3513 }
3514 
3515 bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader> &headers,
3516  const Consensus::Params &consensusParams,
3517  Peer &peer) {
3518  // Do these headers have proof-of-work matching what's claimed?
3519  if (!HasValidProofOfWork(headers, consensusParams)) {
3520  Misbehaving(peer, 100, "header with invalid proof of work");
3521  return false;
3522  }
3523 
3524  // Are these headers connected to each other?
3525  if (!CheckHeadersAreContinuous(headers)) {
3526  Misbehaving(peer, 20, "non-continuous headers sequence");
3527  return false;
3528  }
3529  return true;
3530 }
3531 
3532 arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold() {
3533  arith_uint256 near_chaintip_work = 0;
3534  LOCK(cs_main);
3535  if (m_chainman.ActiveChain().Tip() != nullptr) {
3536  const CBlockIndex *tip = m_chainman.ActiveChain().Tip();
3537  // Use a 144 block buffer, so that we'll accept headers that fork from
3538  // near our tip.
3539  near_chaintip_work =
3540  tip->nChainWork -
3541  std::min<arith_uint256>(144 * GetBlockProof(*tip), tip->nChainWork);
3542  }
3543  return std::max(near_chaintip_work, m_chainman.MinimumChainWork());
3544 }
3545 
3558 void PeerManagerImpl::HandleFewUnconnectingHeaders(
3559  CNode &pfrom, Peer &peer, const std::vector<CBlockHeader> &headers) {
3560  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3561 
3562  peer.m_num_unconnecting_headers_msgs++;
3563  // Try to fill in the missing headers.
3564  const CBlockIndex *best_header{
3565  WITH_LOCK(cs_main, return m_chainman.m_best_header)};
3566  if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) {
3567  LogPrint(
3568  BCLog::NET,
3569  "received header %s: missing prev block %s, sending getheaders "
3570  "(%d) to end (peer=%d, m_num_unconnecting_headers_msgs=%d)\n",
3571  headers[0].GetHash().ToString(),
3572  headers[0].hashPrevBlock.ToString(), best_header->nHeight,
3573  pfrom.GetId(), peer.m_num_unconnecting_headers_msgs);
3574  }
3575 
3576  // Set hashLastUnknownBlock for this peer, so that if we
3577  // eventually get the headers - even from a different peer -
3578  // we can use this peer to download.
3580  UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash()));
3581 
3582  // The peer may just be broken, so periodically assign DoS points if this
3583  // condition persists.
3584  if (peer.m_num_unconnecting_headers_msgs %
3586  0) {
3587  Misbehaving(peer, 20,
3588  strprintf("%d non-connecting headers",
3589  peer.m_num_unconnecting_headers_msgs));
3590  }
3591 }
3592 
3593 bool PeerManagerImpl::CheckHeadersAreContinuous(
3594  const std::vector<CBlockHeader> &headers) const {
3595  BlockHash hashLastBlock;
3596  for (const CBlockHeader &header : headers) {
3597  if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
3598  return false;
3599  }
3600  hashLastBlock = header.GetHash();
3601  }
3602  return true;
3603 }
3604 
3605 bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(
3606  Peer &peer, CNode &pfrom, std::vector<CBlockHeader> &headers) {
3607  if (peer.m_headers_sync) {
3608  auto result = peer.m_headers_sync->ProcessNextHeaders(
3609  headers, headers.size() == MAX_HEADERS_RESULTS);
3610  if (result.request_more) {
3611  auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
3612  // If we were instructed to ask for a locator, it should not be
3613  // empty.
3614  Assume(!locator.vHave.empty());
3615  if (!locator.vHave.empty()) {
3616  // It should be impossible for the getheaders request to fail,
3617  // because we should have cleared the last getheaders timestamp
3618  // when processing the headers that triggered this call. But
3619  // it may be possible to bypass this via compactblock
3620  // processing, so check the result before logging just to be
3621  // safe.
3622  bool sent_getheaders =
3623  MaybeSendGetHeaders(pfrom, locator, peer);
3624  if (sent_getheaders) {
3626  "more getheaders (from %s) to peer=%d\n",
3627  locator.vHave.front().ToString(), pfrom.GetId());
3628  } else {
3630  "error sending next getheaders (from %s) to "
3631  "continue sync with peer=%d\n",
3632  locator.vHave.front().ToString(), pfrom.GetId());
3633  }
3634  }
3635  }
3636 
3637  if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) {
3638  peer.m_headers_sync.reset(nullptr);
3639 
3640  // Delete this peer's entry in m_headers_presync_stats.
3641  // If this is m_headers_presync_bestpeer, it will be replaced later
3642  // by the next peer that triggers the else{} branch below.
3643  LOCK(m_headers_presync_mutex);
3644  m_headers_presync_stats.erase(pfrom.GetId());
3645  } else {
3646  // Build statistics for this peer's sync.
3647  HeadersPresyncStats stats;
3648  stats.first = peer.m_headers_sync->GetPresyncWork();
3649  if (peer.m_headers_sync->GetState() ==
3651  stats.second = {peer.m_headers_sync->GetPresyncHeight(),
3652  peer.m_headers_sync->GetPresyncTime()};
3653  }
3654 
3655  // Update statistics in stats.
3656  LOCK(m_headers_presync_mutex);
3657  m_headers_presync_stats[pfrom.GetId()] = stats;
3658  auto best_it =
3659  m_headers_presync_stats.find(m_headers_presync_bestpeer);
3660  bool best_updated = false;
3661  if (best_it == m_headers_presync_stats.end()) {
3662  // If the cached best peer is outdated, iterate over all
3663  // remaining ones (including newly updated one) to find the best
3664  // one.
3665  NodeId peer_best{-1};
3666  const HeadersPresyncStats *stat_best{nullptr};
3667  for (const auto &[_peer, _stat] : m_headers_presync_stats) {
3668  if (!stat_best || _stat > *stat_best) {
3669  peer_best = _peer;
3670  stat_best = &_stat;
3671  }
3672  }
3673  m_headers_presync_bestpeer = peer_best;
3674  best_updated = (peer_best == pfrom.GetId());
3675  } else if (best_it->first == pfrom.GetId() ||
3676  stats > best_it->second) {
3677  // pfrom was and remains the best peer, or pfrom just became
3678  // best.
3679  m_headers_presync_bestpeer = pfrom.GetId();
3680  best_updated = true;
3681  }
3682  if (best_updated && stats.second.has_value()) {
3683  // If the best peer updated, and it is in its first phase,
3684  // signal.
3685  m_headers_presync_should_signal = true;
3686  }
3687  }
3688 
3689  if (result.success) {
3690  // We only overwrite the headers passed in if processing was
3691  // successful.
3692  headers.swap(result.pow_validated_headers);
3693  }
3694 
3695  return result.success;
3696  }
3697  // Either we didn't have a sync in progress, or something went wrong
3698  // processing these headers, or we are returning headers to the caller to
3699  // process.
3700  return false;
3701 }
3702 
3703 bool PeerManagerImpl::TryLowWorkHeadersSync(
3704  Peer &peer, CNode &pfrom, const CBlockIndex *chain_start_header,
3705  std::vector<CBlockHeader> &headers) {
3706  // Calculate the total work on this chain.
3707  arith_uint256 total_work =
3708  chain_start_header->nChainWork + CalculateHeadersWork(headers);
3709 
3710  // Our dynamic anti-DoS threshold (minimum work required on a headers chain
3711  // before we'll store it)
3712  arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
3713 
3714  // Avoid DoS via low-difficulty-headers by only processing if the headers
3715  // are part of a chain with sufficient work.
3716  if (total_work < minimum_chain_work) {
3717  // Only try to sync with this peer if their headers message was full;
3718  // otherwise they don't have more headers after this so no point in
3719  // trying to sync their too-little-work chain.
3720  if (headers.size() == MAX_HEADERS_RESULTS) {
3721  // Note: we could advance to the last header in this set that is
3722  // known to us, rather than starting at the first header (which we
3723  // may already have); however this is unlikely to matter much since
3724  // ProcessHeadersMessage() already handles the case where all
3725  // headers in a received message are already known and are
3726  // ancestors of m_best_header or chainActive.Tip(), by skipping
3727  // this logic in that case. So even if the first header in this set
3728  // of headers is known, some header in this set must be new, so
3729  // advancing to the first unknown header would be a small effect.
3730  LOCK(peer.m_headers_sync_mutex);
3731  peer.m_headers_sync.reset(
3732  new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(),
3733  chain_start_header, minimum_chain_work));
3734 
3735  // Now a HeadersSyncState object for tracking this synchronization
3736  // is created, process the headers using it as normal.
3737  return IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3738  }
3739 
3741  "Ignoring low-work chain (height=%u) from peer=%d\n",
3742  chain_start_header->nHeight + headers.size(), pfrom.GetId());
3743  // Since this is a low-work headers chain, no further processing is
3744  // required.
3745  headers = {};
3746  return true;
3747  }
3748  return false;
3749 }
3750 
3751 bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex *header) {
3752  return header != nullptr &&
3753  ((m_chainman.m_best_header != nullptr &&
3754  header ==
3755  m_chainman.m_best_header->GetAncestor(header->nHeight)) ||
3756  m_chainman.ActiveChain().Contains(header));
3757 }
3758 
3759 bool PeerManagerImpl::MaybeSendGetHeaders(CNode &pfrom,
3760  const CBlockLocator &locator,
3761  Peer &peer) {
3762  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3763 
3764  const auto current_time = NodeClock::now();
3765 
3766  // Only allow a new getheaders message to go out if we don't have a recent
3767  // one already in-flight
3768  if (current_time - peer.m_last_getheaders_timestamp >
3770  m_connman.PushMessage(
3771  &pfrom, msgMaker.Make(NetMsgType::GETHEADERS, locator, uint256()));
3772  peer.m_last_getheaders_timestamp = current_time;
3773  return true;
3774  }
3775  return false;
3776 }
3777 
3784 void PeerManagerImpl::HeadersDirectFetchBlocks(const Config &config,
3785  CNode &pfrom,
3786  const CBlockIndex *pindexLast) {
3787  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3788 
3789  LOCK(cs_main);
3790  CNodeState *nodestate = State(pfrom.GetId());
3791 
3792  if (CanDirectFetch() && pindexLast->IsValid(BlockValidity::TREE) &&
3793  m_chainman.ActiveChain().Tip()->nChainWork <= pindexLast->nChainWork) {
3794  std::vector<const CBlockIndex *> vToFetch;
3795  const CBlockIndex *pindexWalk = pindexLast;
3796  // Calculate all the blocks we'd need to switch to pindexLast, up to
3797  // a limit.
3798  while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) &&
3799  vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3800  if (!pindexWalk->nStatus.hasData() &&
3801  !IsBlockRequested(pindexWalk->GetBlockHash())) {
3802  // We don't have this block, and it's not yet in flight.
3803  vToFetch.push_back(pindexWalk);
3804  }
3805  pindexWalk = pindexWalk->pprev;
3806  }
3807  // If pindexWalk still isn't on our main chain, we're looking at a
3808  // very large reorg at a time we think we're close to caught up to
3809  // the main chain -- this shouldn't really happen. Bail out on the
3810  // direct fetch and rely on parallel download instead.
3811  if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
3812  LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
3813  pindexLast->GetBlockHash().ToString(),
3814  pindexLast->nHeight);
3815  } else {
3816  std::vector<CInv> vGetData;
3817  // Download as much as possible, from earliest to latest.
3818  for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
3819  if (nodestate->nBlocksInFlight >=
3821  // Can't download any more from this peer
3822  break;
3823  }
3824  vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3825  BlockRequested(config, pfrom.GetId(), *pindex);
3826  LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
3827  pindex->GetBlockHash().ToString(), pfrom.GetId());
3828  }
3829  if (vGetData.size() > 1) {
3831  "Downloading blocks toward %s (%d) via headers "
3832  "direct fetch\n",
3833  pindexLast->GetBlockHash().ToString(),
3834  pindexLast->nHeight);
3835  }
3836  if (vGetData.size() > 0) {
3837  if (!m_opts.ignore_incoming_txs &&
3838  nodestate->m_provides_cmpctblocks && vGetData.size() == 1 &&
3839  mapBlocksInFlight.size() == 1 &&
3840  pindexLast->pprev->IsValid(BlockValidity::CHAIN)) {
3841  // In any case, we want to download using a compact
3842  // block, not a regular one.
3843  vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
3844  }
3845  m_connman.PushMessage(
3846  &pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3847  }
3848  }
3849  }
3850 }
3851 
3857 void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(
3858  CNode &pfrom, Peer &peer, const CBlockIndex *pindexLast,
3859  bool received_new_header, bool may_have_more_headers) {
3860  if (peer.m_num_unconnecting_headers_msgs > 0) {
3861  LogPrint(
3862  BCLog::NET,
3863  "peer=%d: resetting m_num_unconnecting_headers_msgs (%d -> 0)\n",
3864  pfrom.GetId(), peer.m_num_unconnecting_headers_msgs);
3865  }
3866  peer.m_num_unconnecting_headers_msgs = 0;
3867 
3868  LOCK(cs_main);
3869 
3870  CNodeState *nodestate = State(pfrom.GetId());
3871 
3872  assert(pindexLast);
3873  UpdateBlockAvailability(pfrom.GetId(), pindexLast->GetBlockHash());
3874 
3875  // From here, pindexBestKnownBlock should be guaranteed to be non-null,
3876  // because it is set in UpdateBlockAvailability. Some nullptr checks are
3877  // still present, however, as belt-and-suspenders.
3878 
3879  if (received_new_header &&
3880  pindexLast->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
3881  nodestate->m_last_block_announcement = GetTime();
3882  }
3883 
3884  // If we're in IBD, we want outbound peers that will serve us a useful
3885  // chain. Disconnect peers that are on chains with insufficient work.
3886  if (m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
3887  !may_have_more_headers) {
3888  // When nCount < MAX_HEADERS_RESULTS, we know we have no more
3889  // headers to fetch from this peer.
3890  if (nodestate->pindexBestKnownBlock &&
3891  nodestate->pindexBestKnownBlock->nChainWork <
3892  m_chainman.MinimumChainWork()) {
3893  // This peer has too little work on their headers chain to help
3894  // us sync -- disconnect if it is an outbound disconnection
3895  // candidate.
3896  // Note: We compare their tip to the minimum chain work (rather than
3897  // m_chainman.ActiveChain().Tip()) because we won't start block
3898  // download until we have a headers chain that has at least
3899  // the minimum chain work, even if a peer has a chain past our tip,
3900  // as an anti-DoS measure.
3901  if (pfrom.IsOutboundOrBlockRelayConn()) {
3902  LogPrintf("Disconnecting outbound peer %d -- headers "
3903  "chain has insufficient work\n",
3904  pfrom.GetId());
3905  pfrom.fDisconnect = true;
3906  }
3907  }
3908  }
3909 
3910  // If this is an outbound full-relay peer, check to see if we should
3911  // protect it from the bad/lagging chain logic.
3912  // Note that outbound block-relay peers are excluded from this
3913  // protection, and thus always subject to eviction under the bad/lagging
3914  // chain logic.
3915  // See ChainSyncTimeoutState.
3916  if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() &&
3917  nodestate->pindexBestKnownBlock != nullptr) {
3918  if (m_outbound_peers_with_protect_from_disconnect <
3920  nodestate->pindexBestKnownBlock->nChainWork >=
3921  m_chainman.ActiveChain().Tip()->nChainWork &&
3922  !nodestate->m_chain_sync.m_protect) {
3923  LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n",
3924  pfrom.GetId());
3925  nodestate->m_chain_sync.m_protect = true;
3926  ++m_outbound_peers_with_protect_from_disconnect;
3927  }
3928  }
3929 }
3930 
3931 void PeerManagerImpl::ProcessHeadersMessage(const Config &config, CNode &pfrom,
3932  Peer &peer,
3933  std::vector<CBlockHeader> &&headers,
3934  bool via_compact_block) {
3935  size_t nCount = headers.size();
3936 
3937  if (nCount == 0) {
3938  // Nothing interesting. Stop asking this peers for more headers.
3939  // If we were in the middle of headers sync, receiving an empty headers
3940  // message suggests that the peer suddenly has nothing to give us
3941  // (perhaps it reorged to our chain). Clear download state for this
3942  // peer.
3943  LOCK(peer.m_headers_sync_mutex);
3944  if (peer.m_headers_sync) {
3945  peer.m_headers_sync.reset(nullptr);
3946  LOCK(m_headers_presync_mutex);
3947  m_headers_presync_stats.erase(pfrom.GetId());
3948  }
3949  return;
3950  }
3951 
3952  // Before we do any processing, make sure these pass basic sanity checks.
3953  // We'll rely on headers having valid proof-of-work further down, as an
3954  // anti-DoS criteria (note: this check is required before passing any
3955  // headers into HeadersSyncState).
3956  if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) {
3957  // Misbehaving() calls are handled within CheckHeadersPoW(), so we can
3958  // just return. (Note that even if a header is announced via compact
3959  // block, the header itself should be valid, so this type of error can
3960  // always be punished.)
3961  return;
3962  }
3963 
3964  const CBlockIndex *pindexLast = nullptr;
3965 
3966  // We'll set already_validated_work to true if these headers are
3967  // successfully processed as part of a low-work headers sync in progress
3968  // (either in PRESYNC or REDOWNLOAD phase).
3969  // If true, this will mean that any headers returned to us (ie during
3970  // REDOWNLOAD) can be validated without further anti-DoS checks.
3971  bool already_validated_work = false;
3972 
3973  // If we're in the middle of headers sync, let it do its magic.
3974  bool have_headers_sync = false;
3975  {
3976  LOCK(peer.m_headers_sync_mutex);
3977 
3978  already_validated_work =
3979  IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3980 
3981  // The headers we passed in may have been:
3982  // - untouched, perhaps if no headers-sync was in progress, or some
3983  // failure occurred
3984  // - erased, such as if the headers were successfully processed and no
3985  // additional headers processing needs to take place (such as if we
3986  // are still in PRESYNC)
3987  // - replaced with headers that are now ready for validation, such as
3988  // during the REDOWNLOAD phase of a low-work headers sync.
3989  // So just check whether we still have headers that we need to process,
3990  // or not.
3991  if (headers.empty()) {
3992  return;
3993  }
3994 
3995  have_headers_sync = !!peer.m_headers_sync;
3996  }
3997 
3998  // Do these headers connect to something in our block index?
3999  const CBlockIndex *chain_start_header{
4000  WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(
4001  headers[0].hashPrevBlock))};
4002  bool headers_connect_blockindex{chain_start_header != nullptr};
4003 
4004  if (!headers_connect_blockindex) {
4005  if (nCount <= MAX_BLOCKS_TO_ANNOUNCE) {
4006  // If this looks like it could be a BIP 130 block announcement, use
4007  // special logic for handling headers that don't connect, as this
4008  // could be benign.
4009  HandleFewUnconnectingHeaders(pfrom, peer, headers);
4010  } else {
4011  Misbehaving(peer, 10, "invalid header received");
4012  }
4013  return;
4014  }
4015 
4016  // If the headers we received are already in memory and an ancestor of
4017  // m_best_header or our tip, skip anti-DoS checks. These headers will not
4018  // use any more memory (and we are not leaking information that could be
4019  // used to fingerprint us).
4020  const CBlockIndex *last_received_header{nullptr};
4021  {
4022  LOCK(cs_main);
4023  last_received_header =
4024  m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash());
4025  if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
4026  already_validated_work = true;
4027  }
4028  }
4029 
4030  // If our peer has NetPermissionFlags::NoBan privileges, then bypass our
4031  // anti-DoS logic (this saves bandwidth when we connect to a trusted peer
4032  // on startup).
4034  already_validated_work = true;
4035  }
4036 
4037  // At this point, the headers connect to something in our block index.
4038  // Do anti-DoS checks to determine if we should process or store for later
4039  // processing.
4040  if (!already_validated_work &&
4041  TryLowWorkHeadersSync(peer, pfrom, chain_start_header, headers)) {
4042  // If we successfully started a low-work headers sync, then there
4043  // should be no headers to process any further.
4044  Assume(headers.empty());
4045  return;
4046  }
4047 
4048  // At this point, we have a set of headers with sufficient work on them
4049  // which can be processed.
4050 
4051  // If we don't have the last header, then this peer will have given us
4052  // something new (if these headers are valid).
4053  bool received_new_header{last_received_header == nullptr};
4054 
4055  // Now process all the headers.
4056  BlockValidationState state;
4057  if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true,
4058  state, &pindexLast)) {
4059  if (state.IsInvalid()) {
4060  MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block,
4061  "invalid header received");
4062  return;
4063  }
4064  }
4065  Assume(pindexLast);
4066 
4067  // Consider fetching more headers if we are not using our headers-sync
4068  // mechanism.
4069  if (nCount == MAX_HEADERS_RESULTS && !have_headers_sync) {
4070  // Headers message had its maximum size; the peer may have more headers.
4071  if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) {
4072  LogPrint(
4073  BCLog::NET,
4074  "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
4075  pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
4076  }
4077  }
4078 
4079  UpdatePeerStateForReceivedHeaders(pfrom, peer, pindexLast,
4080  received_new_header,
4081  nCount == MAX_HEADERS_RESULTS);
4082 
4083  // Consider immediately downloading blocks.
4084  HeadersDirectFetchBlocks(config, pfrom, pindexLast);
4085 }
4086 
4087 void PeerManagerImpl::ProcessInvalidTx(NodeId nodeid,
4088  const CTransactionRef &ptx,
4089  const TxValidationState &state,
4090  bool maybe_add_extra_compact_tx) {
4091  AssertLockNotHeld(m_peer_mutex);
4092  AssertLockHeld(g_msgproc_mutex);
4094 
4095  LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n",
4096  ptx->GetHash().ToString(), nodeid, state.ToString());
4097 
4099  return;
4100  }
4101 
4103  // If the result is TX_RECONSIDERABLE, add it to
4104  // m_recent_rejects_reconsiderable because we should not download or
4105  // submit this transaction by itself again, but may submit it as part
4106  // of a package later.
4107  m_recent_rejects_reconsiderable.insert(ptx->GetId());
4108  } else {
4109  m_recent_rejects.insert(ptx->GetId());
4110  }
4111  m_txrequest.ForgetInvId(ptx->GetId());
4112 
4113  if (maybe_add_extra_compact_tx && RecursiveDynamicUsage(*ptx) < 100000) {
4114  AddToCompactExtraTransactions(ptx);
4115  }
4116 
4117  MaybePunishNodeForTx(nodeid, state);
4118 
4119  // If the tx failed in ProcessOrphanTx, it should be removed from the
4120  // orphanage unless the tx was still missing inputs. If the tx was not in
4121  // the orphanage, EraseTx does nothing and returns 0.
4122  if (m_orphanage.EraseTx(ptx->GetId()) > 0) {
4123  LogPrint(BCLog::TXPACKAGES, " removed orphan tx %s\n",
4124  ptx->GetHash().ToString());
4125  }
4126 }
4127 
4128 void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef &tx) {
4129  AssertLockNotHeld(m_peer_mutex);
4130  AssertLockHeld(g_msgproc_mutex);
4132 
4133  // As this version of the transaction was acceptable, we can forget about
4134  // any requests for it. No-op if the tx is not in txrequest.
4135  m_txrequest.ForgetInvId(tx->GetId());
4136 
4137  m_orphanage.AddChildrenToWorkSet(*tx);
4138  // If it came from the orphanage, remove it. No-op if the tx is not in
4139  // txorphanage.
4140  m_orphanage.EraseTx(tx->GetId());
4141 
4142  LogPrint(
4144  "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4145  nodeid, tx->GetHash().ToString(), m_mempool.size(),
4146  m_mempool.DynamicMemoryUsage() / 1000);
4147 
4148  RelayTransaction(tx->GetId());
4149 }
4150 
4151 void PeerManagerImpl::ProcessPackageResult(
4152  const PackageToValidate &package_to_validate,
4153  const PackageMempoolAcceptResult &package_result) {
4154  AssertLockNotHeld(m_peer_mutex);
4155  AssertLockHeld(g_msgproc_mutex);
4157 
4158  const auto &package = package_to_validate.m_txns;
4159  const auto &senders = package_to_validate.m_senders;
4160 
4161  if (package_result.m_state.IsInvalid()) {
4162  m_recent_rejects_reconsiderable.insert(GetPackageHash(package));
4163  }
4164  // We currently only expect to process 1-parent-1-child packages. Remove if
4165  // this changes.
4166  if (!Assume(package.size() == 2)) {
4167  return;
4168  }
4169 
4170  // Iterate backwards to erase in-package descendants from the orphanage
4171  // before they become relevant in AddChildrenToWorkSet.
4172  auto package_iter = package.rbegin();
4173  auto senders_iter = senders.rbegin();
4174  while (package_iter != package.rend()) {
4175  const auto &tx = *package_iter;
4176  const NodeId nodeid = *senders_iter;
4177  const auto it_result{package_result.m_tx_results.find(tx->GetId())};
4178 
4179  // It is not guaranteed that a result exists for every transaction.
4180  if (it_result != package_result.m_tx_results.end()) {
4181  const auto &tx_result = it_result->second;
4182  switch (tx_result.m_result_type) {
4184  ProcessValidTx(nodeid, tx);
4185  break;
4186  }
4188  // Don't add to vExtraTxnForCompact, as these transactions
4189  // should have already been added there when added to the
4190  // orphanage or rejected for TX_RECONSIDERABLE.
4191  // This should be updated if package submission is ever used
4192  // for transactions that haven't already been validated
4193  // before.
4194  ProcessInvalidTx(nodeid, tx, tx_result.m_state,
4195  /*maybe_add_extra_compact_tx=*/false);
4196  break;
4197  }
4199  // AlreadyHaveTx() should be catching transactions that are
4200  // already in mempool.
4201  Assume(false);
4202  break;
4203  }
4204  }
4205  }
4206  package_iter++;
4207  senders_iter++;
4208  }
4209 }
4210 
4211 std::optional<PeerManagerImpl::PackageToValidate>
4212 PeerManagerImpl::Find1P1CPackage(const CTransactionRef &ptx, NodeId nodeid) {
4213  AssertLockNotHeld(m_peer_mutex);
4214  AssertLockHeld(g_msgproc_mutex);
4216 
4217  const auto &parent_txid{ptx->GetId()};
4218 
4219  Assume(m_recent_rejects_reconsiderable.contains(parent_txid));
4220 
4221  // Prefer children from this peer. This helps prevent censorship attempts in
4222  // which an attacker sends lots of fake children for the parent, and we
4223  // (unluckily) keep selecting the fake children instead of the real one
4224  // provided by the honest peer.
4225  const auto cpfp_candidates_same_peer{
4226  m_orphanage.GetChildrenFromSamePeer(ptx, nodeid)};
4227 
4228  // These children should be sorted from newest to oldest.
4229  for (const auto &child : cpfp_candidates_same_peer) {
4230  Package maybe_cpfp_package{ptx, child};
4231  if (!m_recent_rejects_reconsiderable.contains(
4232  GetPackageHash(maybe_cpfp_package))) {
4233  return PeerManagerImpl::PackageToValidate{ptx, child, nodeid,
4234  nodeid};
4235  }
4236  }
4237 
4238  // If no suitable candidate from the same peer is found, also try children
4239  // that were provided by a different peer. This is useful because sometimes
4240  // multiple peers announce both transactions to us, and we happen to
4241  // download them from different peers (we wouldn't have known that these 2
4242  // transactions are related). We still want to find 1p1c packages then.
4243  //
4244  // If we start tracking all announcers of orphans, we can restrict this
4245  // logic to parent + child pairs in which both were provided by the same
4246  // peer, i.e. delete this step.
4247  const auto cpfp_candidates_different_peer{
4248  m_orphanage.GetChildrenFromDifferentPeer(ptx, nodeid)};
4249 
4250  // Find the first 1p1c that hasn't already been rejected. We randomize the
4251  // order to not create a bias that attackers can use to delay package
4252  // acceptance.
4253  //
4254  // Create a random permutation of the indices.
4255  std::vector<size_t> tx_indices(cpfp_candidates_different_peer.size());
4256  std::iota(tx_indices.begin(), tx_indices.end(), 0);
4257  Shuffle(tx_indices.begin(), tx_indices.end(), m_rng);
4258 
4259  for (const auto index : tx_indices) {
4260  // If we already tried a package and failed for any reason, the combined
4261  // hash was cached in m_recent_rejects_reconsiderable.
4262  const auto [child_tx, child_sender] =
4263  cpfp_candidates_different_peer.at(index);
4264  Package maybe_cpfp_package{ptx, child_tx};
4265  if (!m_recent_rejects_reconsiderable.contains(
4266  GetPackageHash(maybe_cpfp_package))) {
4267  return PeerManagerImpl::PackageToValidate{ptx, child_tx, nodeid,
4268  child_sender};
4269  }
4270  }
4271  return std::nullopt;
4272 }
4273 
4274 bool PeerManagerImpl::ProcessOrphanTx(const Config &config, Peer &peer) {
4275  AssertLockHeld(g_msgproc_mutex);
4276  LOCK(cs_main);
4277 
4278  while (CTransactionRef porphanTx =
4279  m_orphanage.GetTxToReconsider(peer.m_id)) {
4280  const MempoolAcceptResult result =
4281  m_chainman.ProcessTransaction(porphanTx);
4282  const TxValidationState &state = result.m_state;
4283  const TxId &orphanTxId = porphanTx->GetId();
4284 
4286  LogPrint(BCLog::TXPACKAGES, " accepted orphan tx %s\n",
4287  orphanTxId.ToString());
4288  ProcessValidTx(peer.m_id, porphanTx);
4289  return true;
4290  }
4291 
4294  " invalid orphan tx %s from peer=%d. %s\n",
4295  orphanTxId.ToString(), peer.m_id, state.ToString());
4296 
4297  if (Assume(state.IsInvalid() &&
4299  state.GetResult() !=
4301  ProcessInvalidTx(peer.m_id, porphanTx, state,
4302  /*maybe_add_extra_compact_tx=*/false);
4303  }
4304 
4305  return true;
4306  }
4307  }
4308 
4309  return false;
4310 }
4311 
4312 bool PeerManagerImpl::PrepareBlockFilterRequest(
4313  CNode &node, Peer &peer, BlockFilterType filter_type, uint32_t start_height,
4314  const BlockHash &stop_hash, uint32_t max_height_diff,
4315  const CBlockIndex *&stop_index, BlockFilterIndex *&filter_index) {
4316  const bool supported_filter_type =
4317  (filter_type == BlockFilterType::BASIC &&
4318  (peer.m_our_services & NODE_COMPACT_FILTERS));
4319  if (!supported_filter_type) {
4321  "peer %d requested unsupported block filter type: %d\n",
4322  node.GetId(), static_cast<uint8_t>(filter_type));
4323  node.fDisconnect = true;
4324  return false;
4325  }
4326 
4327  {
4328  LOCK(cs_main);
4329  stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
4330 
4331  // Check that the stop block exists and the peer would be allowed to
4332  // fetch it.
4333  if (!stop_index || !BlockRequestAllowed(stop_index)) {
4334  LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
4335  node.GetId(), stop_hash.ToString());
4336  node.fDisconnect = true;
4337  return false;
4338  }
4339  }
4340 
4341  uint32_t stop_height = stop_index->nHeight;
4342  if (start_height > stop_height) {
4343  LogPrint(
4344  BCLog::NET,
4345  "peer %d sent invalid getcfilters/getcfheaders with " /* Continued
4346  */
4347  "start height %d and stop height %d\n",
4348  node.GetId(), start_height, stop_height);
4349  node.fDisconnect = true;
4350  return false;
4351  }
4352  if (stop_height - start_height >= max_height_diff) {
4354  "peer %d requested too many cfilters/cfheaders: %d / %d\n",
4355  node.GetId(), stop_height - start_height + 1, max_height_diff);
4356  node.fDisconnect = true;
4357  return false;
4358  }
4359 
4360  filter_index = GetBlockFilterIndex(filter_type);
4361  if (!filter_index) {
4362  LogPrint(BCLog::NET, "Filter index for supported type %s not found\n",
4363  BlockFilterTypeName(filter_type));
4364  return false;
4365  }
4366 
4367  return true;
4368 }
4369 
4370 void PeerManagerImpl::ProcessGetCFilters(CNode &node, Peer &peer,
4371  CDataStream &vRecv) {
4372  uint8_t filter_type_ser;
4373  uint32_t start_height;
4374  BlockHash stop_hash;
4375 
4376  vRecv >> filter_type_ser >> start_height >> stop_hash;
4377 
4378  const BlockFilterType filter_type =
4379  static_cast<BlockFilterType>(filter_type_ser);
4380 
4381  const CBlockIndex *stop_index;
4382  BlockFilterIndex *filter_index;
4383  if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height,
4384  stop_hash, MAX_GETCFILTERS_SIZE, stop_index,
4385  filter_index)) {
4386  return;
4387  }
4388 
4389  std::vector<BlockFilter> filters;
4390  if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
4392  "Failed to find block filter in index: filter_type=%s, "
4393  "start_height=%d, stop_hash=%s\n",
4394  BlockFilterTypeName(filter_type), start_height,
4395  stop_hash.ToString());
4396  return;
4397  }
4398 
4399  for (const auto &filter : filters) {
4400  CSerializedNetMsg msg = CNetMsgMaker(node.GetCommonVersion())
4401  .Make(NetMsgType::CFILTER, filter);
4402  m_connman.PushMessage(&node, std::move(msg));
4403  }
4404 }
4405 
4406 void PeerManagerImpl::ProcessGetCFHeaders(CNode &node, Peer &peer,
4407  CDataStream &vRecv) {
4408  uint8_t filter_type_ser;
4409  uint32_t start_height;
4410  BlockHash stop_hash;
4411 
4412  vRecv >> filter_type_ser >> start_height >> stop_hash;
4413 
4414  const BlockFilterType filter_type =
4415  static_cast<BlockFilterType>(filter_type_ser);
4416 
4417  const CBlockIndex *stop_index;
4418  BlockFilterIndex *filter_index;
4419  if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height,
4420  stop_hash, MAX_GETCFHEADERS_SIZE, stop_index,
4421  filter_index)) {
4422  return;
4423  }
4424 
4425  uint256 prev_header;
4426  if (start_height > 0) {
4427  const CBlockIndex *const prev_block =
4428  stop_index->GetAncestor(static_cast<int>(start_height - 1));
4429  if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
4431  "Failed to find block filter header in index: "
4432  "filter_type=%s, block_hash=%s\n",
4433  BlockFilterTypeName(filter_type),
4434  prev_block->GetBlockHash().ToString());
4435  return;
4436  }
4437  }
4438 
4439  std::vector<uint256> filter_hashes;
4440  if (!filter_index->LookupFilterHashRange(start_height, stop_index,
4441  filter_hashes)) {
4443  "Failed to find block filter hashes in index: filter_type=%s, "
4444  "start_height=%d, stop_hash=%s\n",
4445  BlockFilterTypeName(filter_type), start_height,
4446  stop_hash.ToString());
4447  return;
4448  }
4449 
4450  CSerializedNetMsg msg =
4451  CNetMsgMaker(node.GetCommonVersion())
4452  .Make(NetMsgType::CFHEADERS, filter_type_ser,
4453  stop_index->GetBlockHash(), prev_header, filter_hashes);
4454  m_connman.PushMessage(&node, std::move(msg));
4455 }
4456 
4457 void PeerManagerImpl::ProcessGetCFCheckPt(CNode &node, Peer &peer,
4458  CDataStream &vRecv) {
4459  uint8_t filter_type_ser;
4460  BlockHash stop_hash;
4461 
4462  vRecv >> filter_type_ser >> stop_hash;
4463 
4464  const BlockFilterType filter_type =
4465  static_cast<BlockFilterType>(filter_type_ser);
4466 
4467  const CBlockIndex *stop_index;
4468  BlockFilterIndex *filter_index;
4469  if (!PrepareBlockFilterRequest(
4470  node, peer, filter_type, /*start_height=*/0, stop_hash,
4471  /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
4472  stop_index, filter_index)) {
4473  return;
4474  }
4475 
4476  std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
4477 
4478  // Populate headers.
4479  const CBlockIndex *block_index = stop_index;
4480  for (int i = headers.size() - 1; i >= 0; i--) {
4481  int height = (i + 1) * CFCHECKPT_INTERVAL;
4482  block_index = block_index->GetAncestor(height);
4483 
4484  if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
4486  "Failed to find block filter header in index: "
4487  "filter_type=%s, block_hash=%s\n",
4488  BlockFilterTypeName(filter_type),
4489  block_index->GetBlockHash().ToString());
4490  return;
4491  }
4492  }
4493 
4494  CSerializedNetMsg msg = CNetMsgMaker(node.GetCommonVersion())
4495  .Make(NetMsgType::CFCHECKPT, filter_type_ser,
4496  stop_index->GetBlockHash(), headers);
4497  m_connman.PushMessage(&node, std::move(msg));
4498 }
4499 
4500 bool IsAvalancheMessageType(const std::string &msg_type) {
4501  return msg_type == NetMsgType::AVAHELLO ||
4502  msg_type == NetMsgType::AVAPOLL ||
4503  msg_type == NetMsgType::AVARESPONSE ||
4504  msg_type == NetMsgType::AVAPROOF ||
4505  msg_type == NetMsgType::GETAVAADDR ||
4506  msg_type == NetMsgType::GETAVAPROOFS ||
4507  msg_type == NetMsgType::AVAPROOFS ||
4508  msg_type == NetMsgType::AVAPROOFSREQ;
4509 }
4510 
4511 uint32_t
4512 PeerManagerImpl::GetAvalancheVoteForBlock(const BlockHash &hash) const {
4514 
4515  const CBlockIndex *pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
4516 
4517  // Unknown block.
4518  if (!pindex) {
4519  return -1;
4520  }
4521 
4522  // Invalid block
4523  if (pindex->nStatus.isInvalid()) {
4524  return 1;
4525  }
4526 
4527  // Parked block
4528  if (pindex->nStatus.isOnParkedChain()) {
4529  return 2;
4530  }
4531 
4532  const CBlockIndex *pindexTip = m_chainman.ActiveChain().Tip();
4533  const CBlockIndex *pindexFork = LastCommonAncestor(pindex, pindexTip);
4534 
4535  // Active block.
4536  if (pindex == pindexFork) {
4537  return 0;
4538  }
4539 
4540  // Fork block.
4541  if (pindexFork != pindexTip) {
4542  return 3;
4543  }
4544 
4545  // Missing block data.
4546  if (!pindex->nStatus.hasData()) {
4547  return -2;
4548  }
4549 
4550  // This block is built on top of the tip, we have the data, it
4551  // is pending connection or rejection.
4552  return -3;
4553 };
4554 
4555 uint32_t PeerManagerImpl::GetAvalancheVoteForTx(const TxId &id) const {
4556  // Accepted in mempool, or in a recent block
4557  if (m_mempool.exists(id) ||
4558  WITH_LOCK(m_recent_confirmed_transactions_mutex,
4559  return m_recent_confirmed_transactions.contains(id))) {
4560  return 0;
4561  }
4562 
4563  // Invalid tx
4564  if (m_recent_rejects.contains(id)) {
4565  return 1;
4566  }
4567 
4568  // Orphan tx
4569  if (m_orphanage.HaveTx(id)) {
4570  return -2;
4571  }
4572 
4573  // Unknown tx
4574  return -1;
4575 };
4576 
4584  const avalanche::ProofId &id) {
4585  return avalanche.withPeerManager([&id](avalanche::PeerManager &pm) {
4586  // Rejected proof
4587  if (pm.isInvalid(id)) {
4588  return 1;
4589  }
4590 
4591  // The proof is actively bound to a peer
4592  if (pm.isBoundToPeer(id)) {
4593  return 0;
4594  }
4595 
4596  // Unknown proof
4597  if (!pm.exists(id)) {
4598  return -1;
4599  }
4600 
4601  // Immature proof
4602  if (pm.isImmature(id)) {
4603  return 2;
4604  }
4605 
4606  // Not immature, but in conflict with an actively bound proof
4607  if (pm.isInConflictingPool(id)) {
4608  return 3;
4609  }
4610 
4611  // The proof is known, not rejected, not immature, not a conflict, but
4612  // for some reason unbound. This should not happen if the above pools
4613  // are managed correctly, but added for robustness.
4614  return -2;
4615  });
4616 };
4617 
4618 void PeerManagerImpl::ProcessBlock(const Config &config, CNode &node,
4619  const std::shared_ptr<const CBlock> &block,
4620  bool force_processing,
4621  bool min_pow_checked) {
4622  bool new_block{false};
4623  m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked,
4624  &new_block, m_avalanche);
4625  if (new_block) {
4626  node.m_last_block_time = GetTime<std::chrono::seconds>();
4627  } else {
4628  LOCK(cs_main);
4629  mapBlockSource.erase(block->GetHash());
4630  }
4631 }
4632 
4633 void PeerManagerImpl::ProcessMessage(
4634  const Config &config, CNode &pfrom, const std::string &msg_type,
4635  CDataStream &vRecv, const std::chrono::microseconds time_received,
4636  const std::atomic<bool> &interruptMsgProc) {
4637  AssertLockHeld(g_msgproc_mutex);
4638 
4639  LogPrint(BCLog::NETDEBUG, "received: %s (%u bytes) peer=%d\n",
4640  SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
4641 
4642  PeerRef peer = GetPeerRef(pfrom.GetId());
4643  if (peer == nullptr) {
4644  return;
4645  }
4646 
4647  if (IsAvalancheMessageType(msg_type)) {
4648  if (!m_avalanche) {
4650  "Avalanche is not initialized, ignoring %s message\n",
4651  msg_type);
4652  return;
4653  }
4654 
4655  if (!m_avalanche) {
4656  // If avalanche is not enabled, ignore avalanche messages
4657  return;
4658  }
4659  }
4660 
4661  if (msg_type == NetMsgType::VERSION) {
4662  // Each connection can only send one version message
4663  if (pfrom.nVersion != 0) {
4664  Misbehaving(*peer, 1, "redundant version message");
4665  return;
4666  }
4667 
4668  int64_t nTime;
4669  CService addrMe;
4670  uint64_t nNonce = 1;
4671  ServiceFlags nServices;
4672  int nVersion;
4673  std::string cleanSubVer;
4674  int starting_height = -1;
4675  bool fRelay = true;
4676  uint64_t nExtraEntropy = 1;
4677 
4678  vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
4679  if (nTime < 0) {
4680  nTime = 0;
4681  }
4682  // Ignore the addrMe service bits sent by the peer
4683  vRecv.ignore(8);
4684  vRecv >> addrMe;
4685  if (!pfrom.IsInboundConn()) {
4686  m_addrman.SetServices(pfrom.addr, nServices);
4687  }
4688  if (pfrom.ExpectServicesFromConn() &&
4689  !HasAllDesirableServiceFlags(nServices)) {
4691  "peer=%d does not offer the expected services "
4692  "(%08x offered, %08x expected); disconnecting\n",
4693  pfrom.GetId(), nServices,
4694  GetDesirableServiceFlags(nServices));
4695  pfrom.fDisconnect = true;
4696  return;
4697  }
4698 
4699  if (pfrom.IsAvalancheOutboundConnection() &&
4700  !(nServices & NODE_AVALANCHE)) {
4701  LogPrint(
4703  "peer=%d does not offer the avalanche service; disconnecting\n",
4704  pfrom.GetId());
4705  pfrom.fDisconnect = true;
4706  return;
4707  }
4708 
4709  if (nVersion < MIN_PEER_PROTO_VERSION) {
4710  // disconnect from peers older than this proto version
4712  "peer=%d using obsolete version %i; disconnecting\n",
4713  pfrom.GetId(), nVersion);
4714  pfrom.fDisconnect = true;
4715  return;
4716  }
4717 
4718  if (!vRecv.empty()) {
4719  // The version message includes information about the sending node
4720  // which we don't use:
4721  // - 8 bytes (service bits)
4722  // - 16 bytes (ipv6 address)
4723  // - 2 bytes (port)
4724  vRecv.ignore(26);
4725  vRecv >> nNonce;
4726  }
4727  if (!vRecv.empty()) {
4728  std::string strSubVer;
4729  vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
4730  cleanSubVer = SanitizeString(strSubVer);
4731  }
4732  if (!vRecv.empty()) {
4733  vRecv >> starting_height;
4734  }
4735  if (!vRecv.empty()) {
4736  vRecv >> fRelay;
4737  }
4738  if (!vRecv.empty()) {
4739  vRecv >> nExtraEntropy;
4740  }
4741  // Disconnect if we connected to ourself
4742  if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce)) {
4743  LogPrintf("connected to self at %s, disconnecting\n",
4744  pfrom.addr.ToString());
4745  pfrom.fDisconnect = true;
4746  return;
4747  }
4748 
4749  if (pfrom.IsInboundConn() && addrMe.IsRoutable()) {
4750  SeenLocal(addrMe);
4751  }
4752 
4753  // Inbound peers send us their version message when they connect.
4754  // We send our version message in response.
4755  if (pfrom.IsInboundConn()) {
4756  PushNodeVersion(config, pfrom, *peer);
4757  }
4758 
4759  // Change version
4760  const int greatest_common_version =
4761  std::min(nVersion, PROTOCOL_VERSION);
4762  pfrom.SetCommonVersion(greatest_common_version);
4763  pfrom.nVersion = nVersion;
4764 
4765  const CNetMsgMaker msg_maker(greatest_common_version);
4766 
4767  m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::VERACK));
4768 
4769  // Signal ADDRv2 support (BIP155).
4770  m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::SENDADDRV2));
4771 
4773  HasAllDesirableServiceFlags(nServices);
4774  peer->m_their_services = nServices;
4775  pfrom.SetAddrLocal(addrMe);
4776  {
4777  LOCK(pfrom.m_subver_mutex);
4778  pfrom.cleanSubVer = cleanSubVer;
4779  }
4780  peer->m_starting_height = starting_height;
4781 
4782  // We only initialize the m_tx_relay data structure if:
4783  // - this isn't an outbound block-relay-only connection; and
4784  // - fRelay=true or we're offering NODE_BLOOM to this peer
4785  // (NODE_BLOOM means that the peer may turn on tx relay later)
4786  if (!pfrom.IsBlockOnlyConn() &&
4787  (fRelay || (peer->m_our_services & NODE_BLOOM))) {
4788  auto *const tx_relay = peer->SetTxRelay();
4789  {
4790  LOCK(tx_relay->m_bloom_filter_mutex);
4791  // set to true after we get the first filter* message
4792  tx_relay->m_relay_txs = fRelay;
4793  }
4794  if (fRelay) {
4795  pfrom.m_relays_txs = true;
4796  }
4797  }
4798 
4799  pfrom.nRemoteHostNonce = nNonce;
4800  pfrom.nRemoteExtraEntropy = nExtraEntropy;
4801 
4802  // Potentially mark this peer as a preferred download peer.
4803  {
4804  LOCK(cs_main);
4805  CNodeState *state = State(pfrom.GetId());
4806  state->fPreferredDownload =
4807  (!pfrom.IsInboundConn() ||
4809  !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer);
4810  m_num_preferred_download_peers += state->fPreferredDownload;
4811  }
4812 
4813  // Self advertisement & GETADDR logic
4814  if (!pfrom.IsInboundConn() && SetupAddressRelay(pfrom, *peer)) {
4815  // For outbound peers, we try to relay our address (so that other
4816  // nodes can try to find us more quickly, as we have no guarantee
4817  // that an outbound peer is even aware of how to reach us) and do a
4818  // one-time address fetch (to help populate/update our addrman). If
4819  // we're starting up for the first time, our addrman may be pretty
4820  // empty and no one will know who we are, so these mechanisms are
4821  // important to help us connect to the network.
4822  //
4823  // We skip this for block-relay-only peers. We want to avoid
4824  // potentially leaking addr information and we do not want to
4825  // indicate to the peer that we will participate in addr relay.
4826  if (fListen &&
4827  !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
4828  CAddress addr{GetLocalAddress(pfrom.addr), peer->m_our_services,
4829  AdjustedTime()};
4830  if (addr.IsRoutable()) {
4832  "ProcessMessages: advertising address %s\n",
4833  addr.ToString());
4834  PushAddress(*peer, addr);
4835  } else if (IsPeerAddrLocalGood(&pfrom)) {
4836  // Override just the address with whatever the peer sees us
4837  // as. Leave the port in addr as it was returned by
4838  // GetLocalAddress() above, as this is an outbound
4839  // connection and the peer cannot observe our listening
4840  // port.
4841  addr.SetIP(addrMe);
4843  "ProcessMessages: advertising address %s\n",
4844  addr.ToString());
4845  PushAddress(*peer, addr);
4846  }
4847  }
4848 
4849  // Get recent addresses
4850  m_connman.PushMessage(&pfrom, CNetMsgMaker(greatest_common_version)
4851  .Make(NetMsgType::GETADDR));
4852  peer->m_getaddr_sent = true;
4853  // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND
4854  // addresses in response (bypassing the
4855  // MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
4856  WITH_LOCK(peer->m_addr_token_bucket_mutex,
4857  peer->m_addr_token_bucket += m_opts.max_addr_to_send);
4858  }
4859 
4860  if (!pfrom.IsInboundConn()) {
4861  // For non-inbound connections, we update the addrman to record
4862  // connection success so that addrman will have an up-to-date
4863  // notion of which peers are online and available.
4864  //
4865  // While we strive to not leak information about block-relay-only
4866  // connections via the addrman, not moving an address to the tried
4867  // table is also potentially detrimental because new-table entries
4868  // are subject to eviction in the event of addrman collisions. We
4869  // mitigate the information-leak by never calling
4870  // AddrMan::Connected() on block-relay-only peers; see
4871  // FinalizeNode().
4872  //
4873  // This moves an address from New to Tried table in Addrman,
4874  // resolves tried-table collisions, etc.
4875  m_addrman.Good(pfrom.addr);
4876  }
4877 
4878  std::string remoteAddr;
4879  if (fLogIPs) {
4880  remoteAddr = ", peeraddr=" + pfrom.addr.ToString();
4881  }
4882 
4884  "receive version message: [%s] %s: version %d, blocks=%d, "
4885  "us=%s, txrelay=%d, peer=%d%s\n",
4886  pfrom.addr.ToString(), cleanSubVer, pfrom.nVersion,
4887  peer->m_starting_height, addrMe.ToString(), fRelay,
4888  pfrom.GetId(), remoteAddr);
4889 
4890  int64_t currentTime = GetTime();
4891  int64_t nTimeOffset = nTime - currentTime;
4892  pfrom.nTimeOffset = nTimeOffset;
4893  if (nTime < int64_t(m_chainparams.GenesisBlock().nTime)) {
4894  // Ignore time offsets that are improbable (before the Genesis
4895  // block) and may underflow our adjusted time.
4896  Misbehaving(*peer, 20,
4897  "Ignoring invalid timestamp in version message");
4898  } else if (!pfrom.IsInboundConn()) {
4899  // Don't use timedata samples from inbound peers to make it
4900  // harder for others to tamper with our adjusted time.
4901  AddTimeData(pfrom.addr, nTimeOffset);
4902  }
4903 
4904  // Feeler connections exist only to verify if address is online.
4905  if (pfrom.IsFeelerConn()) {
4907  "feeler connection completed peer=%d; disconnecting\n",
4908  pfrom.GetId());
4909  pfrom.fDisconnect = true;
4910  }
4911  return;
4912  }
4913 
4914  if (pfrom.nVersion == 0) {
4915  // Must have a version message before anything else
4916  Misbehaving(*peer, 10, "non-version message before version handshake");
4917  return;
4918  }
4919 
4920  // At this point, the outgoing message serialization version can't change.
4921  const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
4922 
4923  if (msg_type == NetMsgType::VERACK) {
4924  if (pfrom.fSuccessfullyConnected) {
4926  "ignoring redundant verack message from peer=%d\n",
4927  pfrom.GetId());
4928  return;
4929  }
4930 
4931  if (!pfrom.IsInboundConn()) {
4932  LogPrintf(
4933  "New outbound peer connected: version: %d, blocks=%d, "
4934  "peer=%d%s (%s)\n",
4935  pfrom.nVersion.load(), peer->m_starting_height, pfrom.GetId(),
4936  (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToString())
4937  : ""),
4938  pfrom.ConnectionTypeAsString());
4939  }
4940 
4941  if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) {
4942  // Tell our peer we are willing to provide version 1
4943  // cmpctblocks. However, we do not request new block announcements
4944  // using cmpctblock messages. We send this to non-NODE NETWORK peers
4945  // as well, because they may wish to request compact blocks from us.
4946  m_connman.PushMessage(
4947  &pfrom,
4948  msgMaker.Make(NetMsgType::SENDCMPCT, /*high_bandwidth=*/false,
4949  /*version=*/CMPCTBLOCKS_VERSION));
4950  }
4951 
4952  if (m_avalanche) {
4953  if (m_avalanche->sendHello(&pfrom)) {
4954  auto localProof = m_avalanche->getLocalProof();
4955 
4956  if (localProof) {
4957  AddKnownProof(*peer, localProof->getId());
4958  // Add our proof id to the list or the recently announced
4959  // proof INVs to this peer. This is used for filtering which
4960  // INV can be requested for download.
4961  peer->m_proof_relay->m_recently_announced_proofs.insert(
4962  localProof->getId());
4963  }
4964  }
4965  }
4966 
4967  pfrom.fSuccessfullyConnected = true;
4968  return;
4969  }
4970 
4971  if (!pfrom.fSuccessfullyConnected) {
4972  // Must have a verack message before anything else
4973  Misbehaving(*peer, 10, "non-verack message before version handshake");
4974  return;
4975  }
4976 
4977  if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
4978  int stream_version = vRecv.GetVersion();
4979  if (msg_type == NetMsgType::ADDRV2) {
4980  // Add ADDRV2_FORMAT to the version so that the CNetAddr and
4981  // CAddress unserialize methods know that an address in v2 format is
4982  // coming.
4983  stream_version |= ADDRV2_FORMAT;
4984  }
4985 
4986  OverrideStream<CDataStream> s(&vRecv, vRecv.GetType(), stream_version);
4987  std::vector<CAddress> vAddr;
4988 
4989  s >> vAddr;
4990 
4991  if (!SetupAddressRelay(pfrom, *peer)) {
4992  LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n",
4993  msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
4994  return;
4995  }
4996 
4997  if (vAddr.size() > m_opts.max_addr_to_send) {
4998  Misbehaving(
4999  *peer, 20,
5000  strprintf("%s message size = %u", msg_type, vAddr.size()));
5001  return;
5002  }
5003 
5004  // Store the new addresses
5005  std::vector<CAddress> vAddrOk;
5006  const auto current_a_time{AdjustedTime()};
5007 
5008  // Update/increment addr rate limiting bucket.
5009  const auto current_time = GetTime<std::chrono::microseconds>();
5010  {
5011  LOCK(peer->m_addr_token_bucket_mutex);
5012  if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
5013  // Don't increment bucket if it's already full
5014  const auto time_diff =
5015  std::max(current_time - peer->m_addr_token_timestamp, 0us);
5016  const double increment =
5018  peer->m_addr_token_bucket =
5019  std::min<double>(peer->m_addr_token_bucket + increment,
5021  }
5022  }
5023  peer->m_addr_token_timestamp = current_time;
5024 
5025  const bool rate_limited =
5027  uint64_t num_proc = 0;
5028  uint64_t num_rate_limit = 0;
5029  Shuffle(vAddr.begin(), vAddr.end(), m_rng);
5030  for (CAddress &addr : vAddr) {
5031  if (interruptMsgProc) {
5032  return;
5033  }
5034 
5035  {
5036  LOCK(peer->m_addr_token_bucket_mutex);
5037  // Apply rate limiting.
5038  if (peer->m_addr_token_bucket < 1.0) {
5039  if (rate_limited) {
5040  ++num_rate_limit;
5041  continue;
5042  }
5043  } else {
5044  peer->m_addr_token_bucket -= 1.0;
5045  }
5046  }
5047 
5048  // We only bother storing full nodes, though this may include things
5049  // which we would not make an outbound connection to, in part
5050  // because we may make feeler connections to them.
5051  if (!MayHaveUsefulAddressDB(addr.nServices) &&
5053  continue;
5054  }
5055 
5056  if (addr.nTime <= NodeSeconds{100000000s} ||
5057  addr.nTime > current_a_time + 10min) {
5058  addr.nTime = current_a_time - 5 * 24h;
5059  }
5060  AddAddressKnown(*peer, addr);
5061  if (m_banman &&
5062  (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
5063  // Do not process banned/discouraged addresses beyond
5064  // remembering we received them
5065  continue;
5066  }
5067  ++num_proc;
5068  bool fReachable = IsReachable(addr);
5069  if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent &&
5070  vAddr.size() <= 10 && addr.IsRoutable()) {
5071  // Relay to a limited number of other nodes
5072  RelayAddress(pfrom.GetId(), addr, fReachable);
5073  }
5074  // Do not store addresses outside our network
5075  if (fReachable) {
5076  vAddrOk.push_back(addr);
5077  }
5078  }
5079  peer->m_addr_processed += num_proc;
5080  peer->m_addr_rate_limited += num_rate_limit;
5082  "Received addr: %u addresses (%u processed, %u rate-limited) "
5083  "from peer=%d\n",
5084  vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
5085 
5086  m_addrman.Add(vAddrOk, pfrom.addr, 2h);
5087  if (vAddr.size() < 1000) {
5088  peer->m_getaddr_sent = false;
5089  }
5090 
5091  // AddrFetch: Require multiple addresses to avoid disconnecting on
5092  // self-announcements
5093  if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
5095  "addrfetch connection completed peer=%d; disconnecting\n",
5096  pfrom.GetId());
5097  pfrom.fDisconnect = true;
5098  }
5099  return;
5100  }
5101 
5102  if (msg_type == NetMsgType::SENDADDRV2) {
5103  peer->m_wants_addrv2 = true;
5104  return;
5105  }
5106 
5107  if (msg_type == NetMsgType::SENDHEADERS) {
5108  peer->m_prefers_headers = true;
5109  return;
5110  }
5111 
5112  if (msg_type == NetMsgType::SENDCMPCT) {
5113  bool sendcmpct_hb{false};
5114  uint64_t sendcmpct_version{0};
5115  vRecv >> sendcmpct_hb >> sendcmpct_version;
5116 
5117  if (sendcmpct_version != CMPCTBLOCKS_VERSION) {
5118  return;
5119  }
5120 
5121  LOCK(cs_main);
5122  CNodeState *nodestate = State(pfrom.GetId());
5123  nodestate->m_provides_cmpctblocks = true;
5124  nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
5125  // save whether peer selects us as BIP152 high-bandwidth peer
5126  // (receiving sendcmpct(1) signals high-bandwidth,
5127  // sendcmpct(0) low-bandwidth)
5128  pfrom.m_bip152_highbandwidth_from = sendcmpct_hb;
5129  return;
5130  }
5131 
5132  if (msg_type == NetMsgType::INV) {
5133  std::vector<CInv> vInv;
5134  vRecv >> vInv;
5135  if (vInv.size() > MAX_INV_SZ) {
5136  Misbehaving(*peer, 20,
5137  strprintf("inv message size = %u", vInv.size()));
5138  return;
5139  }
5140 
5141  // Reject tx INVs when the -blocksonly setting is enabled, or this is a
5142  // block-relay-only peer
5143  bool reject_tx_invs{m_opts.ignore_incoming_txs ||
5144  pfrom.IsBlockOnlyConn()};
5145 
5146  // Allow peers with relay permission to send data other than blocks
5147  // in blocks only mode
5149  reject_tx_invs = false;
5150  }
5151 
5152  const auto current_time{GetTime<std::chrono::microseconds>()};
5153  std::optional<BlockHash> best_block;
5154 
5155  auto logInv = [&](const CInv &inv, bool fAlreadyHave) {
5156  LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(),
5157  fAlreadyHave ? "have" : "new", pfrom.GetId());
5158  };
5159 
5160  for (CInv &inv : vInv) {
5161  if (interruptMsgProc) {
5162  return;
5163  }
5164 
5165  if (inv.IsMsgBlk()) {
5166  LOCK(cs_main);
5167  const bool fAlreadyHave = AlreadyHaveBlock(BlockHash(inv.hash));
5168  logInv(inv, fAlreadyHave);
5169 
5170  BlockHash hash{inv.hash};
5171  UpdateBlockAvailability(pfrom.GetId(), hash);
5172  if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() &&
5173  !IsBlockRequested(hash)) {
5174  // Headers-first is the primary method of announcement on
5175  // the network. If a node fell back to sending blocks by
5176  // inv, it may be for a re-org, or because we haven't
5177  // completed initial headers sync. The final block hash
5178  // provided should be the highest, so send a getheaders and
5179  // then fetch the blocks we need to catch up.
5180  best_block = std::move(hash);
5181  }
5182 
5183  continue;
5184  }
5185 
5186  if (inv.IsMsgProof()) {
5187  const avalanche::ProofId proofid(inv.hash);
5188  const bool fAlreadyHave = AlreadyHaveProof(proofid);
5189  logInv(inv, fAlreadyHave);
5190  AddKnownProof(*peer, proofid);
5191 
5192  if (!fAlreadyHave && m_avalanche &&
5193  !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
5194  const bool preferred = isPreferredDownloadPeer(pfrom);
5195 
5196  LOCK(cs_proofrequest);
5197  AddProofAnnouncement(pfrom, proofid, current_time,
5198  preferred);
5199  }
5200  continue;
5201  }
5202 
5203  if (inv.IsMsgTx()) {
5204  LOCK(cs_main);
5205  const TxId txid(inv.hash);
5206  const bool fAlreadyHave =
5207  AlreadyHaveTx(txid, /*include_reconsiderable=*/true);
5208  logInv(inv, fAlreadyHave);
5209 
5210  AddKnownTx(*peer, txid);
5211  if (reject_tx_invs) {
5213  "transaction (%s) inv sent in violation of "
5214  "protocol, disconnecting peer=%d\n",
5215  txid.ToString(), pfrom.GetId());
5216  pfrom.fDisconnect = true;
5217  return;
5218  } else if (!fAlreadyHave && !m_chainman.ActiveChainstate()
5219  .IsInitialBlockDownload()) {
5220  AddTxAnnouncement(pfrom, txid, current_time);
5221  }
5222 
5223  continue;
5224  }
5225 
5227  "Unknown inv type \"%s\" received from peer=%d\n",
5228  inv.ToString(), pfrom.GetId());
5229  }
5230 
5231  if (best_block) {
5232  // If we haven't started initial headers-sync with this peer, then
5233  // consider sending a getheaders now. On initial startup, there's a
5234  // reliability vs bandwidth tradeoff, where we are only trying to do
5235  // initial headers sync with one peer at a time, with a long
5236  // timeout (at which point, if the sync hasn't completed, we will
5237  // disconnect the peer and then choose another). In the meantime,
5238  // as new blocks are found, we are willing to add one new peer per
5239  // block to sync with as well, to sync quicker in the case where
5240  // our initial peer is unresponsive (but less bandwidth than we'd
5241  // use if we turned on sync with all peers).
5242  LOCK(::cs_main);
5243  CNodeState &state{*Assert(State(pfrom.GetId()))};
5244  if (state.fSyncStarted ||
5245  (!peer->m_inv_triggered_getheaders_before_sync &&
5246  *best_block != m_last_block_inv_triggering_headers_sync)) {
5247  if (MaybeSendGetHeaders(
5248  pfrom, GetLocator(m_chainman.m_best_header), *peer)) {
5249  LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n",
5250  m_chainman.m_best_header->nHeight,
5251  best_block->ToString(), pfrom.GetId());
5252  }
5253  if (!state.fSyncStarted) {
5254  peer->m_inv_triggered_getheaders_before_sync = true;
5255  // Update the last block hash that triggered a new headers
5256  // sync, so that we don't turn on headers sync with more
5257  // than 1 new peer every new block.
5258  m_last_block_inv_triggering_headers_sync = *best_block;
5259  }
5260  }
5261  }
5262 
5263  return;
5264  }
5265 
5266  if (msg_type == NetMsgType::GETDATA) {
5267  std::vector<CInv> vInv;
5268  vRecv >> vInv;
5269  if (vInv.size() > MAX_INV_SZ) {
5270  Misbehaving(*peer, 20,
5271  strprintf("getdata message size = %u", vInv.size()));
5272  return;
5273  }
5274 
5275  LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n",
5276  vInv.size(), pfrom.GetId());
5277 
5278  if (vInv.size() > 0) {
5279  LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n",
5280  vInv[0].ToString(), pfrom.GetId());
5281  }
5282 
5283  {
5284  LOCK(peer->m_getdata_requests_mutex);
5285  peer->m_getdata_requests.insert(peer->m_getdata_requests.end(),
5286  vInv.begin(), vInv.end());
5287  ProcessGetData(config, pfrom, *peer, interruptMsgProc);
5288  }
5289 
5290  return;
5291  }
5292 
5293  if (msg_type == NetMsgType::GETBLOCKS) {
5294  CBlockLocator locator;
5295  uint256 hashStop;
5296  vRecv >> locator >> hashStop;
5297 
5298  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
5300  "getblocks locator size %lld > %d, disconnect peer=%d\n",
5301  locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
5302  pfrom.fDisconnect = true;
5303  return;
5304  }
5305 
5306  // We might have announced the currently-being-connected tip using a
5307  // compact block, which resulted in the peer sending a getblocks
5308  // request, which we would otherwise respond to without the new block.
5309  // To avoid this situation we simply verify that we are on our best
5310  // known chain now. This is super overkill, but we handle it better
5311  // for getheaders requests, and there are no known nodes which support
5312  // compact blocks but still use getblocks to request blocks.
5313  {
5314  std::shared_ptr<const CBlock> a_recent_block;
5315  {
5316  LOCK(m_most_recent_block_mutex);
5317  a_recent_block = m_most_recent_block;
5318  }
5319  BlockValidationState state;
5320  if (!m_chainman.ActiveChainstate().ActivateBestChain(
5321  state, a_recent_block, m_avalanche)) {
5322  LogPrint(BCLog::NET, "failed to activate chain (%s)\n",
5323  state.ToString());
5324  }
5325  }
5326 
5327  LOCK(cs_main);
5328 
5329  // Find the last block the caller has in the main chain
5330  const CBlockIndex *pindex =
5331  m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
5332 
5333  // Send the rest of the chain
5334  if (pindex) {
5335  pindex = m_chainman.ActiveChain().Next(pindex);
5336  }
5337  int nLimit = 500;
5338  LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n",
5339  (pindex ? pindex->nHeight : -1),
5340  hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit,
5341  pfrom.GetId());
5342  for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) {
5343  if (pindex->GetBlockHash() == hashStop) {
5344  LogPrint(BCLog::NET, " getblocks stopping at %d %s\n",
5345  pindex->nHeight, pindex->GetBlockHash().ToString());
5346  break;
5347  }
5348  // If pruning, don't inv blocks unless we have on disk and are
5349  // likely to still have for some reasonable time window (1 hour)
5350  // that block relay might require.
5351  const int nPrunedBlocksLikelyToHave =
5353  3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
5354  if (m_chainman.m_blockman.IsPruneMode() &&
5355  (!pindex->nStatus.hasData() ||
5356  pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight -
5357  nPrunedBlocksLikelyToHave)) {
5358  LogPrint(
5359  BCLog::NET,
5360  " getblocks stopping, pruned or too old block at %d %s\n",
5361  pindex->nHeight, pindex->GetBlockHash().ToString());
5362  break;
5363  }
5364  WITH_LOCK(
5365  peer->m_block_inv_mutex,
5366  peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
5367  if (--nLimit <= 0) {
5368  // When this block is requested, we'll send an inv that'll
5369  // trigger the peer to getblocks the next batch of inventory.
5370  LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n",
5371  pindex->nHeight, pindex->GetBlockHash().ToString());
5372  WITH_LOCK(peer->m_block_inv_mutex, {
5373  peer->m_continuation_block = pindex->GetBlockHash();
5374  });
5375  break;
5376  }
5377  }
5378  return;
5379  }
5380 
5381  if (msg_type == NetMsgType::GETBLOCKTXN) {
5383  vRecv >> req;
5384 
5385  std::shared_ptr<const CBlock> recent_block;
5386  {
5387  LOCK(m_most_recent_block_mutex);
5388  if (m_most_recent_block_hash == req.blockhash) {
5389  recent_block = m_most_recent_block;
5390  }
5391  // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion
5392  }
5393  if (recent_block) {
5394  SendBlockTransactions(pfrom, *peer, *recent_block, req);
5395  return;
5396  }
5397 
5398  {
5399  LOCK(cs_main);
5400 
5401  const CBlockIndex *pindex =
5402  m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
5403  if (!pindex || !pindex->nStatus.hasData()) {
5404  LogPrint(
5405  BCLog::NET,
5406  "Peer %d sent us a getblocktxn for a block we don't have\n",
5407  pfrom.GetId());
5408  return;
5409  }
5410 
5411  if (pindex->nHeight >=
5412  m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
5413  CBlock block;
5414  const bool ret{
5415  m_chainman.m_blockman.ReadBlockFromDisk(block, *pindex)};
5416  assert(ret);
5417 
5418  SendBlockTransactions(pfrom, *peer, block, req);
5419  return;
5420  }
5421  }
5422 
5423  // If an older block is requested (should never happen in practice,
5424  // but can happen in tests) send a block response instead of a
5425  // blocktxn response. Sending a full block response instead of a
5426  // small blocktxn response is preferable in the case where a peer
5427  // might maliciously send lots of getblocktxn requests to trigger
5428  // expensive disk reads, because it will require the peer to
5429  // actually receive all the data read from disk over the network.
5431  "Peer %d sent us a getblocktxn for a block > %i deep\n",
5432  pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
5433  CInv inv;
5434  inv.type = MSG_BLOCK;
5435  inv.hash = req.blockhash;
5436  WITH_LOCK(peer->m_getdata_requests_mutex,
5437  peer->m_getdata_requests.push_back(inv));
5438  // The message processing loop will go around again (without pausing)
5439  // and we'll respond then (without cs_main)
5440  return;
5441  }
5442 
5443  if (msg_type == NetMsgType::GETHEADERS) {
5444  CBlockLocator locator;
5445  BlockHash hashStop;
5446  vRecv >> locator >> hashStop;
5447 
5448  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
5450  "getheaders locator size %lld > %d, disconnect peer=%d\n",
5451  locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
5452  pfrom.fDisconnect = true;
5453  return;
5454  }
5455 
5456  if (m_chainman.m_blockman.LoadingBlocks()) {
5457  LogPrint(
5458  BCLog::NET,
5459  "Ignoring getheaders from peer=%d while importing/reindexing\n",
5460  pfrom.GetId());
5461  return;
5462  }
5463 
5464  LOCK(cs_main);
5465 
5466  // Note that if we were to be on a chain that forks from the
5467  // checkpointed chain, then serving those headers to a peer that has
5468  // seen the checkpointed chain would cause that peer to disconnect us.
5469  // Requiring that our chainwork exceed the minimum chainwork is a
5470  // protection against being fed a bogus chain when we started up for
5471  // the first time and getting partitioned off the honest network for
5472  // serving that chain to others.
5473  if (m_chainman.ActiveTip() == nullptr ||
5474  (m_chainman.ActiveTip()->nChainWork <
5475  m_chainman.MinimumChainWork() &&
5478  "Ignoring getheaders from peer=%d because active chain "
5479  "has too little work; sending empty response\n",
5480  pfrom.GetId());
5481  // Just respond with an empty headers message, to tell the peer to
5482  // go away but not treat us as unresponsive.
5483  m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::HEADERS,
5484  std::vector<CBlock>()));
5485  return;
5486  }
5487 
5488  CNodeState *nodestate = State(pfrom.GetId());
5489  const CBlockIndex *pindex = nullptr;
5490  if (locator.IsNull()) {
5491  // If locator is null, return the hashStop block
5492  pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
5493  if (!pindex) {
5494  return;
5495  }
5496 
5497  if (!BlockRequestAllowed(pindex)) {
5499  "%s: ignoring request from peer=%i for old block "
5500  "header that isn't in the main chain\n",
5501  __func__, pfrom.GetId());
5502  return;
5503  }
5504  } else {
5505  // Find the last block the caller has in the main chain
5506  pindex =
5507  m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
5508  if (pindex) {
5509  pindex = m_chainman.ActiveChain().Next(pindex);
5510  }
5511  }
5512 
5513  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx
5514  // count at the end
5515  std::vector<CBlock> vHeaders;
5516  int nLimit = MAX_HEADERS_RESULTS;
5517  LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n",
5518  (pindex ? pindex->nHeight : -1),
5519  hashStop.IsNull() ? "end" : hashStop.ToString(),
5520  pfrom.GetId());
5521  for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) {
5522  vHeaders.push_back(pindex->GetBlockHeader());
5523  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) {
5524  break;
5525  }
5526  }
5527  // pindex can be nullptr either if we sent
5528  // m_chainman.ActiveChain().Tip() OR if our peer has
5529  // m_chainman.ActiveChain().Tip() (and thus we are sending an empty
5530  // headers message). In both cases it's safe to update
5531  // pindexBestHeaderSent to be our tip.
5532  //
5533  // It is important that we simply reset the BestHeaderSent value here,
5534  // and not max(BestHeaderSent, newHeaderSent). We might have announced
5535  // the currently-being-connected tip using a compact block, which
5536  // resulted in the peer sending a headers request, which we respond to
5537  // without the new block. By resetting the BestHeaderSent, we ensure we
5538  // will re-announce the new block via headers (or compact blocks again)
5539  // in the SendMessages logic.
5540  nodestate->pindexBestHeaderSent =
5541  pindex ? pindex : m_chainman.ActiveChain().Tip();
5542  m_connman.PushMessage(&pfrom,
5543  msgMaker.Make(NetMsgType::HEADERS, vHeaders));
5544  return;
5545  }
5546 
5547  if (msg_type == NetMsgType::TX) {
5548  // Stop processing the transaction early if
5549  // 1) We are in blocks only mode and peer has no relay permission; OR
5550  // 2) This peer is a block-relay-only peer
5551  if ((m_opts.ignore_incoming_txs &&
5553  pfrom.IsBlockOnlyConn()) {
5555  "transaction sent in violation of protocol peer=%d\n",
5556  pfrom.GetId());
5557  pfrom.fDisconnect = true;
5558  return;
5559  }
5560 
5561  // Stop processing the transaction early if we are still in IBD since we
5562  // don't have enough information to validate it yet. Sending unsolicited
5563  // transactions is not considered a protocol violation, so don't punish
5564  // the peer.
5565  if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
5566  return;
5567  }
5568 
5569  CTransactionRef ptx;
5570  vRecv >> ptx;
5571  const CTransaction &tx = *ptx;
5572  const TxId &txid = tx.GetId();
5573  AddKnownTx(*peer, txid);
5574 
5575  LOCK(cs_main);
5576 
5577  m_txrequest.ReceivedResponse(pfrom.GetId(), txid);
5578 
5579  if (AlreadyHaveTx(txid, /*include_reconsiderable=*/true)) {
5581  // Always relay transactions received from peers with
5582  // forcerelay permission, even if they were already in the
5583  // mempool, allowing the node to function as a gateway for
5584  // nodes hidden behind it.
5585  if (!m_mempool.exists(tx.GetId())) {
5586  LogPrintf("Not relaying non-mempool transaction %s from "
5587  "forcerelay peer=%d\n",
5588  tx.GetId().ToString(), pfrom.GetId());
5589  } else {
5590  LogPrintf("Force relaying tx %s from peer=%d\n",
5591  tx.GetId().ToString(), pfrom.GetId());
5592  RelayTransaction(tx.GetId());
5593  }
5594  }
5595 
5596  if (m_recent_rejects_reconsiderable.contains(txid)) {
5597  // When a transaction is already in
5598  // m_recent_rejects_reconsiderable, we shouldn't submit it by
5599  // itself again. However, look for a matching child in the
5600  // orphanage, as it is possible that they succeed as a package.
5602  "found tx %s in reconsiderable rejects, looking for "
5603  "child in orphanage\n",
5604  txid.ToString());
5605  if (auto package_to_validate{
5606  Find1P1CPackage(ptx, pfrom.GetId())}) {
5607  const auto package_result{ProcessNewPackage(
5608  m_chainman.ActiveChainstate(), m_mempool,
5609  package_to_validate->m_txns, /*test_accept=*/false)};
5611  "package evaluation for %s: %s (%s)\n",
5612  package_to_validate->ToString(),
5613  package_result.m_state.IsValid()
5614  ? "package accepted"
5615  : "package rejected",
5616  package_result.m_state.ToString());
5617  ProcessPackageResult(package_to_validate.value(),
5618  package_result);
5619  }
5620  }
5621  // If a tx is detected by m_recent_rejects it is ignored. Because we
5622  // haven't submitted the tx to our mempool, we won't have computed a
5623  // DoS score for it or determined exactly why we consider it
5624  // invalid.
5625  //
5626  // This means we won't penalize any peer subsequently relaying a
5627  // DoSy tx (even if we penalized the first peer who gave it to us)
5628  // because we have to account for m_recent_rejects showing false
5629  // positives. In other words, we shouldn't penalize a peer if we
5630  // aren't *sure* they submitted a DoSy tx.
5631  //
5632  // Note that m_recent_rejects doesn't just record DoSy or invalid
5633  // transactions, but any tx not accepted by the mempool, which may
5634  // be due to node policy (vs. consensus). So we can't blanket
5635  // penalize a peer simply for relaying a tx that our
5636  // m_recent_rejects has caught, regardless of false positives.
5637  return;
5638  }
5639 
5640  const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx);
5641  const TxValidationState &state = result.m_state;
5642 
5644  ProcessValidTx(pfrom.GetId(), ptx);
5645  pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
5646  } else if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
5647  // It may be the case that the orphans parents have all been
5648  // rejected.
5649  bool fRejectedParents = false;
5650 
5651  // Deduplicate parent txids, so that we don't have to loop over
5652  // the same parent txid more than once down below.
5653  std::vector<TxId> unique_parents;
5654  unique_parents.reserve(tx.vin.size());
5655  for (const CTxIn &txin : tx.vin) {
5656  // We start with all parents, and then remove duplicates below.
5657  unique_parents.push_back(txin.prevout.GetTxId());
5658  }
5659  std::sort(unique_parents.begin(), unique_parents.end());
5660  unique_parents.erase(
5661  std::unique(unique_parents.begin(), unique_parents.end()),
5662  unique_parents.end());
5663 
5664  // Distinguish between parents in m_recent_rejects and
5665  // m_recent_rejects_reconsiderable. We can tolerate having up to 1
5666  // parent in m_recent_rejects_reconsiderable since we submit 1p1c
5667  // packages. However, fail immediately if any are in
5668  // m_recent_rejects.
5669  std::optional<TxId> rejected_parent_reconsiderable;
5670  for (const TxId &parent_txid : unique_parents) {
5671  if (m_recent_rejects.contains(parent_txid)) {
5672  fRejectedParents = true;
5673  break;
5674  }
5675 
5676  if (m_recent_rejects_reconsiderable.contains(parent_txid) &&
5677  !m_mempool.exists(parent_txid)) {
5678  // More than 1 parent in m_recent_rejects_reconsiderable:
5679  // 1p1c will not be sufficient to accept this package, so
5680  // just give up here.
5681  if (rejected_parent_reconsiderable.has_value()) {
5682  fRejectedParents = true;
5683  break;
5684  }
5685  rejected_parent_reconsiderable = parent_txid;
5686  }
5687  }
5688  if (!fRejectedParents) {
5689  const auto current_time{GetTime<std::chrono::microseconds>()};
5690 
5691  for (const TxId &parent_txid : unique_parents) {
5692  // FIXME: MSG_TX should use a TxHash, not a TxId.
5693  AddKnownTx(*peer, parent_txid);
5694  // Exclude m_recent_rejects_reconsiderable: the missing
5695  // parent may have been previously rejected for being too
5696  // low feerate. This orphan might CPFP it.
5697  if (!AlreadyHaveTx(parent_txid,
5698  /*include_reconsiderable=*/false)) {
5699  AddTxAnnouncement(pfrom, parent_txid, current_time);
5700  }
5701  }
5702 
5703  if (m_orphanage.AddTx(ptx, pfrom.GetId())) {
5704  AddToCompactExtraTransactions(ptx);
5705  }
5706 
5707  // Once added to the orphan pool, a tx is considered
5708  // AlreadyHave, and we shouldn't request it anymore.
5709  m_txrequest.ForgetInvId(tx.GetId());
5710 
5711  unsigned int nEvicted =
5712  m_orphanage.LimitOrphans(m_opts.max_orphan_txs, m_rng);
5713  if (nEvicted > 0) {
5715  "orphanage overflow, removed %u tx\n", nEvicted);
5716  }
5717  } else {
5719  "not keeping orphan with rejected parents %s\n",
5720  tx.GetId().ToString());
5721  // We will continue to reject this tx since it has rejected
5722  // parents so avoid re-requesting it from other peers.
5723  m_recent_rejects.insert(tx.GetId());
5724  m_txrequest.ForgetInvId(tx.GetId());
5725  }
5726  }
5727  if (state.IsInvalid()) {
5728  ProcessInvalidTx(pfrom.GetId(), ptx, state,
5729  /*maybe_add_extra_compact_tx=*/true);
5730  }
5731  // When a transaction fails for TX_RECONSIDERABLE, look for a matching
5732  // child in the orphanage, as it is possible that they succeed as a
5733  // package.
5736  "tx %s failed but reconsiderable, looking for child in "
5737  "orphanage\n",
5738  txid.ToString());
5739  if (auto package_to_validate{Find1P1CPackage(ptx, pfrom.GetId())}) {
5740  const auto package_result{ProcessNewPackage(
5741  m_chainman.ActiveChainstate(), m_mempool,
5742  package_to_validate->m_txns, /*test_accept=*/false)};
5744  "package evaluation for %s: %s (%s)\n",
5745  package_to_validate->ToString(),
5746  package_result.m_state.IsValid() ? "package accepted"
5747  : "package rejected",
5748  package_result.m_state.ToString());
5749  ProcessPackageResult(package_to_validate.value(),
5750  package_result);
5751  }
5752  }
5753 
5754  return;
5755  }
5756 
5757  if (msg_type == NetMsgType::CMPCTBLOCK) {
5758  // Ignore cmpctblock received while importing
5759  if (m_chainman.m_blockman.LoadingBlocks()) {
5761  "Unexpected cmpctblock message received from peer %d\n",
5762  pfrom.GetId());
5763  return;
5764  }
5765 
5766  CBlockHeaderAndShortTxIDs cmpctblock;
5767  try {
5768  vRecv >> cmpctblock;
5769  } catch (std::ios_base::failure &e) {
5770  // This block has non contiguous or overflowing indexes
5771  Misbehaving(*peer, 100, "cmpctblock-bad-indexes");
5772  return;
5773  }
5774 
5775  bool received_new_header = false;
5776 
5777  {
5778  LOCK(cs_main);
5779 
5780  const CBlockIndex *prev_block =
5781  m_chainman.m_blockman.LookupBlockIndex(
5782  cmpctblock.header.hashPrevBlock);
5783  if (!prev_block) {
5784  // Doesn't connect (or is genesis), instead of DoSing in
5785  // AcceptBlockHeader, request deeper headers
5786  if (!m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
5787  MaybeSendGetHeaders(
5788  pfrom, GetLocator(m_chainman.m_best_header), *peer);
5789  }
5790  return;
5791  }
5792  if (prev_block->nChainWork +
5793  CalculateHeadersWork({cmpctblock.header}) <
5794  GetAntiDoSWorkThreshold()) {
5795  // If we get a low-work header in a compact block, we can ignore
5796  // it.
5798  "Ignoring low-work compact block from peer %d\n",
5799  pfrom.GetId());
5800  return;
5801  }
5802 
5803  if (!m_chainman.m_blockman.LookupBlockIndex(
5804  cmpctblock.header.GetHash())) {
5805  received_new_header = true;
5806  }
5807  }
5808 
5809  const CBlockIndex *pindex = nullptr;
5810  BlockValidationState state;
5811  if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header},
5812  /*min_pow_checked=*/true, state,
5813  &pindex)) {
5814  if (state.IsInvalid()) {
5815  MaybePunishNodeForBlock(pfrom.GetId(), state,
5816  /*via_compact_block*/ true,
5817  "invalid header via cmpctblock");
5818  return;
5819  }
5820  }
5821 
5822  // When we succeed in decoding a block's txids from a cmpctblock
5823  // message we typically jump to the BLOCKTXN handling code, with a
5824  // dummy (empty) BLOCKTXN message, to re-use the logic there in
5825  // completing processing of the putative block (without cs_main).
5826  bool fProcessBLOCKTXN = false;
5828 
5829  // If we end up treating this as a plain headers message, call that as
5830  // well
5831  // without cs_main.
5832  bool fRevertToHeaderProcessing = false;
5833 
5834  // Keep a CBlock for "optimistic" compactblock reconstructions (see
5835  // below)
5836  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
5837  bool fBlockReconstructed = false;
5838 
5839  {
5840  LOCK(cs_main);
5841  // If AcceptBlockHeader returned true, it set pindex
5842  assert(pindex);
5843  UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
5844 
5845  CNodeState *nodestate = State(pfrom.GetId());
5846 
5847  // If this was a new header with more work than our tip, update the
5848  // peer's last block announcement time
5849  if (received_new_header &&
5850  pindex->nChainWork >
5851  m_chainman.ActiveChain().Tip()->nChainWork) {
5852  nodestate->m_last_block_announcement = GetTime();
5853  }
5854 
5855  std::map<BlockHash,
5856  std::pair<NodeId, std::list<QueuedBlock>::iterator>>::
5857  iterator blockInFlightIt =
5858  mapBlocksInFlight.find(pindex->GetBlockHash());
5859  bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
5860 
5861  if (pindex->nStatus.hasData()) {
5862  // Nothing to do here
5863  return;
5864  }
5865 
5866  if (pindex->nChainWork <=
5867  m_chainman.ActiveChain()
5868  .Tip()
5869  ->nChainWork || // We know something better
5870  pindex->nTx != 0) {
5871  // We had this block at some point, but pruned it
5872  if (fAlreadyInFlight) {
5873  // We requested this block for some reason, but our mempool
5874  // will probably be useless so we just grab the block via
5875  // normal getdata.
5876  std::vector<CInv> vInv(1);
5877  vInv[0] = CInv(MSG_BLOCK, cmpctblock.header.GetHash());
5878  m_connman.PushMessage(
5879  &pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
5880  }
5881  return;
5882  }
5883 
5884  // If we're not close to tip yet, give up and let parallel block
5885  // fetch work its magic.
5886  if (!fAlreadyInFlight && !CanDirectFetch()) {
5887  return;
5888  }
5889 
5890  // We want to be a bit conservative just to be extra careful about
5891  // DoS possibilities in compact block processing...
5892  if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
5893  if ((!fAlreadyInFlight && nodestate->nBlocksInFlight <
5895  (fAlreadyInFlight &&
5896  blockInFlightIt->second.first == pfrom.GetId())) {
5897  std::list<QueuedBlock>::iterator *queuedBlockIt = nullptr;
5898  if (!BlockRequested(config, pfrom.GetId(), *pindex,
5899  &queuedBlockIt)) {
5900  if (!(*queuedBlockIt)->partialBlock) {
5901  (*queuedBlockIt)
5902  ->partialBlock.reset(
5903  new PartiallyDownloadedBlock(config,
5904  &m_mempool));
5905  } else {
5906  // The block was already in flight using compact
5907  // blocks from the same peer.
5908  LogPrint(BCLog::NET, "Peer sent us compact block "
5909  "we were already syncing!\n");
5910  return;
5911  }
5912  }
5913 
5914  PartiallyDownloadedBlock &partialBlock =
5915  *(*queuedBlockIt)->partialBlock;
5916  ReadStatus status =
5917  partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
5918  if (status == READ_STATUS_INVALID) {
5919  // Reset in-flight state in case Misbehaving does not
5920  // result in a disconnect
5921  RemoveBlockRequest(pindex->GetBlockHash());
5922  Misbehaving(*peer, 100, "invalid compact block");
5923  return;
5924  } else if (status == READ_STATUS_FAILED) {
5925  // Duplicate txindices, the block is now in-flight, so
5926  // just request it.
5927  std::vector<CInv> vInv(1);
5928  vInv[0] = CInv(MSG_BLOCK, cmpctblock.header.GetHash());
5929  m_connman.PushMessage(
5930  &pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
5931  return;
5932  }
5933 
5935  for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
5936  if (!partialBlock.IsTxAvailable(i)) {
5937  req.indices.push_back(i);
5938  }
5939  }
5940  if (req.indices.empty()) {
5941  // Dirty hack to jump to BLOCKTXN code (TODO: move
5942  // message handling into their own functions)
5943  BlockTransactions txn;
5944  txn.blockhash = cmpctblock.header.GetHash();
5945  blockTxnMsg << txn;
5946  fProcessBLOCKTXN = true;
5947  } else {
5948  req.blockhash = pindex->GetBlockHash();
5949  m_connman.PushMessage(
5950  &pfrom,
5951  msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
5952  }
5953  } else {
5954  // This block is either already in flight from a different
5955  // peer, or this peer has too many blocks outstanding to
5956  // download from. Optimistically try to reconstruct anyway
5957  // since we might be able to without any round trips.
5958  PartiallyDownloadedBlock tempBlock(config, &m_mempool);
5959  ReadStatus status =
5960  tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
5961  if (status != READ_STATUS_OK) {
5962  // TODO: don't ignore failures
5963  return;
5964  }
5965  std::vector<CTransactionRef> dummy;
5966  status = tempBlock.FillBlock(*pblock, dummy);
5967  if (status == READ_STATUS_OK) {
5968  fBlockReconstructed = true;
5969  }
5970  }
5971  } else {
5972  if (fAlreadyInFlight) {
5973  // We requested this block, but its far into the future, so
5974  // our mempool will probably be useless - request the block
5975  // normally.
5976  std::vector<CInv> vInv(1);
5977  vInv[0] = CInv(MSG_BLOCK, cmpctblock.header.GetHash());
5978  m_connman.PushMessage(
5979  &pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
5980  return;
5981  } else {
5982  // If this was an announce-cmpctblock, we want the same
5983  // treatment as a header message.
5984  fRevertToHeaderProcessing = true;
5985  }
5986  }
5987  } // cs_main
5988 
5989  if (fProcessBLOCKTXN) {
5990  return ProcessMessage(config, pfrom, NetMsgType::BLOCKTXN,
5991  blockTxnMsg, time_received, interruptMsgProc);
5992  }
5993 
5994  if (fRevertToHeaderProcessing) {
5995  // Headers received from HB compact block peers are permitted to be
5996  // relayed before full validation (see BIP 152), so we don't want to
5997  // disconnect the peer if the header turns out to be for an invalid
5998  // block. Note that if a peer tries to build on an invalid chain,
5999  // that will be detected and the peer will be banned.
6000  return ProcessHeadersMessage(config, pfrom, *peer,
6001  {cmpctblock.header},
6002  /*via_compact_block=*/true);
6003  }
6004 
6005  if (fBlockReconstructed) {
6006  // If we got here, we were able to optimistically reconstruct a
6007  // block that is in flight from some other peer.
6008  {
6009  LOCK(cs_main);
6010  mapBlockSource.emplace(pblock->GetHash(),
6011  std::make_pair(pfrom.GetId(), false));
6012  }
6013  // Setting force_processing to true means that we bypass some of
6014  // our anti-DoS protections in AcceptBlock, which filters
6015  // unrequested blocks that might be trying to waste our resources
6016  // (eg disk space). Because we only try to reconstruct blocks when
6017  // we're close to caught up (via the CanDirectFetch() requirement
6018  // above, combined with the behavior of not requesting blocks until
6019  // we have a chain with at least the minimum chain work), and we
6020  // ignore compact blocks with less work than our tip, it is safe to
6021  // treat reconstructed compact blocks as having been requested.
6022  ProcessBlock(config, pfrom, pblock, /*force_processing=*/true,
6023  /*min_pow_checked=*/true);
6024  // hold cs_main for CBlockIndex::IsValid()
6025  LOCK(cs_main);
6026  if (pindex->IsValid(BlockValidity::TRANSACTIONS)) {
6027  // Clear download state for this block, which is in process from
6028  // some other peer. We do this after calling. ProcessNewBlock so
6029  // that a malleated cmpctblock announcement can't be used to
6030  // interfere with block relay.
6031  RemoveBlockRequest(pblock->GetHash());
6032  }
6033  }
6034  return;
6035  }
6036 
6037  if (msg_type == NetMsgType::BLOCKTXN) {
6038  // Ignore blocktxn received while importing
6039  if (m_chainman.m_blockman.LoadingBlocks()) {
6041  "Unexpected blocktxn message received from peer %d\n",
6042  pfrom.GetId());
6043  return;
6044  }
6045 
6046  BlockTransactions resp;
6047  vRecv >> resp;
6048 
6049  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6050  bool fBlockRead = false;
6051  {
6052  LOCK(cs_main);
6053 
6054  std::map<BlockHash,
6055  std::pair<NodeId, std::list<QueuedBlock>::iterator>>::
6056  iterator it = mapBlocksInFlight.find(resp.blockhash);
6057  if (it == mapBlocksInFlight.end() ||
6058  !it->second.second->partialBlock ||
6059  it->second.first != pfrom.GetId()) {
6061  "Peer %d sent us block transactions for block "
6062  "we weren't expecting\n",
6063  pfrom.GetId());
6064  return;
6065  }
6066 
6067  PartiallyDownloadedBlock &partialBlock =
6068  *it->second.second->partialBlock;
6069  ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
6070  if (status == READ_STATUS_INVALID) {
6071  // Reset in-flight state in case of Misbehaving does not
6072  // result in a disconnect.
6073  RemoveBlockRequest(resp.blockhash);
6074  Misbehaving(
6075  *peer, 100,
6076  "invalid compact block/non-matching block transactions");
6077  return;
6078  } else if (status == READ_STATUS_FAILED) {
6079  // Might have collided, fall back to getdata now :(
6080  std::vector<CInv> invs;
6081  invs.push_back(CInv(MSG_BLOCK, resp.blockhash));
6082  m_connman.PushMessage(&pfrom,
6083  msgMaker.Make(NetMsgType::GETDATA, invs));
6084  } else {
6085  // Block is either okay, or possibly we received
6086  // READ_STATUS_CHECKBLOCK_FAILED.
6087  // Note that CheckBlock can only fail for one of a few reasons:
6088  // 1. bad-proof-of-work (impossible here, because we've already
6089  // accepted the header)
6090  // 2. merkleroot doesn't match the transactions given (already
6091  // caught in FillBlock with READ_STATUS_FAILED, so
6092  // impossible here)
6093  // 3. the block is otherwise invalid (eg invalid coinbase,
6094  // block is too big, too many sigChecks, etc).
6095  // So if CheckBlock failed, #3 is the only possibility.
6096  // Under BIP 152, we don't DoS-ban unless proof of work is
6097  // invalid (we don't require all the stateless checks to have
6098  // been run). This is handled below, so just treat this as
6099  // though the block was successfully read, and rely on the
6100  // handling in ProcessNewBlock to ensure the block index is
6101  // updated, etc.
6102 
6103  // it is now an empty pointer
6104  RemoveBlockRequest(resp.blockhash);
6105  fBlockRead = true;
6106  // mapBlockSource is used for potentially punishing peers and
6107  // updating which peers send us compact blocks, so the race
6108  // between here and cs_main in ProcessNewBlock is fine.
6109  // BIP 152 permits peers to relay compact blocks after
6110  // validating the header only; we should not punish peers
6111  // if the block turns out to be invalid.
6112  mapBlockSource.emplace(resp.blockhash,
6113  std::make_pair(pfrom.GetId(), false));
6114  }
6115  } // Don't hold cs_main when we call into ProcessNewBlock
6116  if (fBlockRead) {
6117  // Since we requested this block (it was in mapBlocksInFlight),
6118  // force it to be processed, even if it would not be a candidate for
6119  // new tip (missing previous block, chain not long enough, etc)
6120  // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
6121  // disk-space attacks), but this should be safe due to the
6122  // protections in the compact block handler -- see related comment
6123  // in compact block optimistic reconstruction handling.
6124  ProcessBlock(config, pfrom, pblock, /*force_processing=*/true,
6125  /*min_pow_checked=*/true);
6126  }
6127  return;
6128  }
6129 
6130  if (msg_type == NetMsgType::HEADERS) {
6131  // Ignore headers received while importing
6132  if (m_chainman.m_blockman.LoadingBlocks()) {
6134  "Unexpected headers message received from peer %d\n",
6135  pfrom.GetId());
6136  return;
6137  }
6138 
6139  // Assume that this is in response to any outstanding getheaders
6140  // request we may have sent, and clear out the time of our last request
6141  peer->m_last_getheaders_timestamp = {};
6142 
6143  std::vector<CBlockHeader> headers;
6144 
6145  // Bypass the normal CBlock deserialization, as we don't want to risk
6146  // deserializing 2000 full blocks.
6147  unsigned int nCount = ReadCompactSize(vRecv);
6148  if (nCount > MAX_HEADERS_RESULTS) {
6149  Misbehaving(*peer, 20,
6150  strprintf("too-many-headers: headers message size = %u",
6151  nCount));
6152  return;
6153  }
6154  headers.resize(nCount);
6155  for (unsigned int n = 0; n < nCount; n++) {
6156  vRecv >> headers[n];
6157  // Ignore tx count; assume it is 0.
6158  ReadCompactSize(vRecv);
6159  }
6160 
6161  ProcessHeadersMessage(config, pfrom, *peer, std::move(headers),
6162  /*via_compact_block=*/false);
6163 
6164  // Check if the headers presync progress needs to be reported to
6165  // validation. This needs to be done without holding the
6166  // m_headers_presync_mutex lock.
6167  if (m_headers_presync_should_signal.exchange(false)) {
6168  HeadersPresyncStats stats;
6169  {
6170  LOCK(m_headers_presync_mutex);
6171  auto it =
6172  m_headers_presync_stats.find(m_headers_presync_bestpeer);
6173  if (it != m_headers_presync_stats.end()) {
6174  stats = it->second;
6175  }
6176  }
6177  if (stats.second) {
6178  m_chainman.ReportHeadersPresync(
6179  stats.first, stats.second->first, stats.second->second);
6180  }
6181  }
6182 
6183  return;
6184  }
6185 
6186  if (msg_type == NetMsgType::BLOCK) {
6187  // Ignore block received while importing
6188  if (m_chainman.m_blockman.LoadingBlocks()) {
6190  "Unexpected block message received from peer %d\n",
6191  pfrom.GetId());
6192  return;
6193  }
6194 
6195  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6196  vRecv >> *pblock;
6197 
6198  LogPrint(BCLog::NET, "received block %s peer=%d\n",
6199  pblock->GetHash().ToString(), pfrom.GetId());
6200 
6201  // Process all blocks from whitelisted peers, even if not requested,
6202  // unless we're still syncing with the network. Such an unrequested
6203  // block may still be processed, subject to the conditions in
6204  // AcceptBlock().
6205  bool forceProcessing =
6207  !m_chainman.ActiveChainstate().IsInitialBlockDownload();
6208  const BlockHash hash = pblock->GetHash();
6209  bool min_pow_checked = false;
6210  {
6211  LOCK(cs_main);
6212  // Always process the block if we requested it, since we may
6213  // need it even when it's not a candidate for a new best tip.
6214  forceProcessing = IsBlockRequested(hash);
6215  RemoveBlockRequest(hash);
6216  // mapBlockSource is only used for punishing peers and setting
6217  // which peers send us compact blocks, so the race between here and
6218  // cs_main in ProcessNewBlock is fine.
6219  mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
6220 
6221  // Check work on this block against our anti-dos thresholds.
6222  const CBlockIndex *prev_block =
6223  m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock);
6224  if (prev_block &&
6225  prev_block->nChainWork +
6226  CalculateHeadersWork({pblock->GetBlockHeader()}) >=
6227  GetAntiDoSWorkThreshold()) {
6228  min_pow_checked = true;
6229  }
6230  }
6231  ProcessBlock(config, pfrom, pblock, forceProcessing, min_pow_checked);
6232  return;
6233  }
6234 
6235  if (msg_type == NetMsgType::AVAHELLO) {
6236  if (!m_avalanche) {
6237  return;
6238  }
6239  {
6240  LOCK(pfrom.cs_avalanche_pubkey);
6241  if (pfrom.m_avalanche_pubkey.has_value()) {
6242  LogPrint(
6244  "Ignoring avahello from peer %d: already in our node set\n",
6245  pfrom.GetId());
6246  return;
6247  }
6248 
6249  avalanche::Delegation delegation;
6250  vRecv >> delegation;
6251 
6252  // A delegation with an all zero limited id indicates that the peer
6253  // has no proof, so we're done.
6254  if (delegation.getLimitedProofId() != uint256::ZERO) {
6256  CPubKey pubkey;
6257  if (!delegation.verify(state, pubkey)) {
6258  Misbehaving(*peer, 100, "invalid-delegation");
6259  return;
6260  }
6261  pfrom.m_avalanche_pubkey = std::move(pubkey);
6262 
6263  HashWriter sighasher{};
6264  sighasher << delegation.getId();
6265  sighasher << pfrom.nRemoteHostNonce;
6266  sighasher << pfrom.GetLocalNonce();
6267  sighasher << pfrom.nRemoteExtraEntropy;
6268  sighasher << pfrom.GetLocalExtraEntropy();
6269 
6270  SchnorrSig sig;
6271  vRecv >> sig;
6272  if (!(*pfrom.m_avalanche_pubkey)
6273  .VerifySchnorr(sighasher.GetHash(), sig)) {
6274  Misbehaving(*peer, 100, "invalid-avahello-signature");
6275  return;
6276  }
6277 
6278  // If we don't know this proof already, add it to the tracker so
6279  // it can be requested.
6280  const avalanche::ProofId proofid(delegation.getProofId());
6281  if (!AlreadyHaveProof(proofid)) {
6282  const bool preferred = isPreferredDownloadPeer(pfrom);
6283  LOCK(cs_proofrequest);
6284  AddProofAnnouncement(pfrom, proofid,
6285  GetTime<std::chrono::microseconds>(),
6286  preferred);
6287  }
6288 
6289  // Don't check the return value. If it fails we probably don't
6290  // know about the proof yet.
6291  m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
6292  return pm.addNode(pfrom.GetId(), proofid);
6293  });
6294  }
6295 
6296  pfrom.m_avalanche_enabled = true;
6297  }
6298 
6299  // Send getavaaddr and getavaproofs to our avalanche outbound or
6300  // manual connections
6301  if (!pfrom.IsInboundConn()) {
6302  m_connman.PushMessage(&pfrom,
6303  msgMaker.Make(NetMsgType::GETAVAADDR));
6304  WITH_LOCK(peer->m_addr_token_bucket_mutex,
6305  peer->m_addr_token_bucket += m_opts.max_addr_to_send);
6306 
6307  if (peer->m_proof_relay &&
6308  !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
6309  m_connman.PushMessage(&pfrom,
6310  msgMaker.Make(NetMsgType::GETAVAPROOFS));
6311  peer->m_proof_relay->compactproofs_requested = true;
6312  }
6313  }
6314 
6315  return;
6316  }
6317 
6318  if (msg_type == NetMsgType::AVAPOLL) {
6319  if (!m_avalanche) {
6320  return;
6321  }
6322  const auto now = Now<SteadyMilliseconds>();
6323 
6324  const auto last_poll = pfrom.m_last_poll;
6325  pfrom.m_last_poll = now;
6326 
6327  if (now <
6328  last_poll + std::chrono::milliseconds(m_opts.avalanche_cooldown)) {
6330  "Ignoring repeated avapoll from peer %d: cooldown not "
6331  "elapsed\n",
6332  pfrom.GetId());
6333  return;
6334  }
6335 
6336  const bool quorum_established = m_avalanche->isQuorumEstablished();
6337 
6338  uint64_t round;
6339  Unserialize(vRecv, round);
6340 
6341  unsigned int nCount = ReadCompactSize(vRecv);
6342  if (nCount > AVALANCHE_MAX_ELEMENT_POLL) {
6343  Misbehaving(
6344  *peer, 20,
6345  strprintf("too-many-ava-poll: poll message size = %u", nCount));
6346  return;
6347  }
6348 
6349  std::vector<avalanche::Vote> votes;
6350  votes.reserve(nCount);
6351 
6352  for (unsigned int n = 0; n < nCount; n++) {
6353  CInv inv;
6354  vRecv >> inv;
6355 
6356  // Default vote for unknown inv type
6357  uint32_t vote = -1;
6358 
6359  // We don't vote definitively until we have an established quorum
6360  if (!quorum_established) {
6361  votes.emplace_back(vote, inv.hash);
6362  continue;
6363  }
6364 
6365  // If inv's type is known, get a vote for its hash
6366  switch (inv.type) {
6367  case MSG_TX: {
6368  if (m_opts.avalanche_preconsensus) {
6369  vote = WITH_LOCK(cs_main, return GetAvalancheVoteForTx(
6370  TxId(inv.hash)));
6371  }
6372  } break;
6373  case MSG_BLOCK: {
6374  vote = WITH_LOCK(cs_main, return GetAvalancheVoteForBlock(
6375  BlockHash(inv.hash)));
6376  } break;
6377  case MSG_AVA_PROOF: {
6378  vote = getAvalancheVoteForProof(
6379  *m_avalanche, avalanche::ProofId(inv.hash));
6380  } break;
6381  default: {
6383  "poll inv type %d unknown from peer=%d\n",
6384  inv.type, pfrom.GetId());
6385  }
6386  }
6387 
6388  votes.emplace_back(vote, inv.hash);
6389  }
6390 
6391  // Send the query to the node.
6392  m_avalanche->sendResponse(
6393  &pfrom, avalanche::Response(round, m_opts.avalanche_cooldown,
6394  std::move(votes)));
6395  return;
6396  }
6397 
6398  if (msg_type == NetMsgType::AVARESPONSE) {
6399  if (!m_avalanche) {
6400  return;
6401  }
6402  // As long as QUIC is not implemented, we need to sign response and
6403  // verify response's signatures in order to avoid any manipulation of
6404  // messages at the transport level.
6405  CHashVerifier<CDataStream> verifier(&vRecv);
6407  verifier >> response;
6408 
6409  SchnorrSig sig;
6410  vRecv >> sig;
6411 
6412  {
6413  LOCK(pfrom.cs_avalanche_pubkey);
6414  if (!pfrom.m_avalanche_pubkey.has_value() ||
6415  !(*pfrom.m_avalanche_pubkey)
6416  .VerifySchnorr(verifier.GetHash(), sig)) {
6417  Misbehaving(*peer, 100, "invalid-ava-response-signature");
6418  return;
6419  }
6420  }
6421 
6422  auto now = GetTime<std::chrono::seconds>();
6423 
6424  std::vector<avalanche::VoteItemUpdate> updates;
6425  int banscore{0};
6426  std::string error;
6427  if (!m_avalanche->registerVotes(pfrom.GetId(), response, updates,
6428  banscore, error)) {
6429  if (banscore > 0) {
6430  // If the banscore was set, just increase the node ban score
6431  Misbehaving(*peer, banscore, error);
6432  return;
6433  }
6434 
6435  // Otherwise the node may have got a network issue. Increase the
6436  // fault counter instead and only ban if we reached a threshold.
6437  // This allows for fault tolerance should there be a temporary
6438  // outage while still preventing DoS'ing behaviors, as the counter
6439  // is reset if no fault occured over some time period.
6441  pfrom.m_avalanche_last_message_fault = now;
6442 
6443  // Allow up to 12 messages before increasing the ban score. Since
6444  // the queries are cleared after 10s, this is at least 2 minutes
6445  // of network outage tolerance over the 1h window.
6446  if (pfrom.m_avalanche_message_fault_counter > 12) {
6447  Misbehaving(*peer, 2, error);
6448  return;
6449  }
6450  }
6451 
6452  // If no fault occurred within the last hour, reset the fault counter
6453  if (now > (pfrom.m_avalanche_last_message_fault.load() + 1h)) {
6455  }
6456 
6457  pfrom.invsVoted(response.GetVotes().size());
6458 
6459  auto logVoteUpdate = [](const auto &voteUpdate,
6460  const std::string &voteItemTypeStr,
6461  const auto &voteItemId) {
6462  std::string voteOutcome;
6463  switch (voteUpdate.getStatus()) {
6465  voteOutcome = "invalidated";
6466  break;
6468  voteOutcome = "rejected";
6469  break;
6471  voteOutcome = "accepted";
6472  break;
6474  voteOutcome = "finalized";
6475  break;
6477  voteOutcome = "stalled";
6478  break;
6479 
6480  // No default case, so the compiler can warn about missing
6481  // cases
6482  }
6483 
6484  LogPrint(BCLog::AVALANCHE, "Avalanche %s %s %s\n", voteOutcome,
6485  voteItemTypeStr, voteItemId.ToString());
6486  };
6487 
6488  bool shouldActivateBestChain = false;
6489 
6490  for (const auto &u : updates) {
6491  const avalanche::AnyVoteItem &item = u.getVoteItem();
6492 
6493  // Don't use a visitor here as we want to ignore unsupported item
6494  // types. This comes in handy when adding new types.
6495  if (auto pitem = std::get_if<const avalanche::ProofRef>(&item)) {
6496  avalanche::ProofRef proof = *pitem;
6497  const avalanche::ProofId &proofid = proof->getId();
6498 
6499  logVoteUpdate(u, "proof", proofid);
6500 
6501  auto rejectionMode =
6503  auto nextCooldownTimePoint = GetTime<std::chrono::seconds>();
6504  switch (u.getStatus()) {
6506  m_avalanche->withPeerManager(
6507  [&](avalanche::PeerManager &pm) {
6508  pm.setInvalid(proofid);
6509  });
6510  // Fallthrough
6512  // Invalidate mode removes the proof from all proof
6513  // pools
6514  rejectionMode =
6516  // Fallthrough
6518  if (!m_avalanche->withPeerManager(
6519  [&](avalanche::PeerManager &pm) {
6520  return pm.rejectProof(proofid,
6521  rejectionMode);
6522  })) {
6524  "ERROR: Failed to reject proof: %s\n",
6525  proofid.GetHex());
6526  }
6527  break;
6529  nextCooldownTimePoint += std::chrono::seconds(
6530  m_opts.avalanche_peer_replacement_cooldown);
6532  if (!m_avalanche->withPeerManager(
6533  [&](avalanche::PeerManager &pm) {
6534  pm.registerProof(
6535  proof,
6536  avalanche::PeerManager::
6537  RegistrationMode::FORCE_ACCEPT);
6538  return pm.forPeer(
6539  proofid,
6540  [&](const avalanche::Peer &peer) {
6541  pm.updateNextPossibleConflictTime(
6542  peer.peerid,
6543  nextCooldownTimePoint);
6544  if (u.getStatus() ==
6545  avalanche::VoteStatus::
6546  Finalized) {
6547  pm.setFinalized(peer.peerid);
6548  }
6549  // Only fail if the peer was not
6550  // created
6551  return true;
6552  });
6553  })) {
6555  "ERROR: Failed to accept proof: %s\n",
6556  proofid.GetHex());
6557  }
6558  break;
6559  }
6560  }
6561 
6562  if (auto pitem = std::get_if<const CBlockIndex *>(&item)) {
6563  CBlockIndex *pindex = const_cast<CBlockIndex *>(*pitem);
6564 
6565  shouldActivateBestChain = true;
6566 
6567  logVoteUpdate(u, "block", pindex->GetBlockHash());
6568 
6569  switch (u.getStatus()) {
6572  BlockValidationState state;
6573  m_chainman.ActiveChainstate().ParkBlock(state, pindex);
6574  if (!state.IsValid()) {
6575  LogPrintf("ERROR: Database error: %s\n",
6576  state.GetRejectReason());
6577  return;
6578  }
6579  } break;
6581  LOCK(cs_main);
6582  m_chainman.ActiveChainstate().UnparkBlock(pindex);
6583  } break;
6585  {
6586  LOCK(cs_main);
6587  m_chainman.ActiveChainstate().UnparkBlock(pindex);
6588  }
6589 
6590  if (m_opts.avalanche_preconsensus) {
6591  // First check if the block is cached before reading
6592  // from disk.
6593  auto pblock = WITH_LOCK(m_most_recent_block_mutex,
6594  return m_most_recent_block);
6595 
6596  if (!pblock ||
6597  pblock->GetHash() != pindex->GetBlockHash()) {
6598  std::shared_ptr<CBlock> pblockRead =
6599  std::make_shared<CBlock>();
6600  if (!m_chainman.m_blockman.ReadBlockFromDisk(
6601  *pblockRead, *pindex)) {
6602  assert(!"cannot load block from disk");
6603  }
6604  pblock = pblockRead;
6605  }
6606  assert(pblock);
6607 
6608  LOCK(m_mempool.cs);
6609  m_mempool.removeForFinalizedBlock(pblock->vtx);
6610  }
6611 
6612  m_chainman.ActiveChainstate().AvalancheFinalizeBlock(
6613  pindex, *m_avalanche);
6614  } break;
6616  // Fall back on Nakamoto consensus in the absence of
6617  // Avalanche votes for other competing or descendant
6618  // blocks.
6619  break;
6620  }
6621  }
6622 
6623  if (!m_opts.avalanche_preconsensus) {
6624  continue;
6625  }
6626 
6627  if (auto pitem = std::get_if<const CTransactionRef>(&item)) {
6628  const CTransactionRef tx = *pitem;
6629  assert(tx != nullptr);
6630 
6631  const TxId &txid = tx->GetId();
6632  logVoteUpdate(u, "tx", txid);
6633 
6634  switch (u.getStatus()) {
6636  break;
6638  // Remove from the mempool and the finalized tree, as
6639  // well as all the children txs.
6640  // FIXME Remember the tx has been invalidated so we
6641  // don't poll for it again and again.
6642  LOCK(m_mempool.cs);
6643  auto it = m_mempool.GetIter(txid);
6644  if (it.has_value()) {
6645  m_mempool.removeRecursive(
6647  }
6648 
6649  break;
6650  }
6652  break;
6654  LOCK(m_mempool.cs);
6655  auto it = m_mempool.GetIter(txid);
6656  if (!it.has_value()) {
6658  "Error: finalized tx (%s) is not in the "
6659  "mempool\n",
6660  txid.ToString());
6661  break;
6662  }
6663 
6664  m_mempool.setAvalancheFinalized(**it);
6665 
6666  break;
6667  }
6669  break;
6670  }
6671  }
6672  }
6673 
6674  if (shouldActivateBestChain) {
6675  BlockValidationState state;
6676  if (!m_chainman.ActiveChainstate().ActivateBestChain(
6677  state, /*pblock=*/nullptr, m_avalanche)) {
6678  LogPrintf("failed to activate chain (%s)\n", state.ToString());
6679  }
6680  }
6681 
6682  return;
6683  }
6684 
6685  if (msg_type == NetMsgType::AVAPROOF) {
6686  if (!m_avalanche) {
6687  return;
6688  }
6689  auto proof = RCUPtr<avalanche::Proof>::make();
6690  vRecv >> *proof;
6691 
6692  ReceivedAvalancheProof(pfrom, *peer, proof);
6693 
6694  return;
6695  }
6696 
6697  if (msg_type == NetMsgType::GETAVAPROOFS) {
6698  if (!m_avalanche) {
6699  return;
6700  }
6701  if (peer->m_proof_relay == nullptr) {
6702  return;
6703  }
6704 
6705  peer->m_proof_relay->lastSharedProofsUpdate =
6706  GetTime<std::chrono::seconds>();
6707 
6708  peer->m_proof_relay->sharedProofs =
6709  m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
6710  return pm.getShareableProofsSnapshot();
6711  });
6712 
6713  avalanche::CompactProofs compactProofs(
6714  peer->m_proof_relay->sharedProofs);
6715  m_connman.PushMessage(
6716  &pfrom, msgMaker.Make(NetMsgType::AVAPROOFS, compactProofs));
6717 
6718  return;
6719  }
6720 
6721  if (msg_type == NetMsgType::AVAPROOFS) {
6722  if (!m_avalanche) {
6723  return;
6724  }
6725  if (peer->m_proof_relay == nullptr) {
6726  return;
6727  }
6728 
6729  // Only process the compact proofs if we requested them
6730  if (!peer->m_proof_relay->compactproofs_requested) {
6731  LogPrint(BCLog::AVALANCHE, "Ignoring unsollicited avaproofs\n");
6732  return;
6733  }
6734  peer->m_proof_relay->compactproofs_requested = false;
6735 
6736  avalanche::CompactProofs compactProofs;
6737  try {
6738  vRecv >> compactProofs;
6739  } catch (std::ios_base::failure &e) {
6740  // This compact proofs have non contiguous or overflowing indexes
6741  Misbehaving(*peer, 100, "avaproofs-bad-indexes");
6742  return;
6743  }
6744 
6745  // If there are prefilled proofs, process them first
6746  std::set<uint32_t> prefilledIndexes;
6747  for (const auto &prefilledProof : compactProofs.getPrefilledProofs()) {
6748  if (!ReceivedAvalancheProof(pfrom, *peer, prefilledProof.proof)) {
6749  // If we got an invalid proof, the peer is getting banned and we
6750  // can bail out.
6751  return;
6752  }
6753  }
6754 
6755  // If there is no shortid, avoid parsing/responding/accounting for the
6756  // message.
6757  if (compactProofs.getShortIDs().size() == 0) {
6759  "Got an avaproofs message with no shortid (peer %d)\n",
6760  pfrom.GetId());
6761  return;
6762  }
6763 
6764  // To determine the chance that the number of entries in a bucket
6765  // exceeds N, we use the fact that the number of elements in a single
6766  // bucket is binomially distributed (with n = the number of shorttxids
6767  // S, and p = 1 / the number of buckets), that in the worst case the
6768  // number of buckets is equal to S (due to std::unordered_map having a
6769  // default load factor of 1.0), and that the chance for any bucket to
6770  // exceed N elements is at most buckets * (the chance that any given
6771  // bucket is above N elements). Thus:
6772  // P(max_elements_per_bucket > N) <=
6773  // S * (1 - cdf(binomial(n=S,p=1/S), N))
6774  // If we assume up to 21000000, allowing 15 elements per bucket should
6775  // only fail once per ~2.5 million avaproofs transfers (per peer and
6776  // connection).
6777  // TODO re-evaluate the bucket count to a more realistic value.
6778  // TODO: In the case of a shortid-collision, we should request all the
6779  // proofs which collided. For now, we only request one, which is not
6780  // that bad considering this event is expected to be very rare.
6781  auto shortIdProcessor =
6783  compactProofs.getShortIDs(), 15);
6784 
6785  if (shortIdProcessor.hasOutOfBoundIndex()) {
6786  // This should be catched by deserialization, but catch it here as
6787  // well as a good measure.
6788  Misbehaving(*peer, 100, "avaproofs-bad-indexes");
6789  return;
6790  }
6791  if (!shortIdProcessor.isEvenlyDistributed()) {
6792  // This is suspicious, don't ban but bail out
6793  return;
6794  }
6795 
6796  std::vector<std::pair<avalanche::ProofId, bool>> remoteProofsStatus;
6797  m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
6798  pm.forEachPeer([&](const avalanche::Peer &peer) {
6799  assert(peer.proof);
6800  uint64_t shortid = compactProofs.getShortID(peer.getProofId());
6801 
6802  int added =
6803  shortIdProcessor.matchKnownItem(shortid, peer.proof);
6804 
6805  // No collision
6806  if (added >= 0) {
6807  // Because we know the proof, we can determine if our peer
6808  // has it (added = 1) or not (added = 0) and update the
6809  // remote proof status accordingly.
6810  remoteProofsStatus.emplace_back(peer.getProofId(),
6811  added > 0);
6812  }
6813 
6814  // In order to properly determine which proof is missing, we
6815  // need to keep scanning for all our proofs.
6816  return true;
6817  });
6818  });
6819 
6821  for (size_t i = 0; i < compactProofs.size(); i++) {
6822  if (shortIdProcessor.getItem(i) == nullptr) {
6823  req.indices.push_back(i);
6824  }
6825  }
6826 
6827  m_connman.PushMessage(&pfrom,
6828  msgMaker.Make(NetMsgType::AVAPROOFSREQ, req));
6829 
6830  const NodeId nodeid = pfrom.GetId();
6831 
6832  // We want to keep a count of how many nodes we successfully requested
6833  // avaproofs from as this is used to determine when we are confident our
6834  // quorum is close enough to the other participants.
6835  m_avalanche->avaproofsSent(nodeid);
6836 
6837  // Only save remote proofs from stakers
6838  if (WITH_LOCK(pfrom.cs_avalanche_pubkey,
6839  return pfrom.m_avalanche_pubkey.has_value())) {
6840  m_avalanche->withPeerManager(
6841  [&remoteProofsStatus, nodeid](avalanche::PeerManager &pm) {
6842  for (const auto &[proofid, present] : remoteProofsStatus) {
6843  pm.saveRemoteProof(proofid, nodeid, present);
6844  }
6845  });
6846  }
6847 
6848  return;
6849  }
6850 
6851  if (msg_type == NetMsgType::AVAPROOFSREQ) {
6852  if (peer->m_proof_relay == nullptr) {
6853  return;
6854  }
6855 
6856  avalanche::ProofsRequest proofreq;
6857  vRecv >> proofreq;
6858 
6859  auto requestedIndiceIt = proofreq.indices.begin();
6860  uint32_t treeIndice = 0;
6861  peer->m_proof_relay->sharedProofs.forEachLeaf([&](const auto &proof) {
6862  if (requestedIndiceIt == proofreq.indices.end()) {
6863  // No more indice to process
6864  return false;
6865  }
6866 
6867  if (treeIndice++ == *requestedIndiceIt) {
6868  m_connman.PushMessage(
6869  &pfrom, msgMaker.Make(NetMsgType::AVAPROOF, *proof));
6870  requestedIndiceIt++;
6871  }
6872 
6873  return true;
6874  });
6875 
6876  peer->m_proof_relay->sharedProofs = {};
6877  return;
6878  }
6879 
6880  if (msg_type == NetMsgType::GETADDR) {
6881  // This asymmetric behavior for inbound and outbound connections was
6882  // introduced to prevent a fingerprinting attack: an attacker can send
6883  // specific fake addresses to users' AddrMan and later request them by
6884  // sending getaddr messages. Making nodes which are behind NAT and can
6885  // only make outgoing connections ignore the getaddr message mitigates
6886  // the attack.
6887  if (!pfrom.IsInboundConn()) {
6889  "Ignoring \"getaddr\" from %s connection. peer=%d\n",
6890  pfrom.ConnectionTypeAsString(), pfrom.GetId());
6891  return;
6892  }
6893 
6894  // Since this must be an inbound connection, SetupAddressRelay will
6895  // never fail.
6896  Assume(SetupAddressRelay(pfrom, *peer));
6897 
6898  // Only send one GetAddr response per connection to reduce resource
6899  // waste and discourage addr stamping of INV announcements.
6900  if (peer->m_getaddr_recvd) {
6901  LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n",
6902  pfrom.GetId());
6903  return;
6904  }
6905  peer->m_getaddr_recvd = true;
6906 
6907  peer->m_addrs_to_send.clear();
6908  std::vector<CAddress> vAddr;
6909  const size_t maxAddrToSend = m_opts.max_addr_to_send;
6911  vAddr = m_connman.GetAddresses(maxAddrToSend, MAX_PCT_ADDR_TO_SEND,
6912  /* network */ std::nullopt);
6913  } else {
6914  vAddr = m_connman.GetAddresses(pfrom, maxAddrToSend,
6916  }
6917  for (const CAddress &addr : vAddr) {
6918  PushAddress(*peer, addr);
6919  }
6920  return;
6921  }
6922 
6923  if (msg_type == NetMsgType::GETAVAADDR) {
6924  auto now = GetTime<std::chrono::seconds>();
6925  if (now < pfrom.m_nextGetAvaAddr) {
6926  // Prevent a peer from exhausting our resources by spamming
6927  // getavaaddr messages.
6929  "Ignoring repeated getavaaddr from peer %d\n",
6930  pfrom.GetId());
6931  return;
6932  }
6933 
6934  // Only accept a getavaaddr every GETAVAADDR_INTERVAL at most
6935  pfrom.m_nextGetAvaAddr = now + GETAVAADDR_INTERVAL;
6936 
6937  if (!SetupAddressRelay(pfrom, *peer)) {
6939  "Ignoring getavaaddr message from %s peer=%d\n",
6940  pfrom.ConnectionTypeAsString(), pfrom.GetId());
6941  return;
6942  }
6943 
6944  auto availabilityScoreComparator = [](const CNode *lhs,
6945  const CNode *rhs) {
6946  double scoreLhs = lhs->getAvailabilityScore();
6947  double scoreRhs = rhs->getAvailabilityScore();
6948 
6949  if (scoreLhs != scoreRhs) {
6950  return scoreLhs > scoreRhs;
6951  }
6952 
6953  return lhs < rhs;
6954  };
6955 
6956  // Get up to MAX_ADDR_TO_SEND addresses of the nodes which are the
6957  // most active in the avalanche network. Account for 0 availability as
6958  // well so we can send addresses even if we did not start polling yet.
6959  std::set<const CNode *, decltype(availabilityScoreComparator)> avaNodes(
6960  availabilityScoreComparator);
6961  m_connman.ForEachNode([&](const CNode *pnode) {
6962  if (!pnode->m_avalanche_enabled ||
6963  pnode->getAvailabilityScore() < 0.) {
6964  return;
6965  }
6966 
6967  avaNodes.insert(pnode);
6968  if (avaNodes.size() > m_opts.max_addr_to_send) {
6969  avaNodes.erase(std::prev(avaNodes.end()));
6970  }
6971  });
6972 
6973  peer->m_addrs_to_send.clear();
6974  for (const CNode *pnode : avaNodes) {
6975  PushAddress(*peer, pnode->addr);
6976  }
6977 
6978  return;
6979  }
6980 
6981  if (msg_type == NetMsgType::MEMPOOL) {
6982  if (!(peer->m_our_services & NODE_BLOOM) &&
6986  "mempool request with bloom filters disabled, "
6987  "disconnect peer=%d\n",
6988  pfrom.GetId());
6989  pfrom.fDisconnect = true;
6990  }
6991  return;
6992  }
6993 
6994  if (m_connman.OutboundTargetReached(false) &&
6998  "mempool request with bandwidth limit reached, "
6999  "disconnect peer=%d\n",
7000  pfrom.GetId());
7001  pfrom.fDisconnect = true;
7002  }
7003  return;
7004  }
7005 
7006  if (auto tx_relay = peer->GetTxRelay()) {
7007  LOCK(tx_relay->m_tx_inventory_mutex);
7008  tx_relay->m_send_mempool = true;
7009  }
7010  return;
7011  }
7012 
7013  if (msg_type == NetMsgType::PING) {
7014  if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
7015  uint64_t nonce = 0;
7016  vRecv >> nonce;
7017  // Echo the message back with the nonce. This allows for two useful
7018  // features:
7019  //
7020  // 1) A remote node can quickly check if the connection is
7021  // operational.
7022  // 2) Remote nodes can measure the latency of the network thread. If
7023  // this node is overloaded it won't respond to pings quickly and the
7024  // remote node can avoid sending us more work, like chain download
7025  // requests.
7026  //
7027  // The nonce stops the remote getting confused between different
7028  // pings: without it, if the remote node sends a ping once per
7029  // second and this node takes 5 seconds to respond to each, the 5th
7030  // ping the remote sends would appear to return very quickly.
7031  m_connman.PushMessage(&pfrom,
7032  msgMaker.Make(NetMsgType::PONG, nonce));
7033  }
7034  return;
7035  }
7036 
7037  if (msg_type == NetMsgType::PONG) {
7038  const auto ping_end = time_received;
7039  uint64_t nonce = 0;
7040  size_t nAvail = vRecv.in_avail();
7041  bool bPingFinished = false;
7042  std::string sProblem;
7043 
7044  if (nAvail >= sizeof(nonce)) {
7045  vRecv >> nonce;
7046 
7047  // Only process pong message if there is an outstanding ping (old
7048  // ping without nonce should never pong)
7049  if (peer->m_ping_nonce_sent != 0) {
7050  if (nonce == peer->m_ping_nonce_sent) {
7051  // Matching pong received, this ping is no longer
7052  // outstanding
7053  bPingFinished = true;
7054  const auto ping_time = ping_end - peer->m_ping_start.load();
7055  if (ping_time.count() >= 0) {
7056  // Let connman know about this successful ping-pong
7057  pfrom.PongReceived(ping_time);
7058  } else {
7059  // This should never happen
7060  sProblem = "Timing mishap";
7061  }
7062  } else {
7063  // Nonce mismatches are normal when pings are overlapping
7064  sProblem = "Nonce mismatch";
7065  if (nonce == 0) {
7066  // This is most likely a bug in another implementation
7067  // somewhere; cancel this ping
7068  bPingFinished = true;
7069  sProblem = "Nonce zero";
7070  }
7071  }
7072  } else {
7073  sProblem = "Unsolicited pong without ping";
7074  }
7075  } else {
7076  // This is most likely a bug in another implementation somewhere;
7077  // cancel this ping
7078  bPingFinished = true;
7079  sProblem = "Short payload";
7080  }
7081 
7082  if (!(sProblem.empty())) {
7084  "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
7085  pfrom.GetId(), sProblem, peer->m_ping_nonce_sent, nonce,
7086  nAvail);
7087  }
7088  if (bPingFinished) {
7089  peer->m_ping_nonce_sent = 0;
7090  }
7091  return;
7092  }
7093 
7094  if (msg_type == NetMsgType::FILTERLOAD) {
7095  if (!(peer->m_our_services & NODE_BLOOM)) {
7097  "filterload received despite not offering bloom services "
7098  "from peer=%d; disconnecting\n",
7099  pfrom.GetId());
7100  pfrom.fDisconnect = true;
7101  return;
7102  }
7103  CBloomFilter filter;
7104  vRecv >> filter;
7105 
7106  if (!filter.IsWithinSizeConstraints()) {
7107  // There is no excuse for sending a too-large filter
7108  Misbehaving(*peer, 100, "too-large bloom filter");
7109  } else if (auto tx_relay = peer->GetTxRelay()) {
7110  {
7111  LOCK(tx_relay->m_bloom_filter_mutex);
7112  tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
7113  tx_relay->m_relay_txs = true;
7114  }
7115  pfrom.m_bloom_filter_loaded = true;
7116  }
7117  return;
7118  }
7119 
7120  if (msg_type == NetMsgType::FILTERADD) {
7121  if (!(peer->m_our_services & NODE_BLOOM)) {
7123  "filteradd received despite not offering bloom services "
7124  "from peer=%d; disconnecting\n",
7125  pfrom.GetId());
7126  pfrom.fDisconnect = true;
7127  return;
7128  }
7129  std::vector<uint8_t> vData;
7130  vRecv >> vData;
7131 
7132  // Nodes must NEVER send a data item > 520 bytes (the max size for a
7133  // script data object, and thus, the maximum size any matched object can
7134  // have) in a filteradd message.
7135  bool bad = false;
7136  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
7137  bad = true;
7138  } else if (auto tx_relay = peer->GetTxRelay()) {
7139  LOCK(tx_relay->m_bloom_filter_mutex);
7140  if (tx_relay->m_bloom_filter) {
7141  tx_relay->m_bloom_filter->insert(vData);
7142  } else {
7143  bad = true;
7144  }
7145  }
7146  if (bad) {
7147  // The structure of this code doesn't really allow for a good error
7148  // code. We'll go generic.
7149  Misbehaving(*peer, 100, "bad filteradd message");
7150  }
7151  return;
7152  }
7153 
7154  if (msg_type == NetMsgType::FILTERCLEAR) {
7155  if (!(peer->m_our_services & NODE_BLOOM)) {
7157  "filterclear received despite not offering bloom services "
7158  "from peer=%d; disconnecting\n",
7159  pfrom.GetId());
7160  pfrom.fDisconnect = true;
7161  return;
7162  }
7163  auto tx_relay = peer->GetTxRelay();
7164  if (!tx_relay) {
7165  return;
7166  }
7167 
7168  {
7169  LOCK(tx_relay->m_bloom_filter_mutex);
7170  tx_relay->m_bloom_filter = nullptr;
7171  tx_relay->m_relay_txs = true;
7172  }
7173  pfrom.m_bloom_filter_loaded = false;
7174  pfrom.m_relays_txs = true;
7175  return;
7176  }
7177 
7178  if (msg_type == NetMsgType::FEEFILTER) {
7179  Amount newFeeFilter = Amount::zero();
7180  vRecv >> newFeeFilter;
7181  if (MoneyRange(newFeeFilter)) {
7182  if (auto tx_relay = peer->GetTxRelay()) {
7183  tx_relay->m_fee_filter_received = newFeeFilter;
7184  }
7185  LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n",
7186  CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
7187  }
7188  return;
7189  }
7190 
7191  if (msg_type == NetMsgType::GETCFILTERS) {
7192  ProcessGetCFilters(pfrom, *peer, vRecv);
7193  return;
7194  }
7195 
7196  if (msg_type == NetMsgType::GETCFHEADERS) {
7197  ProcessGetCFHeaders(pfrom, *peer, vRecv);
7198  return;
7199  }
7200 
7201  if (msg_type == NetMsgType::GETCFCHECKPT) {
7202  ProcessGetCFCheckPt(pfrom, *peer, vRecv);
7203  return;
7204  }
7205 
7206  if (msg_type == NetMsgType::NOTFOUND) {
7207  std::vector<CInv> vInv;
7208  vRecv >> vInv;
7209  // A peer might send up to 1 notfound per getdata request, but no more
7210  if (vInv.size() <= PROOF_REQUEST_PARAMS.max_peer_announcements +
7213  for (CInv &inv : vInv) {
7214  if (inv.IsMsgTx()) {
7215  // If we receive a NOTFOUND message for a tx we requested,
7216  // mark the announcement for it as completed in
7217  // InvRequestTracker.
7218  LOCK(::cs_main);
7219  m_txrequest.ReceivedResponse(pfrom.GetId(), TxId(inv.hash));
7220  continue;
7221  }
7222  if (inv.IsMsgProof()) {
7223  LOCK(cs_proofrequest);
7224  m_proofrequest.ReceivedResponse(
7225  pfrom.GetId(), avalanche::ProofId(inv.hash));
7226  }
7227  }
7228  }
7229  return;
7230  }
7231 
7232  // Ignore unknown commands for extensibility
7233  LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n",
7234  SanitizeString(msg_type), pfrom.GetId());
7235  return;
7236 }
7237 
7238 bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode &pnode, Peer &peer) {
7239  {
7240  LOCK(peer.m_misbehavior_mutex);
7241 
7242  // There's nothing to do if the m_should_discourage flag isn't set
7243  if (!peer.m_should_discourage) {
7244  return false;
7245  }
7246 
7247  peer.m_should_discourage = false;
7248  } // peer.m_misbehavior_mutex
7249 
7251  // We never disconnect or discourage peers for bad behavior if they have
7252  // NetPermissionFlags::NoBan permission
7253  LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id);
7254  return false;
7255  }
7256 
7257  if (pnode.IsManualConn()) {
7258  // We never disconnect or discourage manual peers for bad behavior
7259  LogPrintf("Warning: not punishing manually connected peer %d!\n",
7260  peer.m_id);
7261  return false;
7262  }
7263 
7264  if (pnode.addr.IsLocal()) {
7265  // We disconnect local peers for bad behavior but don't discourage
7266  // (since that would discourage all peers on the same local address)
7268  "Warning: disconnecting but not discouraging %s peer %d!\n",
7269  pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
7270  pnode.fDisconnect = true;
7271  return true;
7272  }
7273 
7274  // Normal case: Disconnect the peer and discourage all nodes sharing the
7275  // address
7276  LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n",
7277  peer.m_id);
7278  if (m_banman) {
7279  m_banman->Discourage(pnode.addr);
7280  }
7281  m_connman.DisconnectNode(pnode.addr);
7282  return true;
7283 }
7284 
7285 bool PeerManagerImpl::ProcessMessages(const Config &config, CNode *pfrom,
7286  std::atomic<bool> &interruptMsgProc) {
7287  AssertLockHeld(g_msgproc_mutex);
7288 
7289  //
7290  // Message format
7291  // (4) message start
7292  // (12) command
7293  // (4) size
7294  // (4) checksum
7295  // (x) data
7296  //
7297  bool fMoreWork = false;
7298 
7299  PeerRef peer = GetPeerRef(pfrom->GetId());
7300  if (peer == nullptr) {
7301  return false;
7302  }
7303 
7304  {
7305  LOCK(peer->m_getdata_requests_mutex);
7306  if (!peer->m_getdata_requests.empty()) {
7307  ProcessGetData(config, *pfrom, *peer, interruptMsgProc);
7308  }
7309  }
7310 
7311  const bool processed_orphan = ProcessOrphanTx(config, *peer);
7312 
7313  if (pfrom->fDisconnect) {
7314  return false;
7315  }
7316 
7317  if (processed_orphan) {
7318  return true;
7319  }
7320 
7321  // this maintains the order of responses and prevents m_getdata_requests to
7322  // grow unbounded
7323  {
7324  LOCK(peer->m_getdata_requests_mutex);
7325  if (!peer->m_getdata_requests.empty()) {
7326  return true;
7327  }
7328  }
7329 
7330  // Don't bother if send buffer is too full to respond anyway
7331  if (pfrom->fPauseSend) {
7332  return false;
7333  }
7334 
7335  std::list<CNetMessage> msgs;
7336  {
7337  LOCK(pfrom->cs_vProcessMsg);
7338  if (pfrom->vProcessMsg.empty()) {
7339  return false;
7340  }
7341  // Just take one message
7342  msgs.splice(msgs.begin(), pfrom->vProcessMsg,
7343  pfrom->vProcessMsg.begin());
7344  pfrom->nProcessQueueSize -= msgs.front().m_raw_message_size;
7345  pfrom->fPauseRecv =
7346  pfrom->nProcessQueueSize > m_connman.GetReceiveFloodSize();
7347  fMoreWork = !pfrom->vProcessMsg.empty();
7348  }
7349  CNetMessage &msg(msgs.front());
7350 
7351  TRACE6(net, inbound_message, pfrom->GetId(), pfrom->m_addr_name.c_str(),
7352  pfrom->ConnectionTypeAsString().c_str(), msg.m_type.c_str(),
7353  msg.m_recv.size(), msg.m_recv.data());
7354 
7355  if (m_opts.capture_messages) {
7356  CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv),
7357  /*is_incoming=*/true);
7358  }
7359 
7360  msg.SetVersion(pfrom->GetCommonVersion());
7361 
7362  // Check network magic
7363  if (!msg.m_valid_netmagic) {
7365  "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n",
7366  SanitizeString(msg.m_type), pfrom->GetId());
7367 
7368  // Make sure we discourage where that come from for some time.
7369  if (m_banman) {
7370  m_banman->Discourage(pfrom->addr);
7371  }
7372  m_connman.DisconnectNode(pfrom->addr);
7373 
7374  pfrom->fDisconnect = true;
7375  return false;
7376  }
7377 
7378  // Check header
7379  if (!msg.m_valid_header) {
7380  LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n",
7381  SanitizeString(msg.m_type), pfrom->GetId());
7382  return fMoreWork;
7383  }
7384 
7385  // Checksum
7386  CDataStream &vRecv = msg.m_recv;
7387  if (!msg.m_valid_checksum) {
7388  LogPrint(BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR peer=%d\n",
7389  __func__, SanitizeString(msg.m_type), msg.m_message_size,
7390  pfrom->GetId());
7391  if (m_banman) {
7392  m_banman->Discourage(pfrom->addr);
7393  }
7394  m_connman.DisconnectNode(pfrom->addr);
7395  return fMoreWork;
7396  }
7397 
7398  try {
7399  ProcessMessage(config, *pfrom, msg.m_type, vRecv, msg.m_time,
7400  interruptMsgProc);
7401  if (interruptMsgProc) {
7402  return false;
7403  }
7404 
7405  {
7406  LOCK(peer->m_getdata_requests_mutex);
7407  if (!peer->m_getdata_requests.empty()) {
7408  fMoreWork = true;
7409  }
7410  }
7411  // Does this peer has an orphan ready to reconsider?
7412  // (Note: we may have provided a parent for an orphan provided by
7413  // another peer that was already processed; in that case, the extra work
7414  // may not be noticed, possibly resulting in an unnecessary 100ms delay)
7415  if (m_orphanage.HaveTxToReconsider(peer->m_id)) {
7416  fMoreWork = true;
7417  }
7418  } catch (const std::exception &e) {
7419  LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n",
7420  __func__, SanitizeString(msg.m_type), msg.m_message_size,
7421  e.what(), typeid(e).name());
7422  } catch (...) {
7423  LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n",
7424  __func__, SanitizeString(msg.m_type), msg.m_message_size);
7425  }
7426 
7427  return fMoreWork;
7428 }
7429 
7430 void PeerManagerImpl::ConsiderEviction(CNode &pto, Peer &peer,
7431  std::chrono::seconds time_in_seconds) {
7433 
7434  CNodeState &state = *State(pto.GetId());
7435  const CNetMsgMaker msgMaker(pto.GetCommonVersion());
7436 
7437  if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() &&
7438  state.fSyncStarted) {
7439  // This is an outbound peer subject to disconnection if they don't
7440  // announce a block with as much work as the current tip within
7441  // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if their
7442  // chain has more work than ours, we should sync to it, unless it's
7443  // invalid, in which case we should find that out and disconnect from
7444  // them elsewhere).
7445  if (state.pindexBestKnownBlock != nullptr &&
7446  state.pindexBestKnownBlock->nChainWork >=
7447  m_chainman.ActiveChain().Tip()->nChainWork) {
7448  if (state.m_chain_sync.m_timeout != 0s) {
7449  state.m_chain_sync.m_timeout = 0s;
7450  state.m_chain_sync.m_work_header = nullptr;
7451  state.m_chain_sync.m_sent_getheaders = false;
7452  }
7453  } else if (state.m_chain_sync.m_timeout == 0s ||
7454  (state.m_chain_sync.m_work_header != nullptr &&
7455  state.pindexBestKnownBlock != nullptr &&
7456  state.pindexBestKnownBlock->nChainWork >=
7457  state.m_chain_sync.m_work_header->nChainWork)) {
7458  // Our best block known by this peer is behind our tip, and we're
7459  // either noticing that for the first time, OR this peer was able to
7460  // catch up to some earlier point where we checked against our tip.
7461  // Either way, set a new timeout based on current tip.
7462  state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
7463  state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
7464  state.m_chain_sync.m_sent_getheaders = false;
7465  } else if (state.m_chain_sync.m_timeout > 0s &&
7466  time_in_seconds > state.m_chain_sync.m_timeout) {
7467  // No evidence yet that our peer has synced to a chain with work
7468  // equal to that of our tip, when we first detected it was behind.
7469  // Send a single getheaders message to give the peer a chance to
7470  // update us.
7471  if (state.m_chain_sync.m_sent_getheaders) {
7472  // They've run out of time to catch up!
7473  LogPrintf(
7474  "Disconnecting outbound peer %d for old chain, best known "
7475  "block = %s\n",
7476  pto.GetId(),
7477  state.pindexBestKnownBlock != nullptr
7478  ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7479  : "<none>");
7480  pto.fDisconnect = true;
7481  } else {
7482  assert(state.m_chain_sync.m_work_header);
7483  // Here, we assume that the getheaders message goes out,
7484  // because it'll either go out or be skipped because of a
7485  // getheaders in-flight already, in which case the peer should
7486  // still respond to us with a sufficiently high work chain tip.
7487  MaybeSendGetHeaders(
7488  pto, GetLocator(state.m_chain_sync.m_work_header->pprev),
7489  peer);
7490  LogPrint(
7491  BCLog::NET,
7492  "sending getheaders to outbound peer=%d to verify chain "
7493  "work (current best known block:%s, benchmark blockhash: "
7494  "%s)\n",
7495  pto.GetId(),
7496  state.pindexBestKnownBlock != nullptr
7497  ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7498  : "<none>",
7499  state.m_chain_sync.m_work_header->GetBlockHash()
7500  .ToString());
7501  state.m_chain_sync.m_sent_getheaders = true;
7502  // Bump the timeout to allow a response, which could clear the
7503  // timeout (if the response shows the peer has synced), reset
7504  // the timeout (if the peer syncs to the required work but not
7505  // to our tip), or result in disconnect (if we advance to the
7506  // timeout and pindexBestKnownBlock has not sufficiently
7507  // progressed)
7508  state.m_chain_sync.m_timeout =
7509  time_in_seconds + HEADERS_RESPONSE_TIME;
7510  }
7511  }
7512  }
7513 }
7514 
7515 void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) {
7516  // If we have any extra block-relay-only peers, disconnect the youngest
7517  // unless it's given us a block -- in which case, compare with the
7518  // second-youngest, and out of those two, disconnect the peer who least
7519  // recently gave us a block.
7520  // The youngest block-relay-only peer would be the extra peer we connected
7521  // to temporarily in order to sync our tip; see net.cpp.
7522  // Note that we use higher nodeid as a measure for most recent connection.
7523  if (m_connman.GetExtraBlockRelayCount() > 0) {
7524  std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0},
7525  next_youngest_peer{-1, 0};
7526 
7527  m_connman.ForEachNode([&](CNode *pnode) {
7528  if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) {
7529  return;
7530  }
7531  if (pnode->GetId() > youngest_peer.first) {
7532  next_youngest_peer = youngest_peer;
7533  youngest_peer.first = pnode->GetId();
7534  youngest_peer.second = pnode->m_last_block_time;
7535  }
7536  });
7537 
7538  NodeId to_disconnect = youngest_peer.first;
7539  if (youngest_peer.second > next_youngest_peer.second) {
7540  // Our newest block-relay-only peer gave us a block more recently;
7541  // disconnect our second youngest.
7542  to_disconnect = next_youngest_peer.first;
7543  }
7544 
7545  m_connman.ForNode(
7546  to_disconnect,
7547  [&](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
7549  // Make sure we're not getting a block right now, and that we've
7550  // been connected long enough for this eviction to happen at
7551  // all. Note that we only request blocks from a peer if we learn
7552  // of a valid headers chain with at least as much work as our
7553  // tip.
7554  CNodeState *node_state = State(pnode->GetId());
7555  if (node_state == nullptr ||
7556  (now - pnode->m_connected >= MINIMUM_CONNECT_TIME &&
7557  node_state->nBlocksInFlight == 0)) {
7558  pnode->fDisconnect = true;
7560  "disconnecting extra block-relay-only peer=%d "
7561  "(last block received at time %d)\n",
7562  pnode->GetId(),
7564  return true;
7565  } else {
7566  LogPrint(
7567  BCLog::NET,
7568  "keeping block-relay-only peer=%d chosen for eviction "
7569  "(connect time: %d, blocks_in_flight: %d)\n",
7570  pnode->GetId(), count_seconds(pnode->m_connected),
7571  node_state->nBlocksInFlight);
7572  }
7573  return false;
7574  });
7575  }
7576 
7577  // Check whether we have too many OUTBOUND_FULL_RELAY peers
7578  if (m_connman.GetExtraFullOutboundCount() <= 0) {
7579  return;
7580  }
7581 
7582  // If we have more OUTBOUND_FULL_RELAY peers than we target, disconnect one.
7583  // Pick the OUTBOUND_FULL_RELAY peer that least recently announced us a new
7584  // block, with ties broken by choosing the more recent connection (higher
7585  // node id)
7586  NodeId worst_peer = -1;
7587  int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
7588 
7589  m_connman.ForEachNode([&](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(
7590  ::cs_main) {
7592 
7593  // Only consider OUTBOUND_FULL_RELAY peers that are not already marked
7594  // for disconnection
7595  if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) {
7596  return;
7597  }
7598  CNodeState *state = State(pnode->GetId());
7599  if (state == nullptr) {
7600  // shouldn't be possible, but just in case
7601  return;
7602  }
7603  // Don't evict our protected peers
7604  if (state->m_chain_sync.m_protect) {
7605  return;
7606  }
7607  if (state->m_last_block_announcement < oldest_block_announcement ||
7608  (state->m_last_block_announcement == oldest_block_announcement &&
7609  pnode->GetId() > worst_peer)) {
7610  worst_peer = pnode->GetId();
7611  oldest_block_announcement = state->m_last_block_announcement;
7612  }
7613  });
7614 
7615  if (worst_peer == -1) {
7616  return;
7617  }
7618 
7619  bool disconnected = m_connman.ForNode(
7620  worst_peer, [&](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
7622 
7623  // Only disconnect a peer that has been connected to us for some
7624  // reasonable fraction of our check-frequency, to give it time for
7625  // new information to have arrived. Also don't disconnect any peer
7626  // we're trying to download a block from.
7627  CNodeState &state = *State(pnode->GetId());
7628  if (now - pnode->m_connected > MINIMUM_CONNECT_TIME &&
7629  state.nBlocksInFlight == 0) {
7631  "disconnecting extra outbound peer=%d (last block "
7632  "announcement received at time %d)\n",
7633  pnode->GetId(), oldest_block_announcement);
7634  pnode->fDisconnect = true;
7635  return true;
7636  } else {
7638  "keeping outbound peer=%d chosen for eviction "
7639  "(connect time: %d, blocks_in_flight: %d)\n",
7640  pnode->GetId(), count_seconds(pnode->m_connected),
7641  state.nBlocksInFlight);
7642  return false;
7643  }
7644  });
7645 
7646  if (disconnected) {
7647  // If we disconnected an extra peer, that means we successfully
7648  // connected to at least one peer after the last time we detected a
7649  // stale tip. Don't try any more extra peers until we next detect a
7650  // stale tip, to limit the load we put on the network from these extra
7651  // connections.
7652  m_connman.SetTryNewOutboundPeer(false);
7653  }
7654 }
7655 
7656 void PeerManagerImpl::CheckForStaleTipAndEvictPeers() {
7657  LOCK(cs_main);
7658 
7659  auto now{GetTime<std::chrono::seconds>()};
7660 
7661  EvictExtraOutboundPeers(now);
7662 
7663  if (now > m_stale_tip_check_time) {
7664  // Check whether our tip is stale, and if so, allow using an extra
7665  // outbound peer.
7666  if (!m_chainman.m_blockman.LoadingBlocks() &&
7667  m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() &&
7668  TipMayBeStale()) {
7669  LogPrintf("Potential stale tip detected, will try using extra "
7670  "outbound peer (last tip update: %d seconds ago)\n",
7671  count_seconds(now - m_last_tip_update.load()));
7672  m_connman.SetTryNewOutboundPeer(true);
7673  } else if (m_connman.GetTryNewOutboundPeer()) {
7674  m_connman.SetTryNewOutboundPeer(false);
7675  }
7676  m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
7677  }
7678 
7679  if (!m_initial_sync_finished && CanDirectFetch()) {
7680  m_connman.StartExtraBlockRelayPeers();
7681  m_initial_sync_finished = true;
7682  }
7683 }
7684 
7685 void PeerManagerImpl::MaybeSendPing(CNode &node_to, Peer &peer,
7686  std::chrono::microseconds now) {
7687  if (m_connman.ShouldRunInactivityChecks(
7688  node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
7689  peer.m_ping_nonce_sent &&
7690  now > peer.m_ping_start.load() + TIMEOUT_INTERVAL) {
7691  // The ping timeout is using mocktime. To disable the check during
7692  // testing, increase -peertimeout.
7693  LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n",
7694  0.000001 * count_microseconds(now - peer.m_ping_start.load()),
7695  peer.m_id);
7696  node_to.fDisconnect = true;
7697  return;
7698  }
7699 
7700  const CNetMsgMaker msgMaker(node_to.GetCommonVersion());
7701  bool pingSend = false;
7702 
7703  if (peer.m_ping_queued) {
7704  // RPC ping request by user
7705  pingSend = true;
7706  }
7707 
7708  if (peer.m_ping_nonce_sent == 0 &&
7709  now > peer.m_ping_start.load() + PING_INTERVAL) {
7710  // Ping automatically sent as a latency probe & keepalive.
7711  pingSend = true;
7712  }
7713 
7714  if (pingSend) {
7715  uint64_t nonce;
7716  do {
7717  nonce = GetRand<uint64_t>();
7718  } while (nonce == 0);
7719  peer.m_ping_queued = false;
7720  peer.m_ping_start = now;
7721  if (node_to.GetCommonVersion() > BIP0031_VERSION) {
7722  peer.m_ping_nonce_sent = nonce;
7723  m_connman.PushMessage(&node_to,
7724  msgMaker.Make(NetMsgType::PING, nonce));
7725  } else {
7726  // Peer is too old to support ping command with nonce, pong will
7727  // never arrive.
7728  peer.m_ping_nonce_sent = 0;
7729  m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING));
7730  }
7731  }
7732 }
7733 
7734 void PeerManagerImpl::MaybeSendAddr(CNode &node, Peer &peer,
7735  std::chrono::microseconds current_time) {
7736  // Nothing to do for non-address-relay peers
7737  if (!peer.m_addr_relay_enabled) {
7738  return;
7739  }
7740 
7741  LOCK(peer.m_addr_send_times_mutex);
7742  if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
7743  peer.m_next_local_addr_send < current_time) {
7744  // If we've sent before, clear the bloom filter for the peer, so
7745  // that our self-announcement will actually go out. This might
7746  // be unnecessary if the bloom filter has already rolled over
7747  // since our last self-announcement, but there is only a small
7748  // bandwidth cost that we can incur by doing this (which happens
7749  // once a day on average).
7750  if (peer.m_next_local_addr_send != 0us) {
7751  peer.m_addr_known->reset();
7752  }
7753  if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
7754  CAddress local_addr{*local_service, peer.m_our_services,
7755  AdjustedTime()};
7756  PushAddress(peer, local_addr);
7757  }
7758  peer.m_next_local_addr_send = GetExponentialRand(
7759  current_time, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
7760  }
7761 
7762  // We sent an `addr` message to this peer recently. Nothing more to do.
7763  if (current_time <= peer.m_next_addr_send) {
7764  return;
7765  }
7766 
7767  peer.m_next_addr_send =
7769 
7770  const size_t max_addr_to_send = m_opts.max_addr_to_send;
7771  if (!Assume(peer.m_addrs_to_send.size() <= max_addr_to_send)) {
7772  // Should be impossible since we always check size before adding to
7773  // m_addrs_to_send. Recover by trimming the vector.
7774  peer.m_addrs_to_send.resize(max_addr_to_send);
7775  }
7776 
7777  // Remove addr records that the peer already knows about, and add new
7778  // addrs to the m_addr_known filter on the same pass.
7779  auto addr_already_known =
7780  [&peer](const CAddress &addr)
7781  EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) {
7782  bool ret = peer.m_addr_known->contains(addr.GetKey());
7783  if (!ret) {
7784  peer.m_addr_known->insert(addr.GetKey());
7785  }
7786  return ret;
7787  };
7788  peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(),
7789  peer.m_addrs_to_send.end(),
7790  addr_already_known),
7791  peer.m_addrs_to_send.end());
7792 
7793  // No addr messages to send
7794  if (peer.m_addrs_to_send.empty()) {
7795  return;
7796  }
7797 
7798  const char *msg_type;
7799  int make_flags;
7800  if (peer.m_wants_addrv2) {
7801  msg_type = NetMsgType::ADDRV2;
7802  make_flags = ADDRV2_FORMAT;
7803  } else {
7804  msg_type = NetMsgType::ADDR;
7805  make_flags = 0;
7806  }
7807  m_connman.PushMessage(
7808  &node, CNetMsgMaker(node.GetCommonVersion())
7809  .Make(make_flags, msg_type, peer.m_addrs_to_send));
7810  peer.m_addrs_to_send.clear();
7811 
7812  // we only send the big addr message once
7813  if (peer.m_addrs_to_send.capacity() > 40) {
7814  peer.m_addrs_to_send.shrink_to_fit();
7815  }
7816 }
7817 
7818 void PeerManagerImpl::MaybeSendSendHeaders(CNode &node, Peer &peer) {
7819  // Delay sending SENDHEADERS (BIP 130) until we're done with an
7820  // initial-headers-sync with this peer. Receiving headers announcements for
7821  // new blocks while trying to sync their headers chain is problematic,
7822  // because of the state tracking done.
7823  if (!peer.m_sent_sendheaders &&
7824  node.GetCommonVersion() >= SENDHEADERS_VERSION) {
7825  LOCK(cs_main);
7826  CNodeState &state = *State(node.GetId());
7827  if (state.pindexBestKnownBlock != nullptr &&
7828  state.pindexBestKnownBlock->nChainWork >
7829  m_chainman.MinimumChainWork()) {
7830  // Tell our peer we prefer to receive headers rather than inv's
7831  // We send this to non-NODE NETWORK peers as well, because even
7832  // non-NODE NETWORK peers can announce blocks (such as pruning
7833  // nodes)
7834  m_connman.PushMessage(&node, CNetMsgMaker(node.GetCommonVersion())
7836  peer.m_sent_sendheaders = true;
7837  }
7838  }
7839 }
7840 
7841 void PeerManagerImpl::MaybeSendFeefilter(
7842  CNode &pto, Peer &peer, std::chrono::microseconds current_time) {
7843  if (m_opts.ignore_incoming_txs) {
7844  return;
7845  }
7846  if (pto.GetCommonVersion() < FEEFILTER_VERSION) {
7847  return;
7848  }
7849  // peers with the forcerelay permission should not filter txs to us
7851  return;
7852  }
7853  // Don't send feefilter messages to outbound block-relay-only peers since
7854  // they should never announce transactions to us, regardless of feefilter
7855  // state.
7856  if (pto.IsBlockOnlyConn()) {
7857  return;
7858  }
7859 
7860  Amount currentFilter = m_mempool.GetMinFee().GetFeePerK();
7861 
7862  if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
7863  // Received tx-inv messages are discarded when the active
7864  // chainstate is in IBD, so tell the peer to not send them.
7865  currentFilter = MAX_MONEY;
7866  } else {
7867  static const Amount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)};
7868  if (peer.m_fee_filter_sent == MAX_FILTER) {
7869  // Send the current filter if we sent MAX_FILTER previously
7870  // and made it out of IBD.
7871  peer.m_next_send_feefilter = 0us;
7872  }
7873  }
7874  if (current_time > peer.m_next_send_feefilter) {
7875  Amount filterToSend = m_fee_filter_rounder.round(currentFilter);
7876  // We always have a fee filter of at least the min relay fee
7877  filterToSend =
7878  std::max(filterToSend, m_mempool.m_min_relay_feerate.GetFeePerK());
7879  if (filterToSend != peer.m_fee_filter_sent) {
7880  m_connman.PushMessage(
7881  &pto, CNetMsgMaker(pto.GetCommonVersion())
7882  .Make(NetMsgType::FEEFILTER, filterToSend));
7883  peer.m_fee_filter_sent = filterToSend;
7884  }
7885  peer.m_next_send_feefilter =
7887  }
7888  // If the fee filter has changed substantially and it's still more than
7889  // MAX_FEEFILTER_CHANGE_DELAY until scheduled broadcast, then move the
7890  // broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
7891  else if (current_time + MAX_FEEFILTER_CHANGE_DELAY <
7892  peer.m_next_send_feefilter &&
7893  (currentFilter < 3 * peer.m_fee_filter_sent / 4 ||
7894  currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
7895  peer.m_next_send_feefilter =
7896  current_time + GetRandomDuration<std::chrono::microseconds>(
7898  }
7899 }
7900 
7901 namespace {
7902 class CompareInvMempoolOrder {
7903  CTxMemPool *mp;
7904 
7905 public:
7906  explicit CompareInvMempoolOrder(CTxMemPool *_mempool) : mp(_mempool) {}
7907 
7908  bool operator()(std::set<TxId>::iterator a, std::set<TxId>::iterator b) {
7913  return mp->CompareTopologically(*b, *a);
7914  }
7915 };
7916 } // namespace
7917 
7918 bool PeerManagerImpl::SetupAddressRelay(const CNode &node, Peer &peer) {
7919  // We don't participate in addr relay with outbound block-relay-only
7920  // connections to prevent providing adversaries with the additional
7921  // information of addr traffic to infer the link.
7922  if (node.IsBlockOnlyConn()) {
7923  return false;
7924  }
7925 
7926  if (!peer.m_addr_relay_enabled.exchange(true)) {
7927  // First addr message we have received from the peer, initialize
7928  // m_addr_known
7929  peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
7930  }
7931 
7932  return true;
7933 }
7934 
7935 bool PeerManagerImpl::SendMessages(const Config &config, CNode *pto) {
7936  AssertLockHeld(g_msgproc_mutex);
7937 
7938  PeerRef peer = GetPeerRef(pto->GetId());
7939  if (!peer) {
7940  return false;
7941  }
7942  const Consensus::Params &consensusParams = m_chainparams.GetConsensus();
7943 
7944  // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
7945  // disconnect misbehaving peers even before the version handshake is
7946  // complete.
7947  if (MaybeDiscourageAndDisconnect(*pto, *peer)) {
7948  return true;
7949  }
7950 
7951  // Don't send anything until the version handshake is complete
7952  if (!pto->fSuccessfullyConnected || pto->fDisconnect) {
7953  return true;
7954  }
7955 
7956  // If we get here, the outgoing message serialization version is set and
7957  // can't change.
7958  const CNetMsgMaker msgMaker(pto->GetCommonVersion());
7959 
7960  const auto current_time{GetTime<std::chrono::microseconds>()};
7961 
7962  if (pto->IsAddrFetchConn() &&
7963  current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
7965  "addrfetch connection timeout; disconnecting peer=%d\n",
7966  pto->GetId());
7967  pto->fDisconnect = true;
7968  return true;
7969  }
7970 
7971  MaybeSendPing(*pto, *peer, current_time);
7972 
7973  // MaybeSendPing may have marked peer for disconnection
7974  if (pto->fDisconnect) {
7975  return true;
7976  }
7977 
7978  bool sync_blocks_and_headers_from_peer = false;
7979 
7980  MaybeSendAddr(*pto, *peer, current_time);
7981 
7982  MaybeSendSendHeaders(*pto, *peer);
7983 
7984  {
7985  LOCK(cs_main);
7986 
7987  CNodeState &state = *State(pto->GetId());
7988 
7989  // Start block sync
7990  if (m_chainman.m_best_header == nullptr) {
7991  m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
7992  }
7993 
7994  // Determine whether we might try initial headers sync or parallel
7995  // block download from this peer -- this mostly affects behavior while
7996  // in IBD (once out of IBD, we sync from all peers).
7997  if (state.fPreferredDownload) {
7998  sync_blocks_and_headers_from_peer = true;
7999  } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) {
8000  // Typically this is an inbound peer. If we don't have any outbound
8001  // peers, or if we aren't downloading any blocks from such peers,
8002  // then allow block downloads from this peer, too.
8003  // We prefer downloading blocks from outbound peers to avoid
8004  // putting undue load on (say) some home user who is just making
8005  // outbound connections to the network, but if our only source of
8006  // the latest blocks is from an inbound peer, we have to be sure to
8007  // eventually download it (and not just wait indefinitely for an
8008  // outbound peer to have it).
8009  if (m_num_preferred_download_peers == 0 ||
8010  mapBlocksInFlight.empty()) {
8011  sync_blocks_and_headers_from_peer = true;
8012  }
8013  }
8014 
8015  if (!state.fSyncStarted && CanServeBlocks(*peer) &&
8016  !m_chainman.m_blockman.LoadingBlocks()) {
8017  // Only actively request headers from a single peer, unless we're
8018  // close to today.
8019  if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) ||
8020  m_chainman.m_best_header->Time() > GetAdjustedTime() - 24h) {
8021  const CBlockIndex *pindexStart = m_chainman.m_best_header;
8030  if (pindexStart->pprev) {
8031  pindexStart = pindexStart->pprev;
8032  }
8033  if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) {
8034  LogPrint(
8035  BCLog::NET,
8036  "initial getheaders (%d) to peer=%d (startheight:%d)\n",
8037  pindexStart->nHeight, pto->GetId(),
8038  peer->m_starting_height);
8039 
8040  state.fSyncStarted = true;
8041  peer->m_headers_sync_timeout =
8042  current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
8043  (
8044  // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to
8045  // microseconds before scaling to maintain precision
8046  std::chrono::microseconds{
8048  Ticks<std::chrono::seconds>(
8049  GetAdjustedTime() -
8050  m_chainman.m_best_header->Time()) /
8051  consensusParams.nPowTargetSpacing);
8052  nSyncStarted++;
8053  }
8054  }
8055  }
8056 
8057  //
8058  // Try sending block announcements via headers
8059  //
8060  {
8061  // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our list of block
8062  // hashes we're relaying, and our peer wants headers announcements,
8063  // then find the first header not yet known to our peer but would
8064  // connect, and send. If no header would connect, or if we have too
8065  // many blocks, or if the peer doesn't want headers, just add all to
8066  // the inv queue.
8067  LOCK(peer->m_block_inv_mutex);
8068  std::vector<CBlock> vHeaders;
8069  bool fRevertToInv =
8070  ((!peer->m_prefers_headers &&
8071  (!state.m_requested_hb_cmpctblocks ||
8072  peer->m_blocks_for_headers_relay.size() > 1)) ||
8073  peer->m_blocks_for_headers_relay.size() >
8075  // last header queued for delivery
8076  const CBlockIndex *pBestIndex = nullptr;
8077  // ensure pindexBestKnownBlock is up-to-date
8078  ProcessBlockAvailability(pto->GetId());
8079 
8080  if (!fRevertToInv) {
8081  bool fFoundStartingHeader = false;
8082  // Try to find first header that our peer doesn't have, and then
8083  // send all headers past that one. If we come across an headers
8084  // that aren't on m_chainman.ActiveChain(), give up.
8085  for (const BlockHash &hash : peer->m_blocks_for_headers_relay) {
8086  const CBlockIndex *pindex =
8087  m_chainman.m_blockman.LookupBlockIndex(hash);
8088  assert(pindex);
8089  if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
8090  // Bail out if we reorged away from this block
8091  fRevertToInv = true;
8092  break;
8093  }
8094  if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
8095  // This means that the list of blocks to announce don't
8096  // connect to each other. This shouldn't really be
8097  // possible to hit during regular operation (because
8098  // reorgs should take us to a chain that has some block
8099  // not on the prior chain, which should be caught by the
8100  // prior check), but one way this could happen is by
8101  // using invalidateblock / reconsiderblock repeatedly on
8102  // the tip, causing it to be added multiple times to
8103  // m_blocks_for_headers_relay. Robustly deal with this
8104  // rare situation by reverting to an inv.
8105  fRevertToInv = true;
8106  break;
8107  }
8108  pBestIndex = pindex;
8109  if (fFoundStartingHeader) {
8110  // add this to the headers message
8111  vHeaders.push_back(pindex->GetBlockHeader());
8112  } else if (PeerHasHeader(&state, pindex)) {
8113  // Keep looking for the first new block.
8114  continue;
8115  } else if (pindex->pprev == nullptr ||
8116  PeerHasHeader(&state, pindex->pprev)) {
8117  // Peer doesn't have this header but they do have the
8118  // prior one. Start sending headers.
8119  fFoundStartingHeader = true;
8120  vHeaders.push_back(pindex->GetBlockHeader());
8121  } else {
8122  // Peer doesn't have this header or the prior one --
8123  // nothing will connect, so bail out.
8124  fRevertToInv = true;
8125  break;
8126  }
8127  }
8128  }
8129  if (!fRevertToInv && !vHeaders.empty()) {
8130  if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
8131  // We only send up to 1 block as header-and-ids, as
8132  // otherwise probably means we're doing an initial-ish-sync
8133  // or they're slow.
8135  "%s sending header-and-ids %s to peer=%d\n",
8136  __func__, vHeaders.front().GetHash().ToString(),
8137  pto->GetId());
8138 
8139  std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
8140  {
8141  LOCK(m_most_recent_block_mutex);
8142  if (m_most_recent_block_hash ==
8143  pBestIndex->GetBlockHash()) {
8144  cached_cmpctblock_msg =
8145  msgMaker.Make(NetMsgType::CMPCTBLOCK,
8146  *m_most_recent_compact_block);
8147  }
8148  }
8149  if (cached_cmpctblock_msg.has_value()) {
8150  m_connman.PushMessage(
8151  pto, std::move(cached_cmpctblock_msg.value()));
8152  } else {
8153  CBlock block;
8154  const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(
8155  block, *pBestIndex)};
8156  assert(ret);
8157  CBlockHeaderAndShortTxIDs cmpctblock(block);
8158  m_connman.PushMessage(
8159  pto,
8160  msgMaker.Make(NetMsgType::CMPCTBLOCK, cmpctblock));
8161  }
8162  state.pindexBestHeaderSent = pBestIndex;
8163  } else if (peer->m_prefers_headers) {
8164  if (vHeaders.size() > 1) {
8166  "%s: %u headers, range (%s, %s), to peer=%d\n",
8167  __func__, vHeaders.size(),
8168  vHeaders.front().GetHash().ToString(),
8169  vHeaders.back().GetHash().ToString(),
8170  pto->GetId());
8171  } else {
8173  "%s: sending header %s to peer=%d\n", __func__,
8174  vHeaders.front().GetHash().ToString(),
8175  pto->GetId());
8176  }
8177  m_connman.PushMessage(
8178  pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
8179  state.pindexBestHeaderSent = pBestIndex;
8180  } else {
8181  fRevertToInv = true;
8182  }
8183  }
8184  if (fRevertToInv) {
8185  // If falling back to using an inv, just try to inv the tip. The
8186  // last entry in m_blocks_for_headers_relay was our tip at some
8187  // point in the past.
8188  if (!peer->m_blocks_for_headers_relay.empty()) {
8189  const BlockHash &hashToAnnounce =
8190  peer->m_blocks_for_headers_relay.back();
8191  const CBlockIndex *pindex =
8192  m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
8193  assert(pindex);
8194 
8195  // Warn if we're announcing a block that is not on the main
8196  // chain. This should be very rare and could be optimized
8197  // out. Just log for now.
8198  if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
8199  LogPrint(
8200  BCLog::NET,
8201  "Announcing block %s not on main chain (tip=%s)\n",
8202  hashToAnnounce.ToString(),
8203  m_chainman.ActiveChain()
8204  .Tip()
8205  ->GetBlockHash()
8206  .ToString());
8207  }
8208 
8209  // If the peer's chain has this block, don't inv it back.
8210  if (!PeerHasHeader(&state, pindex)) {
8211  peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
8213  "%s: sending inv peer=%d hash=%s\n", __func__,
8214  pto->GetId(), hashToAnnounce.ToString());
8215  }
8216  }
8217  }
8218  peer->m_blocks_for_headers_relay.clear();
8219  }
8220  } // release cs_main
8221 
8222  //
8223  // Message: inventory
8224  //
8225  std::vector<CInv> vInv;
8226  auto addInvAndMaybeFlush = [&](uint32_t type, const uint256 &hash) {
8227  vInv.emplace_back(type, hash);
8228  if (vInv.size() == MAX_INV_SZ) {
8229  m_connman.PushMessage(
8230  pto, msgMaker.Make(NetMsgType::INV, std::move(vInv)));
8231  vInv.clear();
8232  }
8233  };
8234 
8235  {
8236  LOCK(cs_main);
8237 
8238  {
8239  LOCK(peer->m_block_inv_mutex);
8240 
8241  vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(),
8243  config.GetMaxBlockSize() /
8244  1000000));
8245 
8246  // Add blocks
8247  for (const BlockHash &hash : peer->m_blocks_for_inv_relay) {
8248  addInvAndMaybeFlush(MSG_BLOCK, hash);
8249  }
8250  peer->m_blocks_for_inv_relay.clear();
8251  }
8252 
8253  auto computeNextInvSendTime =
8254  [&](std::chrono::microseconds &next) -> bool {
8255  bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
8256 
8257  if (next < current_time) {
8258  fSendTrickle = true;
8259  if (pto->IsInboundConn()) {
8260  next = NextInvToInbounds(
8261  current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL);
8262  } else {
8263  // Skip delay for outbound peers, as there is less privacy
8264  // concern for them.
8265  next = current_time;
8266  }
8267  }
8268 
8269  return fSendTrickle;
8270  };
8271 
8272  // Add proofs to inventory
8273  if (peer->m_proof_relay != nullptr) {
8274  LOCK(peer->m_proof_relay->m_proof_inventory_mutex);
8275 
8276  if (computeNextInvSendTime(
8277  peer->m_proof_relay->m_next_inv_send_time)) {
8278  auto it =
8279  peer->m_proof_relay->m_proof_inventory_to_send.begin();
8280  while (it !=
8281  peer->m_proof_relay->m_proof_inventory_to_send.end()) {
8282  const avalanche::ProofId proofid = *it;
8283 
8284  it = peer->m_proof_relay->m_proof_inventory_to_send.erase(
8285  it);
8286 
8287  if (peer->m_proof_relay->m_proof_inventory_known_filter
8288  .contains(proofid)) {
8289  continue;
8290  }
8291 
8292  peer->m_proof_relay->m_proof_inventory_known_filter.insert(
8293  proofid);
8294  addInvAndMaybeFlush(MSG_AVA_PROOF, proofid);
8295  peer->m_proof_relay->m_recently_announced_proofs.insert(
8296  proofid);
8297  }
8298  }
8299  }
8300 
8301  if (auto tx_relay = peer->GetTxRelay()) {
8302  LOCK(tx_relay->m_tx_inventory_mutex);
8303  // Check whether periodic sends should happen
8304  const bool fSendTrickle =
8305  computeNextInvSendTime(tx_relay->m_next_inv_send_time);
8306 
8307  // Time to send but the peer has requested we not relay
8308  // transactions.
8309  if (fSendTrickle) {
8310  LOCK(tx_relay->m_bloom_filter_mutex);
8311  if (!tx_relay->m_relay_txs) {
8312  tx_relay->m_tx_inventory_to_send.clear();
8313  }
8314  }
8315 
8316  // Respond to BIP35 mempool requests
8317  if (fSendTrickle && tx_relay->m_send_mempool) {
8318  auto vtxinfo = m_mempool.infoAll();
8319  tx_relay->m_send_mempool = false;
8320  const CFeeRate filterrate{
8321  tx_relay->m_fee_filter_received.load()};
8322 
8323  LOCK(tx_relay->m_bloom_filter_mutex);
8324 
8325  for (const auto &txinfo : vtxinfo) {
8326  const TxId &txid = txinfo.tx->GetId();
8327  tx_relay->m_tx_inventory_to_send.erase(txid);
8328  // Don't send transactions that peers will not put into
8329  // their mempool
8330  if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8331  continue;
8332  }
8333  if (tx_relay->m_bloom_filter &&
8334  !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8335  *txinfo.tx)) {
8336  continue;
8337  }
8338  tx_relay->m_tx_inventory_known_filter.insert(txid);
8339  // Responses to MEMPOOL requests bypass the
8340  // m_recently_announced_invs filter.
8341  addInvAndMaybeFlush(MSG_TX, txid);
8342  }
8343  tx_relay->m_last_mempool_req =
8344  std::chrono::duration_cast<std::chrono::seconds>(
8345  current_time);
8346  }
8347 
8348  // Determine transactions to relay
8349  if (fSendTrickle) {
8350  // Produce a vector with all candidates for sending
8351  std::vector<std::set<TxId>::iterator> vInvTx;
8352  vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
8353  for (std::set<TxId>::iterator it =
8354  tx_relay->m_tx_inventory_to_send.begin();
8355  it != tx_relay->m_tx_inventory_to_send.end(); it++) {
8356  vInvTx.push_back(it);
8357  }
8358  const CFeeRate filterrate{
8359  tx_relay->m_fee_filter_received.load()};
8360  // Send out the inventory in the order of admission to our
8361  // mempool, which is guaranteed to be a topological sort order.
8362  // A heap is used so that not all items need sorting if only a
8363  // few are being sent.
8364  CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool);
8365  std::make_heap(vInvTx.begin(), vInvTx.end(),
8366  compareInvMempoolOrder);
8367  // No reason to drain out at many times the network's
8368  // capacity, especially since we have many peers and some
8369  // will draw much shorter delays.
8370  unsigned int nRelayedTransactions = 0;
8371  LOCK(tx_relay->m_bloom_filter_mutex);
8372  while (!vInvTx.empty() &&
8373  nRelayedTransactions < INVENTORY_BROADCAST_MAX_PER_MB *
8374  config.GetMaxBlockSize() /
8375  1000000) {
8376  // Fetch the top element from the heap
8377  std::pop_heap(vInvTx.begin(), vInvTx.end(),
8378  compareInvMempoolOrder);
8379  std::set<TxId>::iterator it = vInvTx.back();
8380  vInvTx.pop_back();
8381  const TxId txid = *it;
8382  // Remove it from the to-be-sent set
8383  tx_relay->m_tx_inventory_to_send.erase(it);
8384  // Check if not in the filter already
8385  if (tx_relay->m_tx_inventory_known_filter.contains(txid)) {
8386  continue;
8387  }
8388  // Not in the mempool anymore? don't bother sending it.
8389  auto txinfo = m_mempool.info(txid);
8390  if (!txinfo.tx) {
8391  continue;
8392  }
8393  // Peer told you to not send transactions at that
8394  // feerate? Don't bother sending it.
8395  if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8396  continue;
8397  }
8398  if (tx_relay->m_bloom_filter &&
8399  !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8400  *txinfo.tx)) {
8401  continue;
8402  }
8403  // Send
8404  tx_relay->m_recently_announced_invs.insert(txid);
8405  addInvAndMaybeFlush(MSG_TX, txid);
8406  nRelayedTransactions++;
8407  {
8408  // Expire old relay messages
8409  while (!g_relay_expiration.empty() &&
8410  g_relay_expiration.front().first <
8411  current_time) {
8412  mapRelay.erase(g_relay_expiration.front().second);
8413  g_relay_expiration.pop_front();
8414  }
8415 
8416  auto ret = mapRelay.insert(
8417  std::make_pair(txid, std::move(txinfo.tx)));
8418  if (ret.second) {
8419  g_relay_expiration.push_back(std::make_pair(
8420  current_time + RELAY_TX_CACHE_TIME, ret.first));
8421  }
8422  }
8423  tx_relay->m_tx_inventory_known_filter.insert(txid);
8424  }
8425  }
8426  }
8427  } // release cs_main
8428 
8429  if (!vInv.empty()) {
8430  m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
8431  }
8432 
8433  {
8434  LOCK(cs_main);
8435 
8436  CNodeState &state = *State(pto->GetId());
8437 
8438  // Detect whether we're stalling
8439  auto stalling_timeout = m_block_stalling_timeout.load();
8440  if (state.m_stalling_since.count() &&
8441  state.m_stalling_since < current_time - stalling_timeout) {
8442  // Stalling only triggers when the block download window cannot
8443  // move. During normal steady state, the download window should be
8444  // much larger than the to-be-downloaded set of blocks, so
8445  // disconnection should only happen during initial block download.
8446  LogPrintf("Peer=%d is stalling block download, disconnecting\n",
8447  pto->GetId());
8448  pto->fDisconnect = true;
8449  // Increase timeout for the next peer so that we don't disconnect
8450  // multiple peers if our own bandwidth is insufficient.
8451  const auto new_timeout =
8452  std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX);
8453  if (stalling_timeout != new_timeout &&
8454  m_block_stalling_timeout.compare_exchange_strong(
8455  stalling_timeout, new_timeout)) {
8456  LogPrint(
8457  BCLog::NET,
8458  "Increased stalling timeout temporarily to %d seconds\n",
8459  count_seconds(new_timeout));
8460  }
8461  return true;
8462  }
8463  // In case there is a block that has been in flight from this peer for
8464  // block_interval * (1 + 0.5 * N) (with N the number of peers from which
8465  // we're downloading validated blocks), disconnect due to timeout.
8466  // We compensate for other peers to prevent killing off peers due to our
8467  // own downstream link being saturated. We only count validated
8468  // in-flight blocks so peers can't advertise non-existing block hashes
8469  // to unreasonably increase our timeout.
8470  if (state.vBlocksInFlight.size() > 0) {
8471  QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
8472  int nOtherPeersWithValidatedDownloads =
8473  m_peers_downloading_from - 1;
8474  if (current_time >
8475  state.m_downloading_since +
8476  std::chrono::seconds{consensusParams.nPowTargetSpacing} *
8479  nOtherPeersWithValidatedDownloads)) {
8480  LogPrintf("Timeout downloading block %s from peer=%d, "
8481  "disconnecting\n",
8482  queuedBlock.pindex->GetBlockHash().ToString(),
8483  pto->GetId());
8484  pto->fDisconnect = true;
8485  return true;
8486  }
8487  }
8488 
8489  // Check for headers sync timeouts
8490  if (state.fSyncStarted &&
8491  peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
8492  // Detect whether this is a stalling initial-headers-sync peer
8493  if (m_chainman.m_best_header->Time() <= GetAdjustedTime() - 24h) {
8494  if (current_time > peer->m_headers_sync_timeout &&
8495  nSyncStarted == 1 &&
8496  (m_num_preferred_download_peers -
8497  state.fPreferredDownload >=
8498  1)) {
8499  // Disconnect a peer (without NetPermissionFlags::NoBan
8500  // permission) if it is our only sync peer, and we have
8501  // others we could be using instead. Note: If all our peers
8502  // are inbound, then we won't disconnect our sync peer for
8503  // stalling; we have bigger problems if we can't get any
8504  // outbound peers.
8506  LogPrintf("Timeout downloading headers from peer=%d, "
8507  "disconnecting\n",
8508  pto->GetId());
8509  pto->fDisconnect = true;
8510  return true;
8511  } else {
8512  LogPrintf("Timeout downloading headers from noban "
8513  "peer=%d, not disconnecting\n",
8514  pto->GetId());
8515  // Reset the headers sync state so that we have a chance
8516  // to try downloading from a different peer. Note: this
8517  // will also result in at least one more getheaders
8518  // message to be sent to this peer (eventually).
8519  state.fSyncStarted = false;
8520  nSyncStarted--;
8521  peer->m_headers_sync_timeout = 0us;
8522  }
8523  }
8524  } else {
8525  // After we've caught up once, reset the timeout so we can't
8526  // trigger disconnect later.
8527  peer->m_headers_sync_timeout = std::chrono::microseconds::max();
8528  }
8529  }
8530 
8531  // Check that outbound peers have reasonable chains GetTime() is used by
8532  // this anti-DoS logic so we can test this using mocktime.
8533  ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
8534  } // release cs_main
8535 
8536  std::vector<CInv> vGetData;
8537 
8538  //
8539  // Message: getdata (blocks)
8540  //
8541  {
8542  LOCK(cs_main);
8543 
8544  CNodeState &state = *State(pto->GetId());
8545 
8546  if (CanServeBlocks(*peer) &&
8547  ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) ||
8548  !m_chainman.ActiveChainstate().IsInitialBlockDownload()) &&
8549  state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
8550  std::vector<const CBlockIndex *> vToDownload;
8551  NodeId staller = -1;
8552  FindNextBlocksToDownload(pto->GetId(),
8554  state.nBlocksInFlight,
8555  vToDownload, staller);
8556  for (const CBlockIndex *pindex : vToDownload) {
8557  vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
8558  BlockRequested(config, pto->GetId(), *pindex);
8559  LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n",
8560  pindex->GetBlockHash().ToString(), pindex->nHeight,
8561  pto->GetId());
8562  }
8563  if (state.nBlocksInFlight == 0 && staller != -1) {
8564  if (State(staller)->m_stalling_since == 0us) {
8565  State(staller)->m_stalling_since = current_time;
8566  LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
8567  }
8568  }
8569  }
8570  } // release cs_main
8571 
8572  auto addGetDataAndMaybeFlush = [&](uint32_t type, const uint256 &hash) {
8573  CInv inv(type, hash);
8574  LogPrint(BCLog::NET, "Requesting %s from peer=%d\n", inv.ToString(),
8575  pto->GetId());
8576  vGetData.push_back(std::move(inv));
8577  if (vGetData.size() >= MAX_GETDATA_SZ) {
8578  m_connman.PushMessage(
8579  pto, msgMaker.Make(NetMsgType::GETDATA, std::move(vGetData)));
8580  vGetData.clear();
8581  }
8582  };
8583 
8584  //
8585  // Message: getdata (proof)
8586  //
8587  {
8588  LOCK(cs_proofrequest);
8589  std::vector<std::pair<NodeId, avalanche::ProofId>> expired;
8590  auto requestable =
8591  m_proofrequest.GetRequestable(pto->GetId(), current_time, &expired);
8592  for (const auto &entry : expired) {
8594  "timeout of inflight proof %s from peer=%d\n",
8595  entry.second.ToString(), entry.first);
8596  }
8597  for (const auto &proofid : requestable) {
8598  if (!AlreadyHaveProof(proofid)) {
8599  addGetDataAndMaybeFlush(MSG_AVA_PROOF, proofid);
8600  m_proofrequest.RequestedData(
8601  pto->GetId(), proofid,
8602  current_time + PROOF_REQUEST_PARAMS.getdata_interval);
8603  } else {
8604  // We have already seen this proof, no need to download.
8605  // This is just a belt-and-suspenders, as this should
8606  // already be called whenever a proof becomes
8607  // AlreadyHaveProof().
8608  m_proofrequest.ForgetInvId(proofid);
8609  }
8610  }
8611  } // release cs_proofrequest
8612 
8613  //
8614  // Message: getdata (transactions)
8615  //
8616  {
8617  LOCK(cs_main);
8618  std::vector<std::pair<NodeId, TxId>> expired;
8619  auto requestable =
8620  m_txrequest.GetRequestable(pto->GetId(), current_time, &expired);
8621  for (const auto &entry : expired) {
8622  LogPrint(BCLog::NET, "timeout of inflight tx %s from peer=%d\n",
8623  entry.second.ToString(), entry.first);
8624  }
8625  for (const TxId &txid : requestable) {
8626  // Exclude m_recent_rejects_reconsiderable: we may be requesting a
8627  // missing parent that was previously rejected for being too low
8628  // feerate.
8629  if (!AlreadyHaveTx(txid, /*include_reconsiderable=*/false)) {
8630  addGetDataAndMaybeFlush(MSG_TX, txid);
8631  m_txrequest.RequestedData(
8632  pto->GetId(), txid,
8633  current_time + TX_REQUEST_PARAMS.getdata_interval);
8634  } else {
8635  // We have already seen this transaction, no need to download.
8636  // This is just a belt-and-suspenders, as this should already be
8637  // called whenever a transaction becomes AlreadyHaveTx().
8638  m_txrequest.ForgetInvId(txid);
8639  }
8640  }
8641 
8642  if (!vGetData.empty()) {
8643  m_connman.PushMessage(pto,
8644  msgMaker.Make(NetMsgType::GETDATA, vGetData));
8645  }
8646 
8647  } // release cs_main
8648  MaybeSendFeefilter(*pto, *peer, current_time);
8649  return true;
8650 }
8651 
8652 bool PeerManagerImpl::ReceivedAvalancheProof(CNode &node, Peer &peer,
8653  const avalanche::ProofRef &proof) {
8654  assert(proof != nullptr);
8655 
8656  const avalanche::ProofId &proofid = proof->getId();
8657 
8658  AddKnownProof(peer, proofid);
8659 
8660  if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
8661  // We cannot reliably verify proofs during IBD, so bail out early and
8662  // keep the inventory as pending so it can be requested when the node
8663  // has synced.
8664  return true;
8665  }
8666 
8667  const NodeId nodeid = node.GetId();
8668 
8669  const bool isStaker = WITH_LOCK(node.cs_avalanche_pubkey,
8670  return node.m_avalanche_pubkey.has_value());
8671  auto saveProofIfStaker = [this, isStaker](const CNode &node,
8672  const avalanche::ProofId &proofid,
8673  const NodeId nodeid) -> bool {
8674  if (isStaker) {
8675  return m_avalanche->withPeerManager(
8676  [&](avalanche::PeerManager &pm) {
8677  return pm.saveRemoteProof(proofid, nodeid, true);
8678  });
8679  }
8680 
8681  return false;
8682  };
8683 
8684  {
8685  LOCK(cs_proofrequest);
8686  m_proofrequest.ReceivedResponse(nodeid, proofid);
8687 
8688  if (AlreadyHaveProof(proofid)) {
8689  m_proofrequest.ForgetInvId(proofid);
8690  saveProofIfStaker(node, proofid, nodeid);
8691  return true;
8692  }
8693  }
8694 
8695  // registerProof should not be called while cs_proofrequest because it
8696  // holds cs_main and that creates a potential deadlock during shutdown
8697 
8699  if (m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
8700  return pm.registerProof(proof, state);
8701  })) {
8702  WITH_LOCK(cs_proofrequest, m_proofrequest.ForgetInvId(proofid));
8703  RelayProof(proofid);
8704 
8705  node.m_last_proof_time = GetTime<std::chrono::seconds>();
8706 
8707  LogPrint(BCLog::NET, "New avalanche proof: peer=%d, proofid %s\n",
8708  nodeid, proofid.ToString());
8709  }
8710 
8712  m_avalanche->withPeerManager(
8713  [&](avalanche::PeerManager &pm) { pm.setInvalid(proofid); });
8714  Misbehaving(peer, 100, state.GetRejectReason());
8715  return false;
8716  }
8717 
8719  // This is possible that a proof contains a utxo we don't know yet, so
8720  // don't ban for this.
8721  return false;
8722  }
8723 
8724  if (!m_avalanche->reconcileOrFinalize(proof)) {
8726  "Not polling the avalanche proof (%s): peer=%d, proofid %s\n",
8727  state.IsValid() ? "not-worth-polling"
8728  : state.GetRejectReason(),
8729  nodeid, proofid.ToString());
8730  }
8731 
8732  saveProofIfStaker(node, proofid, nodeid);
8733 
8734  return true;
8735 }
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:165
@ READ_STATUS_OK
@ READ_STATUS_INVALID
@ READ_STATUS_FAILED
enum ReadStatus_t ReadStatus
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
BlockFilterType
Definition: blockfilter.h:88
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
@ CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:74
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:41
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:112
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:89
#define Assert(val)
Identity function.
Definition: check.h:84
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Stochastic address manager.
Definition: addrman.h:69
void Good(const CService &addr, bool test_before_evict=true, NodeSeconds time=AdjustedTime())
Mark an entry as accessible, possibly moving it from "new" to "tried".
Definition: addrman.cpp:1324
void Connected(const CService &addr, NodeSeconds time=AdjustedTime())
We have successfully connected to this peer.
Definition: addrman.cpp:1351
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
Definition: addrman.cpp:1319
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Definition: addrman.cpp:1355
Definition: banman.h:58
void Discourage(const CNetAddr &net_addr)
Definition: banman.cpp:122
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
Definition: banman.cpp:89
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
Definition: banman.cpp:84
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
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.
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.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
std::vector< CTransactionRef > txn
std::vector< uint32_t > indices
A CService with information about it as peer.
Definition: protocol.h:442
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:546
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition: protocol.h:544
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
uint32_t nTime
Definition: block.h:29
BlockHash hashPrevBlock
Definition: block.h:27
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:211
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
CBlockHeader GetBlockHeader() const
Definition: blockindex.h:133
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
bool HaveTxsDownloaded() const
Check whether this block's and all previous blocks' transactions have been downloaded (and stored to ...
Definition: blockindex.h:174
int64_t GetBlockTime() const
Definition: blockindex.h:180
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:60
NodeSeconds Time() const
Definition: blockindex.h:176
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:78
BlockHash GetBlockHash() const
Definition: blockindex.h:146
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:44
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
Definition: bloom.cpp:93
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:174
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:150
int Height() const
Return the maximal height in the chain.
Definition: chain.h:186
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:166
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:80
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:92
const CBlock & GenesisBlock() const
Definition: chainparams.h:105
Definition: net.h:845
void ForEachNode(const NodeFn &func)
Definition: net.h:951
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:3367
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3539
bool GetNetworkActive() const
Definition: net.h:938
bool GetTryNewOutboundPeer() const
Definition: net.cpp:2070
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2074
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:3414
int GetExtraBlockRelayCount() const
Definition: net.cpp:2102
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1900
void StartExtraBlockRelayPeers()
Definition: net.h:996
bool DisconnectNode(const std::string &node)
Definition: net.cpp:3278
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3551
int GetExtraFullOutboundCount() const
Definition: net.cpp:2086
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:3159
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:396
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1528
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3494
bool GetUseAddrmanOutgoing() const
Definition: net.h:939
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:177
int GetType() const
Definition: streams.h:337
int GetVersion() const
Definition: streams.h:339
int in_avail() const
Definition: streams.h:334
void ignore(int nSize)
Definition: streams.h:360
bool empty() const
Definition: streams.h:224
size_type size() const
Definition: streams.h:223
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:169
Inv(ventory) message data.
Definition: protocol.h:580
bool IsMsgCmpctBlk() const
Definition: protocol.h:615
bool IsMsgBlk() const
Definition: protocol.h:607
std::string ToString() const
Definition: protocol.cpp:235
uint32_t type
Definition: protocol.h:582
bool IsMsgTx() const
Definition: protocol.h:599
bool IsMsgFilteredBlk() const
Definition: protocol.h:611
uint256 hash
Definition: protocol.h:583
bool IsMsgProof() const
Definition: protocol.h:603
bool IsGenBlkMsg() const
Definition: protocol.h:620
Used to create a Merkle proof (usually from a subset of transactions), which consists of a block head...
Definition: merkleblock.h:147
std::vector< std::pair< size_t, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
Definition: merkleblock.h:159
bool IsRelayable() const
Whether this address should be relayed to other peers even if we can't reach it ourselves.
Definition: netaddress.h:252
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:125
bool IsRoutable() const
Definition: netaddress.cpp:514
bool IsValid() const
Definition: netaddress.cpp:479
bool IsLocal() const
Definition: netaddress.cpp:453
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:530
Transport protocol agnostic message container.
Definition: net.h:331
CSerializedNetMsg Make(int nFlags, std::string msg_type, Args &&...args) const
Information about a peer.
Definition: net.h:456
RecursiveMutex cs_vProcessMsg
Definition: net.h:476
Mutex cs_avalanche_pubkey
Definition: net.h:620
bool IsFeelerConn() const
Definition: net.h:549
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:485
bool ExpectServicesFromConn() const
Definition: net.h:563
std::atomic< int > nVersion
Definition: net.h:495
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:601
bool IsInboundConn() const
Definition: net.h:555
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:508
std::atomic_bool fPauseRecv
Definition: net.h:519
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:522
NodeId GetId() const
Definition: net.h:712
bool IsManualConn() const
Definition: net.h:543
std::atomic< int64_t > nTimeOffset
Definition: net.h:486
const std::string m_addr_name
Definition: net.h:491
std::string ConnectionTypeAsString() const
Definition: net.h:758
void SetCommonVersion(int greatest_common_version)
Definition: net.h:734
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:593
size_t nProcessQueueSize
Definition: net.h:478
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer (their version message did not include fRelay=false...
Definition: net.h:609
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:595
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:707
std::atomic_bool fSuccessfullyConnected
Definition: net.h:511
bool IsAddrFetchConn() const
Definition: net.h:551
uint64_t GetLocalNonce() const
Definition: net.h:714
const CAddress addr
Definition: net.h:488
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:603
bool IsBlockOnlyConn() const
Definition: net.h:545
int GetCommonVersion() const
Definition: net.h:738
bool IsFullOutboundConn() const
Definition: net.h:538
uint64_t nRemoteHostNonce
Definition: net.h:497
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:504
std::atomic_bool fPauseSend
Definition: net.h:520
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:650
uint64_t nRemoteExtraEntropy
Definition: net.h:499
uint64_t GetLocalExtraEntropy() const
Definition: net.h:715
SteadyMilliseconds m_last_poll
Definition: net.h:657
double getAvailabilityScore() const
Definition: net.cpp:3441
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:615
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:3426
std::atomic< std::chrono::seconds > m_avalanche_last_message_fault
Definition: net.h:653
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:494
std::atomic< int > m_avalanche_message_fault_counter
Definition: net.h:655
std::atomic< bool > m_avalanche_enabled
Definition: net.h:618
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:666
std::atomic_bool fDisconnect
Definition: net.h:514
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:674
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:3422
bool IsAvalancheOutboundConnection() const
Definition: net.h:559
const TxId & GetTxId() const
Definition: transaction.h:35
An encapsulated public key.
Definition: pubkey.h:31
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:115
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
void scheduleEvery(Predicate p, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat p until it return false.
Definition: scheduler.cpp:114
void scheduleFromNow(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Call f once after the delta has passed.
Definition: scheduler.h:56
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:545
std::string ToString() const
std::vector< uint8_t > GetKey() const
SipHash-2-4.
Definition: siphash.h:13
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:82
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Definition: siphash.cpp:36
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:192
const std::vector< CTxIn > vin
Definition: transaction.h:206
const TxId GetId() const
Definition: transaction.h:240
An input of a transaction.
Definition: transaction.h:59
COutPoint prevout
Definition: transaction.h:61
std::set< std::reference_wrapper< const CTxMemPoolEntryRef >, CompareIteratorById > Parents
Definition: mempool_entry.h:70
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:209
void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:654
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.h:440
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:296
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:259
bool CompareTopologically(const TxId &txida, const TxId &txidb) const
Definition: txmempool.cpp:459
TxMempoolInfo info(const TxId &txid) const
Definition: txmempool.cpp:515
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:643
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:491
bool setAvalancheFinalized(const CTxMemPoolEntryRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:497
bool exists(const TxId &txid) const
Definition: txmempool.h:492
const CFeeRate m_min_relay_feerate
Definition: txmempool.h:335
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:529
void removeForFinalizedBlock(const std::vector< CTransactionRef > &vtx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:315
unsigned long size() const
Definition: txmempool.h:477
std::optional< txiter > GetIter(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given txid, if found.
Definition: txmempool.cpp:573
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...
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1218
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1428
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1321
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1434
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1350
Definition: config.h:19
virtual uint64_t GetMaxBlockSize() const =0
Fast randomness source.
Definition: random.h:156
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:99
HeadersSyncState:
Definition: headerssync.h:98
@ FINAL
We're done syncing with this peer and can discard any remaining state.
@ PRESYNC
PRESYNC means the peer has not yet demonstrated their chain has sufficient work and we're only buildi...
size_t Count(NodeId peer) const
Count how many announcements a peer has (REQUESTED, CANDIDATE, and COMPLETED combined).
Definition: invrequest.h:309
size_t CountInFlight(NodeId peer) const
Count how many REQUESTED announcements a peer has.
Definition: invrequest.h:296
Interface for message handling.
Definition: net.h:794
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:799
virtual bool ProcessMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool SendMessages(const Config &config, CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void InitializeNode(const Config &config, CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
virtual void FinalizeNode(const Config &config, const CNode &node)=0
Handle removal of a peer (clear state)
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< std::pair< TxHash, CTransactionRef >> &extra_txn)
bool IsTxAvailable(size_t index) const
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
virtual void SendPings()=0
Send ping message to all peers.
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, avalanche::Processor *const avalanche, Options opts)
virtual void ProcessMessage(const Config &config, CNode &pfrom, const std::string &msg_type, CDataStream &vRecv, const std::chrono::microseconds time_received, const std::atomic< bool > &interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process a single message from a peer.
virtual void StartScheduledTasks(CScheduler &scheduler)=0
Begin running background tasks, should only be called once.
virtual bool IgnoresIncomingTxs()=0
Whether this node ignores txs received over p2p.
virtual void UnitTestMisbehaving(const NodeId peer_id, const int howmuch)=0
Public for unit testing.
virtual std::optional< std::string > FetchBlock(const Config &config, NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)=0
This function is used for testing the stale tip eviction logic, see denialofservice_tests....
virtual void CheckForStaleTipAndEvictPeers()=0
Evict extra outbound peers.
static RCUPtr make(Args &&...args)
Construct a new object that is owned by the pointer.
Definition: rcu.h:112
A class to track orphan transactions (failed on TX_MISSING_INPUTS) Since we cannot distinguish orphan...
Definition: txorphanage.h:23
bool HaveTxToReconsider(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Does this peer have any work to do?
void AddChildrenToWorkSet(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Add any orphans that list a particular tx as a parent into the from peer's work set.
unsigned int LimitOrphans(unsigned int max_orphans, FastRandomContext &rng) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Limit the orphanage to the given maximum.
void EraseForBlock(const CBlock &block) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase all orphans included in or invalidated by a new block.
bool AddTx(const CTransactionRef &tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Add a new orphan transaction.
Definition: txorphanage.cpp:19
std::vector< std::pair< CTransactionRef, NodeId > > GetChildrenFromDifferentPeer(const CTransactionRef &parent, NodeId nodeid) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get all children that spend from this tx but were not received from nodeid.
size_t Size() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Return how many entries exist in the orphange.
Definition: txorphanage.h:85
int EraseTx(const TxId &txid) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase an orphan by txid.
Definition: txorphanage.cpp:57
bool HaveTx(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check if we already have an orphan transaction.
CTransactionRef GetTxToReconsider(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Extract a transaction from a peer's work set.
void EraseForPeer(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase all orphans announced by a peer (eg, after that peer disconnects)
std::vector< CTransactionRef > GetChildrenFromSamePeer(const CTransactionRef &parent, NodeId nodeid) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get all children that spend from this tx and were received from nodeid.
bool IsValid() const
Definition: validation.h:117
std::string GetRejectReason() const
Definition: validation.h:121
Result GetResult() const
Definition: validation.h:120
std::string ToString() const
Definition: validation.h:123
bool IsInvalid() const
Definition: validation.h:118
256-bit unsigned big integer.
const std::vector< uint64_t > & getShortIDs() const
Definition: compactproofs.h:79
uint64_t getShortID(const ProofId &proofid) const
const std::vector< PrefilledProof > & getPrefilledProofs() const
Definition: compactproofs.h:76
ProofId getProofId() const
Definition: delegation.cpp:56
bool verify(DelegationState &state, CPubKey &auth) const
Definition: delegation.cpp:73
const LimitedProofId & getLimitedProofId() const
Definition: delegation.h:61
const DelegationId & getId() const
Definition: delegation.h:60
bool shouldRequestMoreNodes()
Returns true if we encountered a lack of node since the last call.
Definition: peermanager.h:331
bool exists(const ProofId &proofid) const
Definition: peermanager.h:402
bool forPeer(const ProofId &proofid, Callable &&func) const
Definition: peermanager.h:410
bool addNode(NodeId nodeid, const ProofId &proofid)
Node API.
Definition: peermanager.cpp:31
void removeUnbroadcastProof(const ProofId &proofid)
bool isBoundToPeer(const ProofId &proofid) const
bool saveRemoteProof(const ProofId &proofid, const NodeId nodeid, const bool present)
void forEachPeer(Callable &&func) const
Definition: peermanager.h:416
void setInvalid(const ProofId &proofid)
bool isInvalid(const ProofId &proofid) const
bool isImmature(const ProofId &proofid) const
const ProofRadixTree & getShareableProofsSnapshot() const
Definition: peermanager.h:516
void updateAvailabilityScores(const double decayFactor, Callable &&getNodeAvailabilityScore)
Definition: peermanager.h:453
auto getUnbroadcastProofs() const
Definition: peermanager.h:432
bool isInConflictingPool(const ProofId &proofid) const
void sendResponse(CNode *pfrom, Response response) const
Definition: processor.cpp:510
int64_t getAvaproofsNodeCounter() const
Definition: processor.h:357
bool registerVotes(NodeId nodeid, const Response &response, std::vector< VoteItemUpdate > &updates, int &banscore, std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:517
bool sendHello(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Send a avahello message.
Definition: processor.cpp:717
bool isQuorumEstablished() LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:779
ProofRef getLocalProof() const
Definition: processor.cpp:739
bool reconcileOrFinalize(const ProofRef &proof) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Wrapper around the addToReconcile for proofs that adds back the finalization flag to the peer if it i...
Definition: processor.cpp:425
void sendDelayedAvahello() EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Definition: processor.cpp:722
auto withPeerManager(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.h:326
void avaproofsSent(NodeId nodeid) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:758
std::vector< uint32_t > indices
uint8_t * end()
Definition: uint256.h:87
std::string ToString() const
Definition: uint256.h:80
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool LoadingBlocks() const
Definition: blockstorage.h:244
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:235
256-bit opaque blob.
Definition: uint256.h:129
static const uint256 ZERO
Definition: uint256.h:134
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ BLOCK_RESULT_UNSET
initial value. Block has not yet been rejected
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_CHILD_BEFORE_PARENT
This tx outputs are already spent in the mempool.
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/etc limits
@ TX_UNKNOWN
transaction was not validated because package failed
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_DUPLICATE
Tx already in mempool or in the chain.
@ TX_INPUTS_NOT_STANDARD
inputs failed policy rules
@ TX_CONFLICT
Tx conflicts with another mempool tx, i.e.
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_RESULT_UNSET
initial value. Tx has not yet been rejected
@ TX_CONSENSUS
invalid by consensus rules
@ TX_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::array< uint8_t, CPubKey::SCHNORR_SIZE > SchnorrSig
a Schnorr signature
Definition: key.h:25
bool fLogIPs
Definition: logging.cpp:17
bool error(const char *fmt, const Args &...args)
Definition: logging.h:226
#define LogPrint(category,...)
Definition: logging.h:211
#define LogPrintf(...)
Definition: logging.h:207
@ AVALANCHE
Definition: logging.h:62
@ TXPACKAGES
Definition: logging.h:70
@ NETDEBUG
Definition: logging.h:69
@ MEMPOOLREJ
Definition: logging.h:56
@ MEMPOOL
Definition: logging.h:42
@ NET
Definition: logging.h:40
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:36
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:48
const char * AVAPROOFSREQ
Request for missing avalanche proofs after an avaproofs message has been processed.
Definition: protocol.cpp:58
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:46
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:30
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:38
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:29
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:21
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:39
const char * AVAPROOFS
The avaproofs message the proof short ids of all the valid proofs that we know.
Definition: protocol.cpp:57
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:34
const char * GETAVAPROOFS
The getavaproofs message requests an avaproofs message that provides the proof short ids of all the v...
Definition: protocol.cpp:56
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:41
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:31
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:49
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:35
const char * GETAVAADDR
The getavaaddr message requests an addr message from the receiving node, containing IP addresses of t...
Definition: protocol.cpp:55
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition: protocol.cpp:42
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:32
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:45
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:28
const char * AVAHELLO
Contains a delegation and a signature.
Definition: protocol.cpp:51
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:37
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:20
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:18
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:26
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:40
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:27
const char * AVARESPONSE
Contains an avalanche::Response.
Definition: protocol.cpp:53
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:24
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:19
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:44
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.cpp:47
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:22
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:33
const char * AVAPOLL
Contains an avalanche::Poll.
Definition: protocol.cpp:52
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:25
const char * AVAPROOF
Contains an avalanche::Proof.
Definition: protocol.cpp:54
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:50
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:43
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:23
ShortIdProcessor< PrefilledProof, ShortIdProcessorPrefilledProofAdapter, ProofRefCompare > ProofShortIdProcessor
Definition: compactproofs.h:52
std::variant< const ProofRef, const CBlockIndex *, const CTransactionRef > AnyVoteItem
Definition: processor.h:87
RCUPtr< const Proof > ProofRef
Definition: proof.h:185
Definition: init.h:28
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:237
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:221
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:243
bool fListen
Definition: net.cpp:126
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:3642
std::string userAgent(const Config &config)
Definition: net.cpp:3591
bool IsReachable(enum Network net)
Definition: net.cpp:325
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:335
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:69
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:63
NetPermissionFlags
static constexpr auto HEADERS_RESPONSE_TIME
How long to wait for a peer to respond to a getheaders request.
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...
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT
Default time during which a peer must stall block download progress before being disconnected.
static constexpr auto GETAVAADDR_INTERVAL
Minimum time between 2 successives getavaaddr messages from the same peer.
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL
Verify that INVENTORY_MAX_RECENT_RELAY is enough to cache everything typically relayed before uncondi...
static constexpr unsigned int INVENTORY_BROADCAST_MAX_PER_MB
Maximum number of inventory items to send per transmission.
static constexpr auto EXTRA_PEER_CHECK_INTERVAL
How frequently to check for extra outbound peers and disconnect.
static const unsigned int BLOCK_DOWNLOAD_WINDOW
Size of the "block download window": how far ahead of our current height do we fetch?...
static uint32_t getAvalancheVoteForProof(const avalanche::Processor &avalanche, const avalanche::ProofId &id)
Decide a response for an Avalanche poll about the given proof.
static constexpr int STALE_RELAY_AGE_LIMIT
Age after which a stale block will no longer be served if requested as protection against fingerprint...
static constexpr int HISTORICAL_BLOCK_AGE
Age after which a block is considered historical for purposes of rate limiting block relay.
static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL
Delay between rotating the peers we relay a particular address to.
static const int MAX_NUM_UNCONNECTING_HEADERS_MSGS
Maximum number of unconnecting headers announcements before DoS score.
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict.
static constexpr auto CHAIN_SYNC_TIMEOUT
Timeout for (unprotected) outbound peers to sync to our chainwork.
static constexpr auto RELAY_TX_CACHE_TIME
How long to cache transactions in mapRelay for normal relay.
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS
Minimum blocks required to signal NODE_NETWORK_LIMITED.
static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
Average delay between local address broadcasts.
static const int MAX_BLOCKTXN_DEPTH
Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for.
static constexpr uint64_t CMPCTBLOCKS_VERSION
The compactblocks version we support.
bool IsAvalancheMessageType(const std::string &msg_type)
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.
static std::chrono::microseconds ComputeRequestTime(const CNode &node, const InvRequestTracker< InvId > &requestTracker, const DataRequestParameters &requestParams, std::chrono::microseconds current_time, bool preferred)
Compute the request time for this announcement, current time plus delays for:
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for inbound peers.
static constexpr DataRequestParameters TX_REQUEST_PARAMS
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY
Maximum feefilter broadcast delay after significant change.
static constexpr uint32_t MAX_GETCFILTERS_SIZE
Maximum number of compact filters that may be requested with one getcfilters.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE
Headers download timeout.
static const unsigned int MAX_GETDATA_SZ
Limit to avoid sending big packets.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in multiples of the block interval (i.e.
static constexpr auto AVALANCHE_AVAPROOFS_TIMEOUT
If no proof was requested from a compact proof message after this timeout expired,...
static constexpr auto STALE_CHECK_INTERVAL
How frequently to check for stale tips.
static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY
The number of most recently announced transactions a peer can request.
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...
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL
Average delay between peer address broadcasts.
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
Additional block download timeout per parallel downloading peer (i.e.
static constexpr double MAX_ADDR_RATE_PER_SECOND
The maximum rate of address records we're willing to process on average.
static constexpr auto PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive.
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested.
static constexpr DataRequestParameters PROOF_REQUEST_PARAMS
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
static bool TooManyAnnouncements(const CNode &node, const InvRequestTracker< InvId > &requestTracker, const DataRequestParameters &requestParams)
static constexpr uint32_t MAX_GETCFHEADERS_SIZE
Maximum number of cf hashes that may be requested with one getcfheaders.
static constexpr auto BLOCK_STALLING_TIMEOUT_MAX
Maximum timeout for stalling block download.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY
SHA256("main address relay")[0:8].
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.
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND
Maximum rate of inventory items to send per second.
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of address records permitted in an ADDR message.
static const int DISCOURAGEMENT_THRESHOLD
Threshold for marking a node to be discouraged, e.g.
static const unsigned int MAX_HEADERS_RESULTS
Number of headers sent in one getheaders result.
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:33
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:753
int64_t NodeId
Definition: nodeid.h:10
uint256 GetPackageHash(const Package &package)
Definition: packages.cpp:129
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:40
static constexpr Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
Response response
Definition: processor.cpp:487
SchnorrSig sig
Definition: processor.cpp:488
static constexpr size_t AVALANCHE_MAX_ELEMENT_POLL
Maximum item that can be polled at once.
Definition: processor.h:52
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:212
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:204
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
Definition: protocol.h:25
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition: protocol.h:427
@ MSG_TX
Definition: protocol.h:565
@ MSG_AVA_PROOF
Definition: protocol.h:572
@ MSG_BLOCK
Definition: protocol.h:566
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:571
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
@ NODE_NETWORK_LIMITED
Definition: protocol.h:365
@ NODE_BLOOM
Definition: protocol.h:352
@ NODE_NETWORK
Definition: protocol.h:342
@ NODE_COMPACT_FILTERS
Definition: protocol.h:360
@ NODE_AVALANCHE
Definition: protocol.h:380
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:435
std::chrono::microseconds GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future sampled from an exponential distribution (https://en....
Definition: random.cpp:794
constexpr auto GetRandMillis
Definition: random.h:107
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:291
reverse_range< T > reverse_iterate(T &x)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
@ SER_NETWORK
Definition: serialize.h:152
void Unserialize(Stream &, char)=delete
#define LIMITED_STRING(obj, n)
Definition: serialize.h:581
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:413
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
Definition: span.h:337
static const double AVALANCHE_STATISTICS_DECAY_FACTOR
Pre-computed decay factor for the avalanche statistics computation.
Definition: statistics.h:18
static constexpr std::chrono::minutes AVALANCHE_STATISTICS_REFRESH_PERIOD
Refresh period for the avalanche statistics computation.
Definition: statistics.h:11
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:86
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:105
std::vector< BlockHash > vHave
Definition: block.h:106
bool IsNull() const
Definition: block.h:123
std::chrono::microseconds m_ping_wait
Amount m_fee_filter_received
std::vector< int > vHeightInFlight
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
int64_t presync_height
ServiceFlags their_services
std::vector< uint8_t > data
Definition: net.h:134
std::string m_type
Definition: net.h:135
Parameters that influence chain consensus.
Definition: params.h:34
int64_t nPowTargetSpacing
Definition: params.h:78
std::chrono::seconds PowTargetSpacing() const
Definition: params.h:80
const std::chrono::seconds overloaded_peer_delay
How long to delay requesting data from overloaded peers (see max_peer_request_in_flight).
const size_t max_peer_announcements
Maximum number of inventories to consider for requesting, per peer.
const std::chrono::seconds nonpref_peer_delay
How long to delay requesting data from non-preferred peers.
const NetPermissionFlags bypass_request_limits_permissions
Permission flags a peer requires to bypass the request limits tracking limits and delay penalty.
const std::chrono::microseconds getdata_interval
How long to wait (in microseconds) before a data request from an additional peer.
const size_t max_peer_request_in_flight
Maximum number of in-flight data requests from a peer.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:206
const ResultType m_result_type
Result type.
Definition: validation.h:217
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:220
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:71
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Validation result for package mempool acceptance.
Definition: validation.h:309
PackageValidationState m_state
Definition: validation.h:310
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:318
This is a radix tree storing values identified by a unique key.
Definition: radix.h:40
A TxId is the identifier of a transaction.
Definition: txid.h:14
std::chrono::seconds registration_time
Definition: peermanager.h:93
const ProofId & getProofId() const
Definition: peermanager.h:110
ProofRef proof
Definition: peermanager.h:89
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
static int count
Definition: tests.c:31
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define GUARDED_BY(x)
Definition: threadsafety.h:45
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:55
#define PT_GUARDED_BY(x)
Definition: threadsafety.h:46
int64_t GetTime()
Definition: time.cpp:109
constexpr int64_t count_microseconds(std::chrono::microseconds t)
Definition: time.h:61
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:55
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
Definition: time.h:72
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:35
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
Definition: timedata.cpp:45
NodeSeconds AdjustedTime()
Definition: timedata.h:70
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
#define TRACE6(context, event, a, b, c, d, e, f)
Definition: trace.h:45
@ AVALANCHE
Removed by avalanche vote.
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:94
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:14
static const int SHORT_IDS_BLOCKS_VERSION
short-id-based block download starts with this version
Definition: version.h:35
static const int SENDHEADERS_VERSION
"sendheaders" command and announcing blocks with headers starts with this version
Definition: version.h:28
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
static const int FEEFILTER_VERSION
"feefilter" tells peers to filter invs to you by fee starts with this version
Definition: version.h:32
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
Definition: version.h:17
static const int INVALID_CB_NO_BAN_VERSION
not banning for invalid compact blocks starts with this version
Definition: version.h:38
static const int BIP0031_VERSION
BIP 0031, pong message, is enabled for all versions AFTER this one.
Definition: version.h:20