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