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