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