Bitcoin ABC  0.26.3
P2P Digital Currency
net_processing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <net_processing.h>
7 
8 #include <addrman.h>
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",