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