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