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