Bitcoin ABC 0.33.10
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.IsMsgBlk()) {
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 // Filtered and compact block requests need a deserialized block.
3414 std::vector<uint8_t> block_data;
3415 if (!m_chainman.m_blockman.ReadRawBlock(block_data, block_pos)) {
3416 handle_block_read_error();
3417 return;
3418 }
3419 MakeAndPushMessage(pfrom, NetMsgType::BLOCK, Span{block_data});
3420 // Don't set pblock as we've sent the block
3421 } else {
3422 // Send block from disk
3423 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
3424 if (!m_chainman.m_blockman.ReadBlock(*pblockRead, block_pos)) {
3425 handle_block_read_error();
3426 return;
3427 }
3428 pblock = pblockRead;
3429 }
3430 if (pblock) {
3431 if (inv.IsMsgBlk()) {
3432 MakeAndPushMessage(pfrom, NetMsgType::BLOCK, *pblock);
3433 } else if (inv.IsMsgFilteredBlk()) {
3434 bool sendMerkleBlock = false;
3435 CMerkleBlock merkleBlock;
3436 if (auto tx_relay = peer.GetTxRelay()) {
3437 LOCK(tx_relay->m_bloom_filter_mutex);
3438 if (tx_relay->m_bloom_filter) {
3439 sendMerkleBlock = true;
3440 merkleBlock =
3441 CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
3442 }
3443 }
3444 if (sendMerkleBlock) {
3445 MakeAndPushMessage(pfrom, NetMsgType::MERKLEBLOCK, merkleBlock);
3446 // CMerkleBlock just contains hashes, so also push any
3447 // transactions in the block the client did not see. This avoids
3448 // hurting performance by pointlessly requiring a round-trip.
3449 // Note that there is currently no way for a node to request any
3450 // single transactions we didn't send here - they must either
3451 // disconnect and retry or request the full block. Thus, the
3452 // protocol spec specified allows for us to provide duplicate
3453 // txn here, however we MUST always provide at least what the
3454 // remote peer needs.
3455 typedef std::pair<size_t, uint256> PairType;
3456 for (PairType &pair : merkleBlock.vMatchedTxn) {
3457 MakeAndPushMessage(pfrom, NetMsgType::TX,
3458 *pblock->vtx[pair.first]);
3459 }
3460 }
3461 // else
3462 // no response
3463 } else if (inv.IsMsgCmpctBlk()) {
3464 // If a peer is asking for old blocks, we're almost guaranteed they
3465 // won't have a useful mempool to match against a compact block, and
3466 // we don't feel like constructing the object for them, so instead
3467 // we respond with the full, non-compact block.
3468 if (can_direct_fetch &&
3469 pindex->nHeight >= tip->nHeight - MAX_CMPCTBLOCK_DEPTH) {
3470 if (a_recent_compact_block &&
3471 a_recent_compact_block->header.GetHash() ==
3472 pindex->GetBlockHash()) {
3473 MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK,
3474 *a_recent_compact_block);
3475 } else {
3476 CBlockHeaderAndShortTxIDs cmpctblock(
3477 *pblock, FastRandomContext().rand64());
3478 MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK,
3479 cmpctblock);
3480 }
3481 } else {
3482 MakeAndPushMessage(pfrom, NetMsgType::BLOCK, *pblock);
3483 }
3484 }
3485 }
3486
3487 {
3488 LOCK(peer.m_block_inv_mutex);
3489 // Trigger the peer node to send a getblocks request for the next
3490 // batch of inventory.
3491 if (hash == peer.m_continuation_block) {
3492 // Send immediately. This must send even if redundant, and
3493 // we want it right after the last block so they don't wait for
3494 // other stuff first.
3495 std::vector<CInv> vInv;
3496 vInv.push_back(CInv(MSG_BLOCK, tip->GetBlockHash()));
3497 MakeAndPushMessage(pfrom, NetMsgType::INV, vInv);
3498 peer.m_continuation_block = BlockHash();
3499 }
3500 }
3501}
3502
3504PeerManagerImpl::FindTxForGetData(const Peer &peer, const TxId &txid,
3505 const std::chrono::seconds mempool_req,
3506 const std::chrono::seconds now) {
3507 auto txinfo = m_mempool.info(txid);
3508 if (txinfo.tx) {
3509 // If a TX could have been INVed in reply to a MEMPOOL request,
3510 // or is older than UNCONDITIONAL_RELAY_DELAY, permit the request
3511 // unconditionally.
3512 if ((mempool_req.count() && txinfo.m_time <= mempool_req) ||
3513 txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
3514 return std::move(txinfo.tx);
3515 }
3516 }
3517
3518 {
3519 LOCK(cs_main);
3520
3521 // Otherwise, the transaction might have been announced recently.
3522 bool recent =
3523 Assume(peer.GetTxRelay())->m_recently_announced_invs.contains(txid);
3524 if (recent && txinfo.tx) {
3525 return std::move(txinfo.tx);
3526 }
3527
3528 // Or it might be from the most recent block
3529 {
3530 LOCK(m_most_recent_block_mutex);
3531 if (m_most_recent_block_txs != nullptr) {
3532 auto it = m_most_recent_block_txs->find(txid);
3533 if (it != m_most_recent_block_txs->end()) {
3534 return it->second;
3535 }
3536 }
3537 }
3538 }
3539
3540 return {};
3541}
3542
3546PeerManagerImpl::FindProofForGetData(const Peer &peer,
3547 const avalanche::ProofId &proofid,
3548 const std::chrono::seconds now) {
3549 avalanche::ProofRef proof;
3550
3551 bool send_unconditionally =
3552 m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
3553 return pm.forPeer(proofid, [&](const avalanche::Peer &peer) {
3554 proof = peer.proof;
3555
3556 // If we know that proof for long enough, allow for requesting
3557 // it.
3558 return peer.registration_time <=
3560 });
3561 });
3562
3563 if (!proof) {
3564 // Always send our local proof if it gets requested, assuming it's
3565 // valid. This will make it easier to bind with peers upon startup where
3566 // the status of our proof is unknown pending for a block. Note that it
3567 // still needs to have been announced first (presumably via an avahello
3568 // message).
3569 proof = m_avalanche->getLocalProof();
3570 }
3571
3572 // We don't have this proof
3573 if (!proof) {
3574 return avalanche::ProofRef();
3575 }
3576
3577 if (send_unconditionally) {
3578 return proof;
3579 }
3580
3581 // Otherwise, the proofs must have been announced recently.
3582 if (peer.m_proof_relay->m_recently_announced_proofs.contains(proofid)) {
3583 return proof;
3584 }
3585
3586 return avalanche::ProofRef();
3587}
3588
3589void PeerManagerImpl::ProcessGetData(
3590 const Config &config, CNode &pfrom, Peer &peer,
3591 const std::atomic<bool> &interruptMsgProc) {
3593
3594 auto tx_relay = peer.GetTxRelay();
3595
3596 std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
3597 std::vector<CInv> vNotFound;
3598
3599 const auto now{GetTime<std::chrono::seconds>()};
3600 // Get last mempool request time
3601 const auto mempool_req = tx_relay != nullptr
3602 ? tx_relay->m_last_mempool_req.load()
3603 : std::chrono::seconds::min();
3604
3605 // Process as many TX or AVA_PROOF items from the front of the getdata
3606 // queue as possible, since they're common and it's efficient to batch
3607 // process them.
3608 while (it != peer.m_getdata_requests.end() &&
3609 (it->IsMsgProof() || it->IsMsgTx())) {
3610 if (interruptMsgProc) {
3611 return;
3612 }
3613 // The send buffer provides backpressure. If there's no space in
3614 // the buffer, pause processing until the next call.
3615 if (pfrom.fPauseSend) {
3616 break;
3617 }
3618
3619 const CInv &inv = *it++;
3620
3621 if (inv.IsMsgProof()) {
3622 if (!m_avalanche) {
3623 vNotFound.push_back(inv);
3624 continue;
3625 }
3626 const avalanche::ProofId proofid(inv.hash);
3627 auto proof = FindProofForGetData(peer, proofid, now);
3628 if (proof) {
3629 MakeAndPushMessage(pfrom, NetMsgType::AVAPROOF, *proof);
3630 m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
3631 pm.removeUnbroadcastProof(proofid);
3632 });
3633 } else {
3634 vNotFound.push_back(inv);
3635 }
3636
3637 continue;
3638 }
3639
3640 if (inv.IsMsgTx()) {
3641 if (tx_relay == nullptr) {
3642 // Ignore GETDATA requests for transactions from
3643 // block-relay-only peers and peers that asked us not to
3644 // announce transactions.
3645 continue;
3646 }
3647
3648 const TxId txid(inv.hash);
3649 CTransactionRef tx = FindTxForGetData(peer, txid, mempool_req, now);
3650 if (tx) {
3651 MakeAndPushMessage(pfrom, NetMsgType::TX, *tx);
3652 m_mempool.RemoveUnbroadcastTx(txid);
3653 // As we're going to send tx, make sure its unconfirmed parents
3654 // are made requestable.
3655 std::vector<TxId> parent_ids_to_add;
3656 {
3657 LOCK(m_mempool.cs);
3658 auto tx_iter = m_mempool.GetIter(tx->GetId());
3659 if (tx_iter) {
3660 auto &pentry = *tx_iter;
3661 const CTxMemPoolEntry::Parents &parents =
3662 (*pentry)->GetMemPoolParentsConst();
3663 parent_ids_to_add.reserve(parents.size());
3664 for (const auto &parent : parents) {
3665 if (parent.get()->GetTime() >
3667 parent_ids_to_add.push_back(
3668 parent.get()->GetTx().GetId());
3669 }
3670 }
3671 }
3672 }
3673 for (const TxId &parent_txid : parent_ids_to_add) {
3674 // Relaying a transaction with a recent but unconfirmed
3675 // parent.
3676 if (WITH_LOCK(tx_relay->m_tx_inventory_mutex,
3677 return !tx_relay->m_tx_inventory_known_filter
3678 .contains(parent_txid))) {
3679 tx_relay->m_recently_announced_invs.insert(parent_txid);
3680 }
3681 }
3682 } else {
3683 vNotFound.push_back(inv);
3684 }
3685
3686 continue;
3687 }
3688
3689 // It's neither a proof nor a transaction
3690 break;
3691 }
3692
3693 // Only process one BLOCK item per call, since they're uncommon and can be
3694 // expensive to process.
3695 if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
3696 const CInv &inv = *it++;
3697 if (inv.IsGenBlkMsg()) {
3698 ProcessGetBlockData(config, pfrom, peer, inv);
3699 }
3700 // else: If the first item on the queue is an unknown type, we erase it
3701 // and continue processing the queue on the next call.
3702 }
3703
3704 peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
3705
3706 if (!vNotFound.empty()) {
3707 // Let the peer know that we didn't find what it asked for, so it
3708 // doesn't have to wait around forever. SPV clients care about this
3709 // message: it's needed when they are recursively walking the
3710 // dependencies of relevant unconfirmed transactions. SPV clients want
3711 // to do that because they want to know about (and store and rebroadcast
3712 // and risk analyze) the dependencies of transactions relevant to them,
3713 // without having to download the entire memory pool. Also, other nodes
3714 // can use these messages to automatically request a transaction from
3715 // some other peer that annnounced it, and stop waiting for us to
3716 // respond. In normal operation, we often send NOTFOUND messages for
3717 // parents of transactions that we relay; if a peer is missing a parent,
3718 // they may assume we have them and request the parents from us.
3719 MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound);
3720 }
3721}
3722
3723void PeerManagerImpl::SendBlockTransactions(
3724 CNode &pfrom, Peer &peer, const CBlock &block,
3725 const BlockTransactionsRequest &req) {
3726 BlockTransactions resp(req);
3727 for (size_t i = 0; i < req.indices.size(); i++) {
3728 if (req.indices[i] >= block.vtx.size()) {
3729 Misbehaving(peer, "getblocktxn with out-of-bounds tx indices");
3730 return;
3731 }
3732 resp.txn[i] = block.vtx[req.indices[i]];
3733 }
3734 LOCK(cs_main);
3735 MakeAndPushMessage(pfrom, NetMsgType::BLOCKTXN, resp);
3736}
3737
3738bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader> &headers,
3739 const Consensus::Params &consensusParams,
3740 Peer &peer) {
3741 // Do these headers have proof-of-work matching what's claimed?
3742 if (!HasValidProofOfWork(headers, consensusParams)) {
3743 Misbehaving(peer, "header with invalid proof of work");
3744 return false;
3745 }
3746
3747 // Are these headers connected to each other?
3748 if (!CheckHeadersAreContinuous(headers)) {
3749 Misbehaving(peer, "non-continuous headers sequence");
3750 return false;
3751 }
3752 return true;
3753}
3754
3755arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold() {
3756 arith_uint256 near_chaintip_work = 0;
3757 LOCK(cs_main);
3758 if (m_chainman.ActiveChain().Tip() != nullptr) {
3759 const CBlockIndex *tip = m_chainman.ActiveChain().Tip();
3760 // Use a 144 block buffer, so that we'll accept headers that fork from
3761 // near our tip.
3762 near_chaintip_work =
3763 tip->nChainWork -
3764 std::min<arith_uint256>(144 * GetBlockProof(*tip), tip->nChainWork);
3765 }
3766 return std::max(near_chaintip_work, m_chainman.MinimumChainWork());
3767}
3768
3775void PeerManagerImpl::HandleUnconnectingHeaders(
3776 CNode &pfrom, Peer &peer, const std::vector<CBlockHeader> &headers) {
3777 // Try to fill in the missing headers.
3778 const CBlockIndex *best_header{
3779 WITH_LOCK(cs_main, return m_chainman.m_best_header)};
3780 if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) {
3781 LogPrint(
3782 BCLog::NET,
3783 "received header %s: missing prev block %s, sending getheaders "
3784 "(%d) to end (peer=%d)\n",
3785 headers[0].GetHash().ToString(),
3786 headers[0].hashPrevBlock.ToString(), best_header->nHeight,
3787 pfrom.GetId());
3788 }
3789
3790 // Set hashLastUnknownBlock for this peer, so that if we
3791 // eventually get the headers - even from a different peer -
3792 // we can use this peer to download.
3794 UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash()));
3795}
3796
3797bool PeerManagerImpl::CheckHeadersAreContinuous(
3798 const std::vector<CBlockHeader> &headers) const {
3799 BlockHash hashLastBlock;
3800 for (const CBlockHeader &header : headers) {
3801 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
3802 return false;
3803 }
3804 hashLastBlock = header.GetHash();
3805 }
3806 return true;
3807}
3808
3809bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(
3810 Peer &peer, CNode &pfrom, std::vector<CBlockHeader> &headers) {
3811 if (peer.m_headers_sync) {
3812 auto result = peer.m_headers_sync->ProcessNextHeaders(
3813 headers, headers.size() == MAX_HEADERS_RESULTS);
3814 // If it is a valid continuation, we should treat the existing
3815 // getheaders request as responded to.
3816 if (result.success) {
3817 peer.m_last_getheaders_timestamp = {};
3818 }
3819 if (result.request_more) {
3820 auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
3821 // If we were instructed to ask for a locator, it should not be
3822 // empty.
3823 Assume(!locator.vHave.empty());
3824 // We can only be instructed to request more if processing was
3825 // successful.
3826 Assume(result.success);
3827 if (!locator.vHave.empty()) {
3828 // It should be impossible for the getheaders request to fail,
3829 // because we just cleared the last getheaders timestamp.
3830 bool sent_getheaders =
3831 MaybeSendGetHeaders(pfrom, locator, peer);
3832 Assume(sent_getheaders);
3833 LogPrint(BCLog::NET, "more getheaders (from %s) to peer=%d\n",
3834 locator.vHave.front().ToString(), pfrom.GetId());
3835 }
3836 }
3837
3838 if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) {
3839 peer.m_headers_sync.reset(nullptr);
3840
3841 // Delete this peer's entry in m_headers_presync_stats.
3842 // If this is m_headers_presync_bestpeer, it will be replaced later
3843 // by the next peer that triggers the else{} branch below.
3844 LOCK(m_headers_presync_mutex);
3845 m_headers_presync_stats.erase(pfrom.GetId());
3846 } else {
3847 // Build statistics for this peer's sync.
3848 HeadersPresyncStats stats;
3849 stats.first = peer.m_headers_sync->GetPresyncWork();
3850 if (peer.m_headers_sync->GetState() ==
3852 stats.second = {peer.m_headers_sync->GetPresyncHeight(),
3853 peer.m_headers_sync->GetPresyncTime()};
3854 }
3855
3856 // Update statistics in stats.
3857 LOCK(m_headers_presync_mutex);
3858 m_headers_presync_stats[pfrom.GetId()] = stats;
3859 auto best_it =
3860 m_headers_presync_stats.find(m_headers_presync_bestpeer);
3861 bool best_updated = false;
3862 if (best_it == m_headers_presync_stats.end()) {
3863 // If the cached best peer is outdated, iterate over all
3864 // remaining ones (including newly updated one) to find the best
3865 // one.
3866 NodeId peer_best{-1};
3867 const HeadersPresyncStats *stat_best{nullptr};
3868 for (const auto &[_peer, _stat] : m_headers_presync_stats) {
3869 if (!stat_best || _stat > *stat_best) {
3870 peer_best = _peer;
3871 stat_best = &_stat;
3872 }
3873 }
3874 m_headers_presync_bestpeer = peer_best;
3875 best_updated = (peer_best == pfrom.GetId());
3876 } else if (best_it->first == pfrom.GetId() ||
3877 stats > best_it->second) {
3878 // pfrom was and remains the best peer, or pfrom just became
3879 // best.
3880 m_headers_presync_bestpeer = pfrom.GetId();
3881 best_updated = true;
3882 }
3883 if (best_updated && stats.second.has_value()) {
3884 // If the best peer updated, and it is in its first phase,
3885 // signal.
3886 m_headers_presync_should_signal = true;
3887 }
3888 }
3889
3890 if (result.success) {
3891 // We only overwrite the headers passed in if processing was
3892 // successful.
3893 headers.swap(result.pow_validated_headers);
3894 }
3895
3896 return result.success;
3897 }
3898 // Either we didn't have a sync in progress, or something went wrong
3899 // processing these headers, or we are returning headers to the caller to
3900 // process.
3901 return false;
3902}
3903
3904bool PeerManagerImpl::TryLowWorkHeadersSync(
3905 Peer &peer, CNode &pfrom, const CBlockIndex *chain_start_header,
3906 std::vector<CBlockHeader> &headers) {
3907 // Calculate the total work on this chain.
3908 arith_uint256 total_work =
3909 chain_start_header->nChainWork + CalculateHeadersWork(headers);
3910
3911 // Our dynamic anti-DoS threshold (minimum work required on a headers chain
3912 // before we'll store it)
3913 arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
3914
3915 // Avoid DoS via low-difficulty-headers by only processing if the headers
3916 // are part of a chain with sufficient work.
3917 if (total_work < minimum_chain_work) {
3918 // Only try to sync with this peer if their headers message was full;
3919 // otherwise they don't have more headers after this so no point in
3920 // trying to sync their too-little-work chain.
3921 if (headers.size() == MAX_HEADERS_RESULTS) {
3922 // Note: we could advance to the last header in this set that is
3923 // known to us, rather than starting at the first header (which we
3924 // may already have); however this is unlikely to matter much since
3925 // ProcessHeadersMessage() already handles the case where all
3926 // headers in a received message are already known and are
3927 // ancestors of m_best_header or chainActive.Tip(), by skipping
3928 // this logic in that case. So even if the first header in this set
3929 // of headers is known, some header in this set must be new, so
3930 // advancing to the first unknown header would be a small effect.
3931 LOCK(peer.m_headers_sync_mutex);
3932 peer.m_headers_sync.reset(
3933 new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(),
3934 chain_start_header, minimum_chain_work));
3935
3936 // Now a HeadersSyncState object for tracking this synchronization
3937 // is created, process the headers using it as normal. Failures are
3938 // handled inside of IsContinuationOfLowWorkHeadersSync.
3939 (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3940 } else {
3942 "Ignoring low-work chain (height=%u) from peer=%d\n",
3943 chain_start_header->nHeight + headers.size(),
3944 pfrom.GetId());
3945 }
3946 // The peer has not yet given us a chain that meets our work threshold,
3947 // so we want to prevent further processing of the headers in any case.
3948 headers = {};
3949 return true;
3950 }
3951
3952 return false;
3953}
3954
3955bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex *header) {
3956 return header != nullptr &&
3957 ((m_chainman.m_best_header != nullptr &&
3958 header ==
3959 m_chainman.m_best_header->GetAncestor(header->nHeight)) ||
3960 m_chainman.ActiveChain().Contains(header));
3961}
3962
3963bool PeerManagerImpl::MaybeSendGetHeaders(CNode &pfrom,
3964 const CBlockLocator &locator,
3965 Peer &peer) {
3966 const auto current_time = NodeClock::now();
3967
3968 // Only allow a new getheaders message to go out if we don't have a recent
3969 // one already in-flight
3970 if (current_time - peer.m_last_getheaders_timestamp >
3972 MakeAndPushMessage(pfrom, NetMsgType::GETHEADERS, locator, uint256());
3973 peer.m_last_getheaders_timestamp = current_time;
3974 return true;
3975 }
3976 return false;
3977}
3978
3985void PeerManagerImpl::HeadersDirectFetchBlocks(const Config &config,
3986 CNode &pfrom,
3987 const CBlockIndex &last_header) {
3988 LOCK(cs_main);
3989 CNodeState *nodestate = State(pfrom.GetId());
3990
3991 if (CanDirectFetch() && last_header.IsValid(BlockValidity::TREE) &&
3992 m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork) {
3993 std::vector<const CBlockIndex *> vToFetch;
3994 const CBlockIndex *pindexWalk{&last_header};
3995 // Calculate all the blocks we'd need to switch to last_header, up to
3996 // a limit.
3997 while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) &&
3998 vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3999 if (!pindexWalk->nStatus.hasData() &&
4000 !IsBlockRequested(pindexWalk->GetBlockHash())) {
4001 // We don't have this block, and it's not yet in flight.
4002 vToFetch.push_back(pindexWalk);
4003 }
4004 pindexWalk = pindexWalk->pprev;
4005 }
4006 // If pindexWalk still isn't on our main chain, we're looking at a
4007 // very large reorg at a time we think we're close to caught up to
4008 // the main chain -- this shouldn't really happen. Bail out on the
4009 // direct fetch and rely on parallel download instead.
4010 if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
4011 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
4012 last_header.GetBlockHash().ToString(),
4013 last_header.nHeight);
4014 } else {
4015 std::vector<CInv> vGetData;
4016 // Download as much as possible, from earliest to latest.
4017 for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
4018 if (nodestate->vBlocksInFlight.size() >=
4020 // Can't download any more from this peer
4021 break;
4022 }
4023 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4024 BlockRequested(config, pfrom.GetId(), *pindex);
4025 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
4026 pindex->GetBlockHash().ToString(), pfrom.GetId());
4027 }
4028 if (vGetData.size() > 1) {
4030 "Downloading blocks toward %s (%d) via headers "
4031 "direct fetch\n",
4032 last_header.GetBlockHash().ToString(),
4033 last_header.nHeight);
4034 }
4035 if (vGetData.size() > 0) {
4036 if (!m_opts.ignore_incoming_txs &&
4037 nodestate->m_provides_cmpctblocks && vGetData.size() == 1 &&
4038 mapBlocksInFlight.size() == 1 &&
4039 last_header.pprev->IsValid(BlockValidity::CHAIN)) {
4040 // In any case, we want to download using a compact
4041 // block, not a regular one.
4042 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
4043 }
4044 MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vGetData);
4045 }
4046 }
4047 }
4048}
4049
4055void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(
4056 CNode &pfrom, Peer &peer, const CBlockIndex &last_header,
4057 bool received_new_header, bool may_have_more_headers) {
4058 LOCK(cs_main);
4059
4060 CNodeState *nodestate = State(pfrom.GetId());
4061
4062 UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash());
4063
4064 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
4065 // because it is set in UpdateBlockAvailability. Some nullptr checks are
4066 // still present, however, as belt-and-suspenders.
4067
4068 if (received_new_header &&
4069 last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
4070 nodestate->m_last_block_announcement = GetTime();
4071 }
4072
4073 // If we're in IBD, we want outbound peers that will serve us a useful
4074 // chain. Disconnect peers that are on chains with insufficient work.
4075 if (m_chainman.IsInitialBlockDownload() && !may_have_more_headers) {
4076 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
4077 // headers to fetch from this peer.
4078 if (nodestate->pindexBestKnownBlock &&
4079 nodestate->pindexBestKnownBlock->nChainWork <
4080 m_chainman.MinimumChainWork()) {
4081 // This peer has too little work on their headers chain to help
4082 // us sync -- disconnect if it is an outbound disconnection
4083 // candidate.
4084 // Note: We compare their tip to the minimum chain work (rather than
4085 // m_chainman.ActiveChain().Tip()) because we won't start block
4086 // download until we have a headers chain that has at least
4087 // the minimum chain work, even if a peer has a chain past our tip,
4088 // as an anti-DoS measure.
4089 if (pfrom.IsOutboundOrBlockRelayConn()) {
4090 LogPrintf("Disconnecting outbound peer %d -- headers "
4091 "chain has insufficient work\n",
4092 pfrom.GetId());
4093 pfrom.fDisconnect = true;
4094 }
4095 }
4096 }
4097
4098 // If this is an outbound full-relay peer, check to see if we should
4099 // protect it from the bad/lagging chain logic.
4100 // Note that outbound block-relay peers are excluded from this
4101 // protection, and thus always subject to eviction under the bad/lagging
4102 // chain logic.
4103 // See ChainSyncTimeoutState.
4104 if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() &&
4105 nodestate->pindexBestKnownBlock != nullptr) {
4106 if (m_outbound_peers_with_protect_from_disconnect <
4108 nodestate->pindexBestKnownBlock->nChainWork >=
4109 m_chainman.ActiveChain().Tip()->nChainWork &&
4110 !nodestate->m_chain_sync.m_protect) {
4111 LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n",
4112 pfrom.GetId());
4113 nodestate->m_chain_sync.m_protect = true;
4114 ++m_outbound_peers_with_protect_from_disconnect;
4115 }
4116 }
4117}
4118
4119void PeerManagerImpl::ProcessHeadersMessage(const Config &config, CNode &pfrom,
4120 Peer &peer,
4121 std::vector<CBlockHeader> &&headers,
4122 bool via_compact_block) {
4123 size_t nCount = headers.size();
4124
4125 if (nCount == 0) {
4126 // Nothing interesting. Stop asking this peers for more headers.
4127 // If we were in the middle of headers sync, receiving an empty headers
4128 // message suggests that the peer suddenly has nothing to give us
4129 // (perhaps it reorged to our chain). Clear download state for this
4130 // peer.
4131 LOCK(peer.m_headers_sync_mutex);
4132 if (peer.m_headers_sync) {
4133 peer.m_headers_sync.reset(nullptr);
4134 LOCK(m_headers_presync_mutex);
4135 m_headers_presync_stats.erase(pfrom.GetId());
4136 }
4137 // A headers message with no headers cannot be an announcement, so
4138 // assume it is a response to our last getheaders request, if there is
4139 // one.
4140 peer.m_last_getheaders_timestamp = {};
4141 return;
4142 }
4143
4144 // Before we do any processing, make sure these pass basic sanity checks.
4145 // We'll rely on headers having valid proof-of-work further down, as an
4146 // anti-DoS criteria (note: this check is required before passing any
4147 // headers into HeadersSyncState).
4148 if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) {
4149 // Misbehaving() calls are handled within CheckHeadersPoW(), so we can
4150 // just return. (Note that even if a header is announced via compact
4151 // block, the header itself should be valid, so this type of error can
4152 // always be punished.)
4153 return;
4154 }
4155
4156 const CBlockIndex *pindexLast = nullptr;
4157
4158 // We'll set already_validated_work to true if these headers are
4159 // successfully processed as part of a low-work headers sync in progress
4160 // (either in PRESYNC or REDOWNLOAD phase).
4161 // If true, this will mean that any headers returned to us (ie during
4162 // REDOWNLOAD) can be validated without further anti-DoS checks.
4163 bool already_validated_work = false;
4164
4165 // If we're in the middle of headers sync, let it do its magic.
4166 bool have_headers_sync = false;
4167 {
4168 LOCK(peer.m_headers_sync_mutex);
4169
4170 already_validated_work =
4171 IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
4172
4173 // The headers we passed in may have been:
4174 // - untouched, perhaps if no headers-sync was in progress, or some
4175 // failure occurred
4176 // - erased, such as if the headers were successfully processed and no
4177 // additional headers processing needs to take place (such as if we
4178 // are still in PRESYNC)
4179 // - replaced with headers that are now ready for validation, such as
4180 // during the REDOWNLOAD phase of a low-work headers sync.
4181 // So just check whether we still have headers that we need to process,
4182 // or not.
4183 if (headers.empty()) {
4184 return;
4185 }
4186
4187 have_headers_sync = !!peer.m_headers_sync;
4188 }
4189
4190 // Do these headers connect to something in our block index?
4191 const CBlockIndex *chain_start_header{
4193 headers[0].hashPrevBlock))};
4194 bool headers_connect_blockindex{chain_start_header != nullptr};
4195
4196 if (!headers_connect_blockindex) {
4197 // This could be a BIP 130 block announcement, use
4198 // special logic for handling headers that don't connect, as this
4199 // could be benign.
4200 HandleUnconnectingHeaders(pfrom, peer, headers);
4201 return;
4202 }
4203
4204 // If headers connect, assume that this is in response to any outstanding
4205 // getheaders request we may have sent, and clear out the time of our last
4206 // request. Non-connecting headers cannot be a response to a getheaders
4207 // request.
4208 peer.m_last_getheaders_timestamp = {};
4209
4210 // If the headers we received are already in memory and an ancestor of
4211 // m_best_header or our tip, skip anti-DoS checks. These headers will not
4212 // use any more memory (and we are not leaking information that could be
4213 // used to fingerprint us).
4214 const CBlockIndex *last_received_header{nullptr};
4215 {
4216 LOCK(cs_main);
4217 last_received_header =
4218 m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash());
4219 if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
4220 already_validated_work = true;
4221 }
4222 }
4223
4224 // If our peer has NetPermissionFlags::NoBan privileges, then bypass our
4225 // anti-DoS logic (this saves bandwidth when we connect to a trusted peer
4226 // on startup).
4228 already_validated_work = true;
4229 }
4230
4231 // At this point, the headers connect to something in our block index.
4232 // Do anti-DoS checks to determine if we should process or store for later
4233 // processing.
4234 if (!already_validated_work &&
4235 TryLowWorkHeadersSync(peer, pfrom, chain_start_header, headers)) {
4236 // If we successfully started a low-work headers sync, then there
4237 // should be no headers to process any further.
4238 Assume(headers.empty());
4239 return;
4240 }
4241
4242 // At this point, we have a set of headers with sufficient work on them
4243 // which can be processed.
4244
4245 // If we don't have the last header, then this peer will have given us
4246 // something new (if these headers are valid).
4247 bool received_new_header{last_received_header == nullptr};
4248
4249 // Now process all the headers.
4251 if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true,
4252 state, &pindexLast)) {
4253 if (state.IsInvalid()) {
4254 MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block,
4255 "invalid header received");
4256 return;
4257 }
4258 }
4259
4260 if (!pindexLast) {
4261 LogError("headers message processed but no pindexLast\n");
4262 // Nothing to do here
4263 return;
4264 }
4265
4266 // Consider fetching more headers if we are not using our headers-sync
4267 // mechanism.
4268 if (nCount == MAX_HEADERS_RESULTS && !have_headers_sync) {
4269 // Headers message had its maximum size; the peer may have more headers.
4270 if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) {
4271 LogPrint(
4272 BCLog::NET,
4273 "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
4274 pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
4275 }
4276 }
4277
4278 UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast,
4279 received_new_header,
4280 nCount == MAX_HEADERS_RESULTS);
4281
4282 // Consider immediately downloading blocks.
4283 HeadersDirectFetchBlocks(config, pfrom, *pindexLast);
4284}
4285
4286void PeerManagerImpl::ProcessInvalidTx(NodeId nodeid,
4287 const CTransactionRef &ptx,
4288 const TxValidationState &state,
4289 bool maybe_add_extra_compact_tx) {
4290 AssertLockNotHeld(m_peer_mutex);
4291 AssertLockHeld(g_msgproc_mutex);
4293
4294 const TxId &txid = ptx->GetId();
4295
4296 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n",
4297 txid.ToString(), nodeid, state.ToString());
4298
4300 return;
4301 }
4302
4303 if (m_avalanche &&
4304 m_avalanche->isPreconsensusActivated(m_chainman.ActiveTip()) &&
4306 return;
4307 }
4308
4310 // If the result is TX_PACKAGE_RECONSIDERABLE, add it to
4311 // m_recent_rejects_package_reconsiderable because we should not
4312 // download or submit this transaction by itself again, but may submit
4313 // it as part of a package later.
4314 m_recent_rejects_package_reconsiderable.insert(txid);
4315 } else {
4316 m_recent_rejects.insert(txid);
4317 }
4318 m_txrequest.ForgetInvId(txid);
4319
4320 if (maybe_add_extra_compact_tx && RecursiveDynamicUsage(*ptx) < 100000) {
4321 AddToCompactExtraTransactions(ptx);
4322 }
4323
4324 MaybePunishNodeForTx(nodeid, state);
4325
4326 // If the tx failed in ProcessOrphanTx, it should be removed from the
4327 // orphanage unless the tx was still missing inputs. If the tx was not in
4328 // the orphanage, EraseTx does nothing and returns 0.
4329 if (m_mempool.withOrphanage([&txid](TxOrphanage &orphanage) {
4330 return orphanage.EraseTx(txid);
4331 }) > 0) {
4332 LogPrint(BCLog::TXPACKAGES, " removed orphan tx %s\n",
4333 txid.ToString());
4334 }
4335}
4336
4337void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef &tx) {
4338 AssertLockNotHeld(m_peer_mutex);
4339 AssertLockHeld(g_msgproc_mutex);
4341
4342 // As this version of the transaction was acceptable, we can forget about
4343 // any requests for it. No-op if the tx is not in txrequest.
4344 m_txrequest.ForgetInvId(tx->GetId());
4345
4346 m_mempool.withOrphanage([&tx](TxOrphanage &orphanage) {
4347 orphanage.AddChildrenToWorkSet(*tx);
4348 // If it came from the orphanage, remove it. No-op if the tx is not in
4349 // txorphanage.
4350 orphanage.EraseTx(tx->GetId());
4351 });
4352
4353 LogPrint(
4355 "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4356 nodeid, tx->GetId().ToString(), m_mempool.size(),
4357 m_mempool.DynamicMemoryUsage() / 1000);
4358
4359 RelayTransaction(tx->GetId());
4360}
4361
4362void PeerManagerImpl::ProcessPackageResult(
4363 const PackageToValidate &package_to_validate,
4364 const PackageMempoolAcceptResult &package_result) {
4365 AssertLockNotHeld(m_peer_mutex);
4366 AssertLockHeld(g_msgproc_mutex);
4368
4369 const auto &package = package_to_validate.m_txns;
4370 const auto &senders = package_to_validate.m_senders;
4371
4372 if (package_result.m_state.IsInvalid()) {
4373 m_recent_rejects_package_reconsiderable.insert(GetPackageHash(package));
4374 }
4375 // We currently only expect to process 1-parent-1-child packages. Remove if
4376 // this changes.
4377 if (!Assume(package.size() == 2)) {
4378 return;
4379 }
4380
4381 // Iterate backwards to erase in-package descendants from the orphanage
4382 // before they become relevant in AddChildrenToWorkSet.
4383 auto package_iter = package.rbegin();
4384 auto senders_iter = senders.rbegin();
4385 while (package_iter != package.rend()) {
4386 const auto &tx = *package_iter;
4387 const NodeId nodeid = *senders_iter;
4388 const auto it_result{package_result.m_tx_results.find(tx->GetId())};
4389
4390 // It is not guaranteed that a result exists for every transaction.
4391 if (it_result != package_result.m_tx_results.end()) {
4392 const auto &tx_result = it_result->second;
4393 switch (tx_result.m_result_type) {
4395 ProcessValidTx(nodeid, tx);
4396 break;
4397 }
4399 // Don't add to vExtraTxnForCompact, as these transactions
4400 // should have already been added there when added to the
4401 // orphanage or rejected for TX_PACKAGE_RECONSIDERABLE.
4402 // This should be updated if package submission is ever used
4403 // for transactions that haven't already been validated
4404 // before.
4405 ProcessInvalidTx(nodeid, tx, tx_result.m_state,
4406 /*maybe_add_extra_compact_tx=*/false);
4407 break;
4408 }
4410 // AlreadyHaveTx() should be catching transactions that are
4411 // already in mempool.
4412 Assume(false);
4413 break;
4414 }
4415 }
4416 }
4417 package_iter++;
4418 senders_iter++;
4419 }
4420}
4421
4422std::optional<PeerManagerImpl::PackageToValidate>
4423PeerManagerImpl::Find1P1CPackage(const CTransactionRef &ptx, NodeId nodeid) {
4424 AssertLockNotHeld(m_peer_mutex);
4425 AssertLockHeld(g_msgproc_mutex);
4427
4428 const auto &parent_txid{ptx->GetId()};
4429
4430 Assume(m_recent_rejects_package_reconsiderable.contains(parent_txid));
4431
4432 // Prefer children from this peer. This helps prevent censorship attempts in
4433 // which an attacker sends lots of fake children for the parent, and we
4434 // (unluckily) keep selecting the fake children instead of the real one
4435 // provided by the honest peer.
4436 const auto cpfp_candidates_same_peer{
4437 m_mempool.withOrphanage([&ptx, nodeid](const TxOrphanage &orphanage) {
4438 return orphanage.GetChildrenFromSamePeer(ptx, nodeid);
4439 })};
4440
4441 // These children should be sorted from newest to oldest.
4442 for (const auto &child : cpfp_candidates_same_peer) {
4443 Package maybe_cpfp_package{ptx, child};
4444 if (!m_recent_rejects_package_reconsiderable.contains(
4445 GetPackageHash(maybe_cpfp_package))) {
4446 return PeerManagerImpl::PackageToValidate{ptx, child, nodeid,
4447 nodeid};
4448 }
4449 }
4450
4451 // If no suitable candidate from the same peer is found, also try children
4452 // that were provided by a different peer. This is useful because sometimes
4453 // multiple peers announce both transactions to us, and we happen to
4454 // download them from different peers (we wouldn't have known that these 2
4455 // transactions are related). We still want to find 1p1c packages then.
4456 //
4457 // If we start tracking all announcers of orphans, we can restrict this
4458 // logic to parent + child pairs in which both were provided by the same
4459 // peer, i.e. delete this step.
4460 const auto cpfp_candidates_different_peer{
4461 m_mempool.withOrphanage([&ptx, nodeid](const TxOrphanage &orphanage) {
4462 return orphanage.GetChildrenFromDifferentPeer(ptx, nodeid);
4463 })};
4464
4465 // Find the first 1p1c that hasn't already been rejected. We randomize the
4466 // order to not create a bias that attackers can use to delay package
4467 // acceptance.
4468 //
4469 // Create a random permutation of the indices.
4470 std::vector<size_t> tx_indices(cpfp_candidates_different_peer.size());
4471 std::iota(tx_indices.begin(), tx_indices.end(), 0);
4472 Shuffle(tx_indices.begin(), tx_indices.end(), m_rng);
4473
4474 for (const auto index : tx_indices) {
4475 // If we already tried a package and failed for any reason, the combined
4476 // hash was cached in m_recent_rejects_package_reconsiderable.
4477 const auto [child_tx, child_sender] =
4478 cpfp_candidates_different_peer.at(index);
4479 Package maybe_cpfp_package{ptx, child_tx};
4480 if (!m_recent_rejects_package_reconsiderable.contains(
4481 GetPackageHash(maybe_cpfp_package))) {
4482 return PeerManagerImpl::PackageToValidate{ptx, child_tx, nodeid,
4483 child_sender};
4484 }
4485 }
4486 return std::nullopt;
4487}
4488
4489bool PeerManagerImpl::ProcessOrphanTx(const Config &config, Peer &peer) {
4490 AssertLockHeld(g_msgproc_mutex);
4491 LOCK(cs_main);
4492
4493 while (CTransactionRef porphanTx =
4494 m_mempool.withOrphanage([&peer](TxOrphanage &orphanage) {
4495 return orphanage.GetTxToReconsider(peer.m_id);
4496 })) {
4497 const MempoolAcceptResult result =
4498 m_chainman.ProcessTransaction(porphanTx);
4499 const TxValidationState &state = result.m_state;
4500 const TxId &orphanTxId = porphanTx->GetId();
4501
4503 LogPrint(BCLog::TXPACKAGES, " accepted orphan tx %s\n",
4504 orphanTxId.ToString());
4505 ProcessValidTx(peer.m_id, porphanTx);
4506 return true;
4507 }
4508
4511 " invalid orphan tx %s from peer=%d. %s\n",
4512 orphanTxId.ToString(), peer.m_id, state.ToString());
4513
4514 if (Assume(state.IsInvalid() &&
4516 state.GetResult() !=
4518 ProcessInvalidTx(peer.m_id, porphanTx, state,
4519 /*maybe_add_extra_compact_tx=*/false);
4520 }
4521
4522 return true;
4523 }
4524 }
4525
4526 return false;
4527}
4528
4529bool PeerManagerImpl::PrepareBlockFilterRequest(
4530 CNode &node, Peer &peer, BlockFilterType filter_type, uint32_t start_height,
4531 const BlockHash &stop_hash, uint32_t max_height_diff,
4532 const CBlockIndex *&stop_index, BlockFilterIndex *&filter_index) {
4533 const bool supported_filter_type =
4534 (filter_type == BlockFilterType::BASIC &&
4535 (peer.m_our_services & NODE_COMPACT_FILTERS));
4536 if (!supported_filter_type) {
4538 "peer %d requested unsupported block filter type: %d\n",
4539 node.GetId(), static_cast<uint8_t>(filter_type));
4540 node.fDisconnect = true;
4541 return false;
4542 }
4543
4544 {
4545 LOCK(cs_main);
4546 stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
4547
4548 // Check that the stop block exists and the peer would be allowed to
4549 // fetch it.
4550 if (!stop_index || !BlockRequestAllowed(stop_index)) {
4551 LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
4552 node.GetId(), stop_hash.ToString());
4553 node.fDisconnect = true;
4554 return false;
4555 }
4556 }
4557
4558 uint32_t stop_height = stop_index->nHeight;
4559 if (start_height > stop_height) {
4560 LogPrint(
4561 BCLog::NET,
4562 "peer %d sent invalid getcfilters/getcfheaders with " /* Continued
4563 */
4564 "start height %d and stop height %d\n",
4565 node.GetId(), start_height, stop_height);
4566 node.fDisconnect = true;
4567 return false;
4568 }
4569 if (stop_height - start_height >= max_height_diff) {
4571 "peer %d requested too many cfilters/cfheaders: %d / %d\n",
4572 node.GetId(), stop_height - start_height + 1, max_height_diff);
4573 node.fDisconnect = true;
4574 return false;
4575 }
4576
4577 filter_index = GetBlockFilterIndex(filter_type);
4578 if (!filter_index) {
4579 LogPrint(BCLog::NET, "Filter index for supported type %s not found\n",
4580 BlockFilterTypeName(filter_type));
4581 return false;
4582 }
4583
4584 return true;
4585}
4586
4587void PeerManagerImpl::ProcessGetCFilters(CNode &node, Peer &peer,
4588 DataStream &vRecv) {
4589 uint8_t filter_type_ser;
4590 uint32_t start_height;
4591 BlockHash stop_hash;
4592
4593 vRecv >> filter_type_ser >> start_height >> stop_hash;
4594
4595 const BlockFilterType filter_type =
4596 static_cast<BlockFilterType>(filter_type_ser);
4597
4598 const CBlockIndex *stop_index;
4599 BlockFilterIndex *filter_index;
4600 if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height,
4601 stop_hash, MAX_GETCFILTERS_SIZE, stop_index,
4602 filter_index)) {
4603 return;
4604 }
4605
4606 std::vector<BlockFilter> filters;
4607 if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
4609 "Failed to find block filter in index: filter_type=%s, "
4610 "start_height=%d, stop_hash=%s\n",
4611 BlockFilterTypeName(filter_type), start_height,
4612 stop_hash.ToString());
4613 return;
4614 }
4615
4616 for (const auto &filter : filters) {
4617 MakeAndPushMessage(node, NetMsgType::CFILTER, filter);
4618 }
4619}
4620
4621void PeerManagerImpl::ProcessGetCFHeaders(CNode &node, Peer &peer,
4622 DataStream &vRecv) {
4623 uint8_t filter_type_ser;
4624 uint32_t start_height;
4625 BlockHash stop_hash;
4626
4627 vRecv >> filter_type_ser >> start_height >> stop_hash;
4628
4629 const BlockFilterType filter_type =
4630 static_cast<BlockFilterType>(filter_type_ser);
4631
4632 const CBlockIndex *stop_index;
4633 BlockFilterIndex *filter_index;
4634 if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height,
4635 stop_hash, MAX_GETCFHEADERS_SIZE, stop_index,
4636 filter_index)) {
4637 return;
4638 }
4639
4640 uint256 prev_header;
4641 if (start_height > 0) {
4642 const CBlockIndex *const prev_block =
4643 stop_index->GetAncestor(static_cast<int>(start_height - 1));
4644 if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
4646 "Failed to find block filter header in index: "
4647 "filter_type=%s, block_hash=%s\n",
4648 BlockFilterTypeName(filter_type),
4649 prev_block->GetBlockHash().ToString());
4650 return;
4651 }
4652 }
4653
4654 std::vector<uint256> filter_hashes;
4655 if (!filter_index->LookupFilterHashRange(start_height, stop_index,
4656 filter_hashes)) {
4658 "Failed to find block filter hashes in index: filter_type=%s, "
4659 "start_height=%d, stop_hash=%s\n",
4660 BlockFilterTypeName(filter_type), start_height,
4661 stop_hash.ToString());
4662 return;
4663 }
4664
4665 MakeAndPushMessage(node, NetMsgType::CFHEADERS, filter_type_ser,
4666 stop_index->GetBlockHash(), prev_header, filter_hashes);
4667}
4668
4669void PeerManagerImpl::ProcessGetCFCheckPt(CNode &node, Peer &peer,
4670 DataStream &vRecv) {
4671 uint8_t filter_type_ser;
4672 BlockHash stop_hash;
4673
4674 vRecv >> filter_type_ser >> stop_hash;
4675
4676 const BlockFilterType filter_type =
4677 static_cast<BlockFilterType>(filter_type_ser);
4678
4679 const CBlockIndex *stop_index;
4680 BlockFilterIndex *filter_index;
4681 if (!PrepareBlockFilterRequest(
4682 node, peer, filter_type, /*start_height=*/0, stop_hash,
4683 /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
4684 stop_index, filter_index)) {
4685 return;
4686 }
4687
4688 std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
4689
4690 // Populate headers.
4691 const CBlockIndex *block_index = stop_index;
4692 for (int i = headers.size() - 1; i >= 0; i--) {
4693 int height = (i + 1) * CFCHECKPT_INTERVAL;
4694 block_index = block_index->GetAncestor(height);
4695
4696 if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
4698 "Failed to find block filter header in index: "
4699 "filter_type=%s, block_hash=%s\n",
4700 BlockFilterTypeName(filter_type),
4701 block_index->GetBlockHash().ToString());
4702 return;
4703 }
4704 }
4705
4706 MakeAndPushMessage(node, NetMsgType::CFCHECKPT, filter_type_ser,
4707 stop_index->GetBlockHash(), headers);
4708}
4709
4710bool IsAvalancheMessageType(const std::string &msg_type) {
4711 return msg_type == NetMsgType::AVAHELLO ||
4712 msg_type == NetMsgType::AVAPOLL ||
4713 msg_type == NetMsgType::AVARESPONSE ||
4714 msg_type == NetMsgType::AVAPROOF ||
4715 msg_type == NetMsgType::GETAVAADDR ||
4716 msg_type == NetMsgType::GETAVAPROOFS ||
4717 msg_type == NetMsgType::AVAPROOFS ||
4718 msg_type == NetMsgType::AVAPROOFSREQ;
4719}
4720
4721uint32_t
4722PeerManagerImpl::GetAvalancheVoteForBlock(const BlockHash &hash) const {
4724
4725 const CBlockIndex *pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
4726
4727 // Unknown block.
4728 if (!pindex) {
4729 return -1;
4730 }
4731
4732 // Invalid block
4733 if (pindex->nStatus.isInvalid()) {
4734 return 1;
4735 }
4736
4737 // Parked block
4738 if (pindex->nStatus.isOnParkedChain()) {
4739 return 2;
4740 }
4741
4742 const CBlockIndex *pindexTip = m_chainman.ActiveChain().Tip();
4743 const CBlockIndex *pindexFork = LastCommonAncestor(pindex, pindexTip);
4744
4745 // Active block.
4746 if (pindex == pindexFork) {
4747 return 0;
4748 }
4749
4750 // Fork block.
4751 if (pindexFork != pindexTip) {
4752 return 3;
4753 }
4754
4755 // Missing block data.
4756 if (!pindex->nStatus.hasData()) {
4757 return -2;
4758 }
4759
4760 // This block is built on top of the tip, we have the data, it
4761 // is pending connection or rejection.
4762 return -3;
4763};
4764
4765uint32_t
4766PeerManagerImpl::GetAvalancheVoteForTx(const avalanche::Processor &avalanche,
4767 const TxId &id) const {
4768 // Recently confirmed
4769 if (WITH_LOCK(m_recent_confirmed_transactions_mutex,
4770 return m_recent_confirmed_transactions.contains(id))) {
4771 return 0;
4772 }
4773
4774 CTransactionRef mempool_tx;
4775 {
4776 LOCK(::cs_main);
4777
4778 // Invalid tx. m_recent_rejects needs cs_main
4779 if (m_recent_rejects.contains(id)) {
4780 return 1;
4781 }
4782
4783 LOCK(m_mempool.cs);
4784
4785 // Finalized
4786 if (m_mempool.isAvalancheFinalizedPreConsensus(id)) {
4787 return 0;
4788 }
4789
4790 // Accepted in mempool
4791 if (auto iter = m_mempool.GetIter(id)) {
4792 mempool_tx = (**iter)->GetSharedTx();
4793 } else {
4794 // Conflicting tx
4795 if (m_mempool.withConflicting(
4796 [&id](const TxConflicting &conflicting) {
4797 return conflicting.HaveTx(id);
4798 })) {
4799 return 2;
4800 }
4801
4802 // Orphan tx
4803 if (m_mempool.withOrphanage([&id](const TxOrphanage &orphanage) {
4804 return orphanage.HaveTx(id);
4805 })) {
4806 return -2;
4807 }
4808 }
4809 } // release cs_main and mempool.cs locks
4810
4811 // isPolled() access the vote records, and should be accessed with cs_main
4812 // released.
4813 // If the tx is in the mempool...
4814 if (mempool_tx) {
4815 // ... and in the polled list
4816 if (avalanche.isPolled(mempool_tx)) {
4817 return 0;
4818 }
4819
4820 // ... but not in the polled list
4821 return -3;
4822 }
4823
4824 // Unknown tx
4825 return -1;
4826};
4827
4835 const avalanche::ProofId &id) {
4836 return avalanche.withPeerManager([&id](avalanche::PeerManager &pm) {
4837 // Rejected proof
4838 if (pm.isInvalid(id)) {
4839 return 1;
4840 }
4841
4842 // The proof is actively bound to a peer
4843 if (pm.isBoundToPeer(id)) {
4844 return 0;
4845 }
4846
4847 // Unknown proof
4848 if (!pm.exists(id)) {
4849 return -1;
4850 }
4851
4852 // Immature proof
4853 if (pm.isImmature(id)) {
4854 return 2;
4855 }
4856
4857 // Not immature, but in conflict with an actively bound proof
4858 if (pm.isInConflictingPool(id)) {
4859 return 3;
4860 }
4861
4862 // The proof is known, not rejected, not immature, not a conflict, but
4863 // for some reason unbound. This should not happen if the above pools
4864 // are managed correctly, but added for robustness.
4865 return -2;
4866 });
4867};
4868
4869void PeerManagerImpl::ProcessBlock(const Config &config, CNode &node,
4870 const std::shared_ptr<const CBlock> &block,
4871 bool force_processing,
4872 bool min_pow_checked) {
4873 bool new_block{false};
4874 m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked,
4875 &new_block, m_avalanche);
4876 if (new_block) {
4877 node.m_last_block_time = GetTime<std::chrono::seconds>();
4878 // In case this block came from a different peer than we requested
4879 // from, we can erase the block request now anyway (as we just stored
4880 // this block to disk).
4881 LOCK(cs_main);
4882 RemoveBlockRequest(block->GetHash(), std::nullopt);
4883 } else {
4884 LOCK(cs_main);
4885 mapBlockSource.erase(block->GetHash());
4886 }
4887}
4888
4889void PeerManagerImpl::ProcessMessage(
4890 const Config &config, CNode &pfrom, const std::string &msg_type,
4891 DataStream &vRecv, const std::chrono::microseconds time_received,
4892 const std::atomic<bool> &interruptMsgProc) {
4893 AssertLockHeld(g_msgproc_mutex);
4894
4895 LogPrint(BCLog::NETDEBUG, "received: %s (%u bytes) peer=%d\n",
4896 SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
4897
4898 PeerRef peer = GetPeerRef(pfrom.GetId());
4899 if (peer == nullptr) {
4900 return;
4901 }
4902
4903 if (!m_avalanche && IsAvalancheMessageType(msg_type)) {
4905 "Avalanche is not initialized, ignoring %s message\n",
4906 msg_type);
4907 return;
4908 }
4909
4910 if (msg_type == NetMsgType::VERSION) {
4911 // Each connection can only send one version message
4912 if (pfrom.nVersion != 0) {
4913 LogPrint(BCLog::NET, "redundant version message from peer=%d\n",
4914 pfrom.GetId());
4915 return;
4916 }
4917
4918 int64_t nTime;
4919 CService addrMe;
4920 uint64_t nNonce = 1;
4921 ServiceFlags nServices;
4922 int nVersion;
4923 std::string cleanSubVer;
4924 int starting_height = -1;
4925 bool fRelay = true;
4926 uint64_t nExtraEntropy = 1;
4927
4928 vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
4929 if (nTime < 0) {
4930 nTime = 0;
4931 }
4932 // Ignore the addrMe service bits sent by the peer
4933 vRecv.ignore(8);
4934 vRecv >> WithParams(CNetAddr::V1, addrMe);
4935 if (!pfrom.IsInboundConn()) {
4936 m_addrman.SetServices(pfrom.addr, nServices);
4937 }
4938 if (pfrom.ExpectServicesFromConn() &&
4939 !HasAllDesirableServiceFlags(nServices)) {
4941 "peer=%d does not offer the expected services "
4942 "(%08x offered, %08x expected); disconnecting\n",
4943 pfrom.GetId(), nServices,
4944 GetDesirableServiceFlags(nServices));
4945 pfrom.fDisconnect = true;
4946 return;
4947 }
4948
4949 if (pfrom.IsAvalancheOutboundConnection() &&
4950 !(nServices & NODE_AVALANCHE)) {
4951 LogPrint(
4953 "peer=%d does not offer the avalanche service; disconnecting\n",
4954 pfrom.GetId());
4955 pfrom.fDisconnect = true;
4956 return;
4957 }
4958
4959 if (nVersion < MIN_PEER_PROTO_VERSION) {
4960 // disconnect from peers older than this proto version
4962 "peer=%d using obsolete version %i; disconnecting\n",
4963 pfrom.GetId(), nVersion);
4964 pfrom.fDisconnect = true;
4965 return;
4966 }
4967
4968 if (!vRecv.empty()) {
4969 // The version message includes information about the sending node
4970 // which we don't use:
4971 // - 8 bytes (service bits)
4972 // - 16 bytes (ipv6 address)
4973 // - 2 bytes (port)
4974 vRecv.ignore(26);
4975 vRecv >> nNonce;
4976 }
4977 if (!vRecv.empty()) {
4978 std::string strSubVer;
4979 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
4980 cleanSubVer = SanitizeString(strSubVer);
4981 }
4982 if (!vRecv.empty()) {
4983 vRecv >> starting_height;
4984 }
4985 if (!vRecv.empty()) {
4986 vRecv >> fRelay;
4987 }
4988 if (!vRecv.empty()) {
4989 vRecv >> nExtraEntropy;
4990 }
4991 // Disconnect if we connected to ourself
4992 if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce)) {
4993 LogPrintf("connected to self at %s, disconnecting\n",
4994 pfrom.addr.ToStringAddrPort());
4995 pfrom.fDisconnect = true;
4996 return;
4997 }
4998
4999 if (pfrom.IsInboundConn() && addrMe.IsRoutable()) {
5000 SeenLocal(addrMe);
5001 }
5002
5003 // Inbound peers send us their version message when they connect.
5004 // We send our version message in response.
5005 if (pfrom.IsInboundConn()) {
5006 PushNodeVersion(config, pfrom, *peer);
5007 }
5008
5009 // Change version
5010 const int greatest_common_version =
5011 std::min(nVersion, PROTOCOL_VERSION);
5012 pfrom.SetCommonVersion(greatest_common_version);
5013 pfrom.nVersion = nVersion;
5014
5015 MakeAndPushMessage(pfrom, NetMsgType::VERACK);
5016
5017 // Signal ADDRv2 support (BIP155).
5018 MakeAndPushMessage(pfrom, NetMsgType::SENDADDRV2);
5019
5021 HasAllDesirableServiceFlags(nServices);
5022 peer->m_their_services = nServices;
5023 pfrom.SetAddrLocal(addrMe);
5024 {
5025 LOCK(pfrom.m_subver_mutex);
5026 pfrom.cleanSubVer = cleanSubVer;
5027 }
5028 peer->m_starting_height = starting_height;
5029
5030 // Only initialize the m_tx_relay data structure if:
5031 // - this isn't an outbound block-relay-only connection; and
5032 // - this isn't an outbound feeler connection, and
5033 // - fRelay=true or we're offering NODE_BLOOM to this peer
5034 // (NODE_BLOOM means that the peer may turn on tx relay later)
5035 if (!pfrom.IsBlockOnlyConn() && !pfrom.IsFeelerConn() &&
5036 (fRelay || (peer->m_our_services & NODE_BLOOM))) {
5037 auto *const tx_relay = peer->SetTxRelay();
5038 {
5039 LOCK(tx_relay->m_bloom_filter_mutex);
5040 // set to true after we get the first filter* message
5041 tx_relay->m_relay_txs = fRelay;
5042 }
5043 if (fRelay) {
5044 pfrom.m_relays_txs = true;
5045 }
5046 }
5047
5048 pfrom.nRemoteHostNonce = nNonce;
5049 pfrom.nRemoteExtraEntropy = nExtraEntropy;
5050
5051 // Potentially mark this peer as a preferred download peer.
5052 {
5053 LOCK(cs_main);
5054 CNodeState *state = State(pfrom.GetId());
5055 state->fPreferredDownload =
5056 (!pfrom.IsInboundConn() ||
5058 !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer);
5059 m_num_preferred_download_peers += state->fPreferredDownload;
5060 }
5061
5062 // Attempt to initialize address relay for outbound peers and use result
5063 // to decide whether to send GETADDR, so that we don't send it to
5064 // inbound or outbound block-relay-only peers.
5065 bool send_getaddr{false};
5066 if (!pfrom.IsInboundConn()) {
5067 send_getaddr = SetupAddressRelay(pfrom, *peer);
5068 }
5069 if (send_getaddr) {
5070 // Do a one-time address fetch to help populate/update our addrman.
5071 // If we're starting up for the first time, our addrman may be
5072 // pretty empty, so this mechanism is important to help us connect
5073 // to the network.
5074 // We skip this for block-relay-only peers. We want to avoid
5075 // potentially leaking addr information and we do not want to
5076 // indicate to the peer that we will participate in addr relay.
5077 MakeAndPushMessage(pfrom, NetMsgType::GETADDR);
5078 peer->m_getaddr_sent = true;
5079 // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND
5080 // addresses in response (bypassing the
5081 // MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
5082 WITH_LOCK(peer->m_addr_token_bucket_mutex,
5083 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
5084 }
5085
5086 if (!pfrom.IsInboundConn()) {
5087 // For non-inbound connections, we update the addrman to record
5088 // connection success so that addrman will have an up-to-date
5089 // notion of which peers are online and available.
5090 //
5091 // While we strive to not leak information about block-relay-only
5092 // connections via the addrman, not moving an address to the tried
5093 // table is also potentially detrimental because new-table entries
5094 // are subject to eviction in the event of addrman collisions. We
5095 // mitigate the information-leak by never calling
5096 // AddrMan::Connected() on block-relay-only peers; see
5097 // FinalizeNode().
5098 //
5099 // This moves an address from New to Tried table in Addrman,
5100 // resolves tried-table collisions, etc.
5101 m_addrman.Good(pfrom.addr);
5102 }
5103
5104 std::string remoteAddr;
5105 if (fLogIPs) {
5106 remoteAddr = ", peeraddr=" + pfrom.addr.ToStringAddrPort();
5107 }
5108
5110 "receive version message: [%s] %s: version %d, blocks=%d, "
5111 "us=%s, txrelay=%d, peer=%d%s\n",
5112 pfrom.addr.ToStringAddrPort(), cleanSubVer, pfrom.nVersion,
5113 peer->m_starting_height, addrMe.ToStringAddrPort(), fRelay,
5114 pfrom.GetId(), remoteAddr);
5115
5116 int64_t currentTime = GetTime();
5117 int64_t nTimeOffset = nTime - currentTime;
5118 pfrom.nTimeOffset = nTimeOffset;
5119 if (nTime < int64_t(m_chainparams.GenesisBlock().nTime)) {
5120 // Ignore time offsets that are improbable (before the Genesis
5121 // block) and may underflow our adjusted time.
5122 Misbehaving(*peer, "Ignoring invalid timestamp in version message");
5123 } else if (!pfrom.IsInboundConn()) {
5124 // Don't use timedata samples from inbound peers to make it
5125 // harder for others to tamper with our adjusted time.
5126 AddTimeData(pfrom.addr, nTimeOffset);
5127 }
5128
5129 // Feeler connections exist only to verify if address is online.
5130 if (pfrom.IsFeelerConn()) {
5132 "feeler connection completed peer=%d; disconnecting\n",
5133 pfrom.GetId());
5134 pfrom.fDisconnect = true;
5135 }
5136 return;
5137 }
5138
5139 if (pfrom.nVersion == 0) {
5140 // Must have a version message before anything else
5141 Misbehaving(*peer, "non-version message before version handshake");
5142 return;
5143 }
5144
5145 if (msg_type == NetMsgType::VERACK) {
5146 if (pfrom.fSuccessfullyConnected) {
5148 "ignoring redundant verack message from peer=%d\n",
5149 pfrom.GetId());
5150 return;
5151 }
5152
5153 if (!pfrom.IsInboundConn()) {
5154 LogPrintf("New outbound peer connected: version: %d, blocks=%d, "
5155 "peer=%d%s (%s)\n",
5156 pfrom.nVersion.load(), peer->m_starting_height,
5157 pfrom.GetId(),
5158 (fLogIPs ? strprintf(", peeraddr=%s",
5159 pfrom.addr.ToStringAddrPort())
5160 : ""),
5161 pfrom.ConnectionTypeAsString());
5162 }
5163
5165 // Tell our peer we are willing to provide version 1
5166 // cmpctblocks. However, we do not request new block announcements
5167 // using cmpctblock messages. We send this to non-NODE NETWORK peers
5168 // as well, because they may wish to request compact blocks from us.
5169 MakeAndPushMessage(pfrom, NetMsgType::SENDCMPCT,
5170 /*high_bandwidth=*/false,
5171 /*version=*/CMPCTBLOCKS_VERSION);
5172 }
5173
5174 if (m_avalanche) {
5175 if (m_avalanche->sendHello(&pfrom)) {
5176 auto localProof = m_avalanche->getLocalProof();
5177
5178 if (localProof) {
5179 AddKnownProof(*peer, localProof->getId());
5180 // Add our proof id to the list or the recently announced
5181 // proof INVs to this peer. This is used for filtering which
5182 // INV can be requested for download.
5183 peer->m_proof_relay->m_recently_announced_proofs.insert(
5184 localProof->getId());
5185 }
5186 }
5187 }
5188
5189 if (auto tx_relay = peer->GetTxRelay()) {
5190 // `TxRelay::m_tx_inventory_to_send` must be empty before the
5191 // version handshake is completed as
5192 // `TxRelay::m_next_inv_send_time` is first initialised in
5193 // `SendMessages` after the verack is received. Any transactions
5194 // received during the version handshake would otherwise
5195 // immediately be advertised without random delay, potentially
5196 // leaking the time of arrival to a spy.
5197 Assume(WITH_LOCK(tx_relay->m_tx_inventory_mutex,
5198 return tx_relay->m_tx_inventory_to_send.empty() &&
5199 tx_relay->m_next_inv_send_time == 0s));
5200 }
5201
5202 pfrom.fSuccessfullyConnected = true;
5203 return;
5204 }
5205
5206 if (!pfrom.fSuccessfullyConnected) {
5207 // Must have a verack message before anything else
5208 Misbehaving(*peer, "non-verack message before version handshake");
5209 return;
5210 }
5211
5212 if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
5213 const auto ser_params{
5214 msg_type == NetMsgType::ADDRV2
5215 ?
5216 // Set V2 param so that the CNetAddr and CAddress unserialize
5217 // methods know that an address in v2 format is coming.
5220 };
5221
5222 std::vector<CAddress> vAddr;
5223
5224 vRecv >> WithParams(ser_params, vAddr);
5225
5226 if (!SetupAddressRelay(pfrom, *peer)) {
5227 LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n",
5228 msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
5229 return;
5230 }
5231
5232 if (vAddr.size() > m_opts.max_addr_to_send) {
5233 Misbehaving(*peer, strprintf("%s message size = %u", msg_type,
5234 vAddr.size()));
5235 return;
5236 }
5237
5238 // Store the new addresses
5239 std::vector<CAddress> vAddrOk;
5240 const auto current_a_time{Now<NodeSeconds>()};
5241
5242 // Update/increment addr rate limiting bucket.
5243 const auto current_time = GetTime<std::chrono::microseconds>();
5244 {
5245 LOCK(peer->m_addr_token_bucket_mutex);
5246 if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
5247 // Don't increment bucket if it's already full
5248 const auto time_diff =
5249 std::max(current_time - peer->m_addr_token_timestamp, 0us);
5250 const double increment =
5252 peer->m_addr_token_bucket =
5253 std::min<double>(peer->m_addr_token_bucket + increment,
5255 }
5256 }
5257 peer->m_addr_token_timestamp = current_time;
5258
5259 const bool rate_limited =
5261 uint64_t num_proc = 0;
5262 uint64_t num_rate_limit = 0;
5263 Shuffle(vAddr.begin(), vAddr.end(), m_rng);
5264 for (CAddress &addr : vAddr) {
5265 if (interruptMsgProc) {
5266 return;
5267 }
5268
5269 {
5270 LOCK(peer->m_addr_token_bucket_mutex);
5271 // Apply rate limiting.
5272 if (peer->m_addr_token_bucket < 1.0) {
5273 if (rate_limited) {
5274 ++num_rate_limit;
5275 continue;
5276 }
5277 } else {
5278 peer->m_addr_token_bucket -= 1.0;
5279 }
5280 }
5281
5282 // We only bother storing full nodes, though this may include things
5283 // which we would not make an outbound connection to, in part
5284 // because we may make feeler connections to them.
5285 if (!MayHaveUsefulAddressDB(addr.nServices) &&
5287 continue;
5288 }
5289
5290 if (addr.nTime <= NodeSeconds{100000000s} ||
5291 addr.nTime > current_a_time + 10min) {
5292 addr.nTime = current_a_time - 5 * 24h;
5293 }
5294 AddAddressKnown(*peer, addr);
5295 if (m_banman &&
5296 (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
5297 // Do not process banned/discouraged addresses beyond
5298 // remembering we received them
5299 continue;
5300 }
5301 ++num_proc;
5302 bool fReachable = IsReachable(addr);
5303 if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent &&
5304 vAddr.size() <= 10 && addr.IsRoutable()) {
5305 // Relay to a limited number of other nodes
5306 RelayAddress(pfrom.GetId(), addr, fReachable);
5307 }
5308 // Do not store addresses outside our network
5309 if (fReachable) {
5310 vAddrOk.push_back(addr);
5311 }
5312 }
5313 peer->m_addr_processed += num_proc;
5314 peer->m_addr_rate_limited += num_rate_limit;
5316 "Received addr: %u addresses (%u processed, %u rate-limited) "
5317 "from peer=%d\n",
5318 vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
5319
5320 m_addrman.Add(vAddrOk, pfrom.addr, 2h);
5321 if (vAddr.size() < 1000) {
5322 peer->m_getaddr_sent = false;
5323 }
5324
5325 // AddrFetch: Require multiple addresses to avoid disconnecting on
5326 // self-announcements
5327 if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
5329 "addrfetch connection completed peer=%d; disconnecting\n",
5330 pfrom.GetId());
5331 pfrom.fDisconnect = true;
5332 }
5333 return;
5334 }
5335
5336 if (msg_type == NetMsgType::SENDADDRV2) {
5337 peer->m_wants_addrv2 = true;
5338 return;
5339 }
5340
5341 if (msg_type == NetMsgType::SENDHEADERS) {
5342 peer->m_prefers_headers = true;
5343 return;
5344 }
5345
5346 if (msg_type == NetMsgType::SENDCMPCT) {
5347 bool sendcmpct_hb{false};
5348 uint64_t sendcmpct_version{0};
5349 vRecv >> sendcmpct_hb >> sendcmpct_version;
5350
5351 if (sendcmpct_version != CMPCTBLOCKS_VERSION) {
5352 return;
5353 }
5354
5355 LOCK(cs_main);
5356 CNodeState *nodestate = State(pfrom.GetId());
5357 nodestate->m_provides_cmpctblocks = true;
5358 nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
5359 // save whether peer selects us as BIP152 high-bandwidth peer
5360 // (receiving sendcmpct(1) signals high-bandwidth,
5361 // sendcmpct(0) low-bandwidth)
5362 pfrom.m_bip152_highbandwidth_from = sendcmpct_hb;
5363 return;
5364 }
5365
5366 if (msg_type == NetMsgType::INV) {
5367 std::vector<CInv> vInv;
5368 vRecv >> vInv;
5369 if (vInv.size() > MAX_INV_SZ) {
5370 Misbehaving(*peer, strprintf("inv message size = %u", vInv.size()));
5371 return;
5372 }
5373
5374 const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
5375
5376 const auto current_time{GetTime<std::chrono::microseconds>()};
5377 std::optional<BlockHash> best_block;
5378
5379 auto logInv = [&](const CInv &inv, bool fAlreadyHave) {
5380 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(),
5381 fAlreadyHave ? "have" : "new", pfrom.GetId());
5382 };
5383
5384 for (CInv &inv : vInv) {
5385 if (interruptMsgProc) {
5386 return;
5387 }
5388
5389 if (inv.IsMsgStakeContender()) {
5390 // Ignore invs with stake contenders. This type is only used for
5391 // polling.
5392 continue;
5393 }
5394
5395 if (inv.IsMsgBlk()) {
5396 LOCK(cs_main);
5397 const bool fAlreadyHave = AlreadyHaveBlock(BlockHash(inv.hash));
5398 logInv(inv, fAlreadyHave);
5399
5400 BlockHash hash{inv.hash};
5401 UpdateBlockAvailability(pfrom.GetId(), hash);
5402 if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() &&
5403 !IsBlockRequested(hash)) {
5404 // Headers-first is the primary method of announcement on
5405 // the network. If a node fell back to sending blocks by
5406 // inv, it may be for a re-org, or because we haven't
5407 // completed initial headers sync. The final block hash
5408 // provided should be the highest, so send a getheaders and
5409 // then fetch the blocks we need to catch up.
5410 best_block = std::move(hash);
5411 }
5412
5413 continue;
5414 }
5415
5416 if (inv.IsMsgProof()) {
5417 if (!m_avalanche) {
5418 continue;
5419 }
5420 const avalanche::ProofId proofid(inv.hash);
5421 const bool fAlreadyHave = AlreadyHaveProof(proofid);
5422 logInv(inv, fAlreadyHave);
5423 AddKnownProof(*peer, proofid);
5424
5425 if (!fAlreadyHave && m_avalanche &&
5426 !m_chainman.IsInitialBlockDownload()) {
5427 const bool preferred = isPreferredDownloadPeer(pfrom);
5428
5429 LOCK(cs_proofrequest);
5430 AddProofAnnouncement(pfrom, proofid, current_time,
5431 preferred);
5432 }
5433 continue;
5434 }
5435
5436 if (inv.IsMsgTx()) {
5437 LOCK(cs_main);
5438 const TxId txid(inv.hash);
5439 const bool fAlreadyHave =
5440 AlreadyHaveTx(txid, /*include_reconsiderable=*/true);
5441 logInv(inv, fAlreadyHave);
5442
5443 AddKnownTx(*peer, txid);
5444 if (reject_tx_invs) {
5446 "transaction (%s) inv sent in violation of "
5447 "protocol, disconnecting peer=%d\n",
5448 txid.ToString(), pfrom.GetId());
5449 pfrom.fDisconnect = true;
5450 return;
5451 } else if (!fAlreadyHave &&
5452 !m_chainman.IsInitialBlockDownload()) {
5453 AddTxAnnouncement(pfrom, txid, current_time);
5454 }
5455
5456 continue;
5457 }
5458
5460 "Unknown inv type \"%s\" received from peer=%d\n",
5461 inv.ToString(), pfrom.GetId());
5462 }
5463
5464 if (best_block) {
5465 // If we haven't started initial headers-sync with this peer, then
5466 // consider sending a getheaders now. On initial startup, there's a
5467 // reliability vs bandwidth tradeoff, where we are only trying to do
5468 // initial headers sync with one peer at a time, with a long
5469 // timeout (at which point, if the sync hasn't completed, we will
5470 // disconnect the peer and then choose another). In the meantime,
5471 // as new blocks are found, we are willing to add one new peer per
5472 // block to sync with as well, to sync quicker in the case where
5473 // our initial peer is unresponsive (but less bandwidth than we'd
5474 // use if we turned on sync with all peers).
5475 LOCK(::cs_main);
5476 CNodeState &state{*Assert(State(pfrom.GetId()))};
5477 if (state.fSyncStarted ||
5478 (!peer->m_inv_triggered_getheaders_before_sync &&
5479 *best_block != m_last_block_inv_triggering_headers_sync)) {
5480 if (MaybeSendGetHeaders(
5481 pfrom, GetLocator(m_chainman.m_best_header), *peer)) {
5482 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n",
5483 m_chainman.m_best_header->nHeight,
5484 best_block->ToString(), pfrom.GetId());
5485 }
5486 if (!state.fSyncStarted) {
5487 peer->m_inv_triggered_getheaders_before_sync = true;
5488 // Update the last block hash that triggered a new headers
5489 // sync, so that we don't turn on headers sync with more
5490 // than 1 new peer every new block.
5491 m_last_block_inv_triggering_headers_sync = *best_block;
5492 }
5493 }
5494 }
5495
5496 return;
5497 }
5498
5499 if (msg_type == NetMsgType::GETDATA) {
5500 std::vector<CInv> vInv;
5501 vRecv >> vInv;
5502 if (vInv.size() > MAX_INV_SZ) {
5503 Misbehaving(*peer,
5504 strprintf("getdata message size = %u", vInv.size()));
5505 return;
5506 }
5507
5508 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n",
5509 vInv.size(), pfrom.GetId());
5510
5511 if (vInv.size() > 0) {
5512 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n",
5513 vInv[0].ToString(), pfrom.GetId());
5514 }
5515
5516 {
5517 LOCK(peer->m_getdata_requests_mutex);
5518 peer->m_getdata_requests.insert(peer->m_getdata_requests.end(),
5519 vInv.begin(), vInv.end());
5520 ProcessGetData(config, pfrom, *peer, interruptMsgProc);
5521 }
5522
5523 return;
5524 }
5525
5526 if (msg_type == NetMsgType::GETBLOCKS) {
5527 CBlockLocator locator;
5528 uint256 hashStop;
5529 vRecv >> locator >> hashStop;
5530
5531 if (locator.vHave.size() > MAX_LOCATOR_SZ) {
5533 "getblocks locator size %lld > %d, disconnect peer=%d\n",
5534 locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
5535 pfrom.fDisconnect = true;
5536 return;
5537 }
5538
5539 // We might have announced the currently-being-connected tip using a
5540 // compact block, which resulted in the peer sending a getblocks
5541 // request, which we would otherwise respond to without the new block.
5542 // To avoid this situation we simply verify that we are on our best
5543 // known chain now. This is super overkill, but we handle it better
5544 // for getheaders requests, and there are no known nodes which support
5545 // compact blocks but still use getblocks to request blocks.
5546 {
5547 std::shared_ptr<const CBlock> a_recent_block;
5548 {
5549 LOCK(m_most_recent_block_mutex);
5550 a_recent_block = m_most_recent_block;
5551 }
5553 if (!m_chainman.ActiveChainstate().ActivateBestChain(
5554 state, a_recent_block, m_avalanche)) {
5555 LogPrint(BCLog::NET, "failed to activate chain (%s)\n",
5556 state.ToString());
5557 }
5558 }
5559
5560 LOCK(cs_main);
5561
5562 // Find the last block the caller has in the main chain
5563 const CBlockIndex *pindex =
5564 m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
5565
5566 // Send the rest of the chain
5567 if (pindex) {
5568 pindex = m_chainman.ActiveChain().Next(pindex);
5569 }
5570 int nLimit = 500;
5571 LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n",
5572 (pindex ? pindex->nHeight : -1),
5573 hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit,
5574 pfrom.GetId());
5575 for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) {
5576 if (pindex->GetBlockHash() == hashStop) {
5577 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n",
5578 pindex->nHeight, pindex->GetBlockHash().ToString());
5579 break;
5580 }
5581 // If pruning, don't inv blocks unless we have on disk and are
5582 // likely to still have for some reasonable time window (1 hour)
5583 // that block relay might require.
5584 const int nPrunedBlocksLikelyToHave =
5586 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
5587 if (m_chainman.m_blockman.IsPruneMode() &&
5588 (!pindex->nStatus.hasData() ||
5589 pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight -
5590 nPrunedBlocksLikelyToHave)) {
5591 LogPrint(
5592 BCLog::NET,
5593 " getblocks stopping, pruned or too old block at %d %s\n",
5594 pindex->nHeight, pindex->GetBlockHash().ToString());
5595 break;
5596 }
5597 WITH_LOCK(
5598 peer->m_block_inv_mutex,
5599 peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
5600 if (--nLimit <= 0) {
5601 // When this block is requested, we'll send an inv that'll
5602 // trigger the peer to getblocks the next batch of inventory.
5603 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n",
5604 pindex->nHeight, pindex->GetBlockHash().ToString());
5605 WITH_LOCK(peer->m_block_inv_mutex, {
5606 peer->m_continuation_block = pindex->GetBlockHash();
5607 });
5608 break;
5609 }
5610 }
5611 return;
5612 }
5613
5614 if (msg_type == NetMsgType::GETBLOCKTXN) {
5616 vRecv >> req;
5617
5618 std::shared_ptr<const CBlock> recent_block;
5619 {
5620 LOCK(m_most_recent_block_mutex);
5621 if (m_most_recent_block_hash == req.blockhash) {
5622 recent_block = m_most_recent_block;
5623 }
5624 // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion
5625 }
5626 if (recent_block) {
5627 SendBlockTransactions(pfrom, *peer, *recent_block, req);
5628 return;
5629 }
5630
5631 FlatFilePos block_pos{};
5632 {
5633 LOCK(cs_main);
5634
5635 const CBlockIndex *pindex =
5636 m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
5637 if (!pindex || !pindex->nStatus.hasData()) {
5638 LogPrint(
5639 BCLog::NET,
5640 "Peer %d sent us a getblocktxn for a block we don't have\n",
5641 pfrom.GetId());
5642 return;
5643 }
5644
5645 if (pindex->nHeight >=
5646 m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
5647 block_pos = pindex->GetBlockPos();
5648 }
5649 }
5650
5651 if (!block_pos.IsNull()) {
5652 CBlock block;
5653 const bool ret{m_chainman.m_blockman.ReadBlock(block, block_pos)};
5654 // If height is above MAX_BLOCKTXN_DEPTH then this block cannot get
5655 // pruned after we release cs_main above, so this read should never
5656 // fail.
5657 if (!ret) {
5658 LogError("getblocktxn: block read failed for block %s\n",
5659 req.blockhash.ToString());
5660 // Nothing to do here
5661 return;
5662 }
5663
5664 SendBlockTransactions(pfrom, *peer, block, req);
5665 return;
5666 }
5667
5668 // If an older block is requested (should never happen in practice,
5669 // but can happen in tests) send a block response instead of a
5670 // blocktxn response. Sending a full block response instead of a
5671 // small blocktxn response is preferable in the case where a peer
5672 // might maliciously send lots of getblocktxn requests to trigger
5673 // expensive disk reads, because it will require the peer to
5674 // actually receive all the data read from disk over the network.
5676 "Peer %d sent us a getblocktxn for a block > %i deep\n",
5677 pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
5678 CInv inv;
5679 inv.type = MSG_BLOCK;
5680 inv.hash = req.blockhash;
5681 WITH_LOCK(peer->m_getdata_requests_mutex,
5682 peer->m_getdata_requests.push_back(inv));
5683 // The message processing loop will go around again (without pausing)
5684 // and we'll respond then (without cs_main)
5685 return;
5686 }
5687
5688 if (msg_type == NetMsgType::GETHEADERS) {
5689 CBlockLocator locator;
5690 BlockHash hashStop;
5691 vRecv >> locator >> hashStop;
5692
5693 if (locator.vHave.size() > MAX_LOCATOR_SZ) {
5695 "getheaders locator size %lld > %d, disconnect peer=%d\n",
5696 locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
5697 pfrom.fDisconnect = true;
5698 return;
5699 }
5700
5701 if (m_chainman.m_blockman.LoadingBlocks()) {
5702 LogPrint(
5703 BCLog::NET,
5704 "Ignoring getheaders from peer=%d while importing/reindexing\n",
5705 pfrom.GetId());
5706 return;
5707 }
5708
5709 LOCK(cs_main);
5710
5711 // Note that if we were to be on a chain that forks from the
5712 // checkpointed chain, then serving those headers to a peer that has
5713 // seen the checkpointed chain would cause that peer to disconnect us.
5714 // Requiring that our chainwork exceed the minimum chainwork is a
5715 // protection against being fed a bogus chain when we started up for
5716 // the first time and getting partitioned off the honest network for
5717 // serving that chain to others.
5718 if (m_chainman.ActiveTip() == nullptr ||
5719 (m_chainman.ActiveTip()->nChainWork <
5720 m_chainman.MinimumChainWork() &&
5723 "Ignoring getheaders from peer=%d because active chain "
5724 "has too little work; sending empty response\n",
5725 pfrom.GetId());
5726 // Just respond with an empty headers message, to tell the peer to
5727 // go away but not treat us as unresponsive.
5728 MakeAndPushMessage(pfrom, NetMsgType::HEADERS,
5729 std::vector<CBlock>());
5730 return;
5731 }
5732
5733 CNodeState *nodestate = State(pfrom.GetId());
5734 const CBlockIndex *pindex = nullptr;
5735 if (locator.IsNull()) {
5736 // If locator is null, return the hashStop block
5737 pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
5738 if (!pindex) {
5739 return;
5740 }
5741
5742 if (!BlockRequestAllowed(pindex)) {
5744 "%s: ignoring request from peer=%i for old block "
5745 "header that isn't in the main chain\n",
5746 __func__, pfrom.GetId());
5747 return;
5748 }
5749 } else {
5750 // Find the last block the caller has in the main chain
5751 pindex =
5752 m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
5753 if (pindex) {
5754 pindex = m_chainman.ActiveChain().Next(pindex);
5755 }
5756 }
5757
5758 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx
5759 // count at the end
5760 std::vector<CBlock> vHeaders;
5761 int nLimit = MAX_HEADERS_RESULTS;
5762 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n",
5763 (pindex ? pindex->nHeight : -1),
5764 hashStop.IsNull() ? "end" : hashStop.ToString(),
5765 pfrom.GetId());
5766 for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) {
5767 vHeaders.push_back(pindex->GetBlockHeader());
5768 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) {
5769 break;
5770 }
5771 }
5772 // pindex can be nullptr either if we sent
5773 // m_chainman.ActiveChain().Tip() OR if our peer has
5774 // m_chainman.ActiveChain().Tip() (and thus we are sending an empty
5775 // headers message). In both cases it's safe to update
5776 // pindexBestHeaderSent to be our tip.
5777 //
5778 // It is important that we simply reset the BestHeaderSent value here,
5779 // and not max(BestHeaderSent, newHeaderSent). We might have announced
5780 // the currently-being-connected tip using a compact block, which
5781 // resulted in the peer sending a headers request, which we respond to
5782 // without the new block. By resetting the BestHeaderSent, we ensure we
5783 // will re-announce the new block via headers (or compact blocks again)
5784 // in the SendMessages logic.
5785 nodestate->pindexBestHeaderSent =
5786 pindex ? pindex : m_chainman.ActiveChain().Tip();
5787 MakeAndPushMessage(pfrom, NetMsgType::HEADERS, vHeaders);
5788 return;
5789 }
5790
5791 if (msg_type == NetMsgType::TX) {
5792 if (RejectIncomingTxs(pfrom)) {
5794 "transaction sent in violation of protocol peer=%d\n",
5795 pfrom.GetId());
5796 pfrom.fDisconnect = true;
5797 return;
5798 }
5799
5800 // Stop processing the transaction early if we are still in IBD since we
5801 // don't have enough information to validate it yet. Sending unsolicited
5802 // transactions is not considered a protocol violation, so don't punish
5803 // the peer.
5804 if (m_chainman.IsInitialBlockDownload()) {
5805 return;
5806 }
5807
5808 CTransactionRef ptx;
5809 vRecv >> ptx;
5810 const CTransaction &tx = *ptx;
5811 const TxId &txid = tx.GetId();
5812 AddKnownTx(*peer, txid);
5813
5814 {
5815 LOCK(cs_main);
5816
5817 m_txrequest.ReceivedResponse(pfrom.GetId(), txid);
5818
5819 if (AlreadyHaveTx(txid, /*include_reconsiderable=*/true)) {
5821 // Always relay transactions received from peers with
5822 // forcerelay permission, even if they were already in the
5823 // mempool, allowing the node to function as a gateway for
5824 // nodes hidden behind it.
5825 if (!m_mempool.exists(tx.GetId())) {
5826 LogPrintf(
5827 "Not relaying non-mempool transaction %s from "
5828 "forcerelay peer=%d\n",
5829 tx.GetId().ToString(), pfrom.GetId());
5830 } else {
5831 LogPrintf("Force relaying tx %s from peer=%d\n",
5832 tx.GetId().ToString(), pfrom.GetId());
5833 RelayTransaction(tx.GetId());
5834 }
5835 }
5836
5837 if (m_recent_rejects_package_reconsiderable.contains(txid)) {
5838 // When a transaction is already in
5839 // m_recent_rejects_package_reconsiderable, we shouldn't
5840 // submit it by itself again. However, look for a matching
5841 // child in the orphanage, as it is possible that they
5842 // succeed as a package.
5843 LogPrint(
5845 "found tx %s in reconsiderable rejects, looking for "
5846 "child in orphanage\n",
5847 txid.ToString());
5848 if (auto package_to_validate{
5849 Find1P1CPackage(ptx, pfrom.GetId())}) {
5850 const auto package_result{ProcessNewPackage(
5851 m_chainman.ActiveChainstate(), m_mempool,
5852 package_to_validate->m_txns,
5853 /*test_accept=*/false)};
5855 "package evaluation for %s: %s (%s)\n",
5856 package_to_validate->ToString(),
5857 package_result.m_state.IsValid()
5858 ? "package accepted"
5859 : "package rejected",
5860 package_result.m_state.ToString());
5861 ProcessPackageResult(package_to_validate.value(),
5862 package_result);
5863 }
5864 }
5865 // If a tx is detected by m_recent_rejects it is ignored.
5866 // Because we haven't submitted the tx to our mempool, we won't
5867 // have computed a DoS score for it or determined exactly why we
5868 // consider it invalid.
5869 //
5870 // This means we won't penalize any peer subsequently relaying a
5871 // DoSy tx (even if we penalized the first peer who gave it to
5872 // us) because we have to account for m_recent_rejects showing
5873 // false positives. In other words, we shouldn't penalize a peer
5874 // if we aren't *sure* they submitted a DoSy tx.
5875 //
5876 // Note that m_recent_rejects doesn't just record DoSy or
5877 // invalid transactions, but any tx not accepted by the mempool,
5878 // which may be due to node policy (vs. consensus). So we can't
5879 // blanket penalize a peer simply for relaying a tx that our
5880 // m_recent_rejects has caught, regardless of false positives.
5881 return;
5882 }
5883
5884 const MempoolAcceptResult result =
5885 m_chainman.ProcessTransaction(ptx);
5886 const TxValidationState &state = result.m_state;
5887
5888 if (result.m_result_type ==
5890 ProcessValidTx(pfrom.GetId(), ptx);
5891 pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
5892 } else if (state.GetResult() ==
5894 // It may be the case that the orphans parents have all been
5895 // rejected.
5896 bool fRejectedParents = false;
5897
5898 // Deduplicate parent txids, so that we don't have to loop over
5899 // the same parent txid more than once down below.
5900 std::vector<TxId> unique_parents;
5901 unique_parents.reserve(tx.vin.size());
5902 for (const CTxIn &txin : tx.vin) {
5903 // We start with all parents, and then remove duplicates
5904 // below.
5905 unique_parents.push_back(txin.prevout.GetTxId());
5906 }
5907 std::sort(unique_parents.begin(), unique_parents.end());
5908 unique_parents.erase(
5909 std::unique(unique_parents.begin(), unique_parents.end()),
5910 unique_parents.end());
5911
5912 // Distinguish between parents in m_recent_rejects and
5913 // m_recent_rejects_package_reconsiderable. We can tolerate
5914 // having up to 1 parent in
5915 // m_recent_rejects_package_reconsiderable since we submit 1p1c
5916 // packages. However, fail immediately if any are in
5917 // m_recent_rejects.
5918 std::optional<TxId> rejected_parent_reconsiderable;
5919 for (const TxId &parent_txid : unique_parents) {
5920 if (m_recent_rejects.contains(parent_txid)) {
5921 fRejectedParents = true;
5922 break;
5923 }
5924
5925 if (m_recent_rejects_package_reconsiderable.contains(
5926 parent_txid) &&
5927 !m_mempool.exists(parent_txid)) {
5928 // More than 1 parent in
5929 // m_recent_rejects_package_reconsiderable:
5930 // 1p1c will not be sufficient to accept this package,
5931 // so just give up here.
5932 if (rejected_parent_reconsiderable.has_value()) {
5933 fRejectedParents = true;
5934 break;
5935 }
5936 rejected_parent_reconsiderable = parent_txid;
5937 }
5938 }
5939 if (!fRejectedParents) {
5940 const auto current_time{
5941 GetTime<std::chrono::microseconds>()};
5942
5943 for (const TxId &parent_txid : unique_parents) {
5944 // FIXME: MSG_TX should use a TxHash, not a TxId.
5945 AddKnownTx(*peer, parent_txid);
5946 // Exclude m_recent_rejects_package_reconsiderable: the
5947 // missing parent may have been previously rejected for
5948 // being too low feerate. This orphan might CPFP it.
5949 if (!AlreadyHaveTx(parent_txid,
5950 /*include_reconsiderable=*/false)) {
5951 AddTxAnnouncement(pfrom, parent_txid, current_time);
5952 }
5953 }
5954
5955 // NO_THREAD_SAFETY_ANALYSIS because we can't annotate for
5956 // g_msgproc_mutex
5957 if (unsigned int nEvicted =
5958 m_mempool.withOrphanage(
5959 [&](TxOrphanage &orphanage)
5961 if (orphanage.AddTx(ptx,
5962 pfrom.GetId())) {
5963 AddToCompactExtraTransactions(ptx);
5964 }
5965 return orphanage.LimitTxs(
5966 m_opts.max_orphan_txs, m_rng);
5967 }) > 0) {
5969 "orphanage overflow, removed %u tx\n",
5970 nEvicted);
5971 }
5972
5973 // Once added to the orphan pool, a tx is considered
5974 // AlreadyHave, and we shouldn't request it anymore.
5975 m_txrequest.ForgetInvId(tx.GetId());
5976
5977 } else {
5979 "not keeping orphan with rejected parents %s\n",
5980 tx.GetId().ToString());
5981 // We will continue to reject this tx since it has rejected
5982 // parents so avoid re-requesting it from other peers.
5983 m_recent_rejects.insert(tx.GetId());
5984 m_txrequest.ForgetInvId(tx.GetId());
5985 }
5986 }
5987 if (state.IsInvalid()) {
5988 ProcessInvalidTx(pfrom.GetId(), ptx, state,
5989 /*maybe_add_extra_compact_tx=*/true);
5990 }
5991 // When a transaction fails for TX_PACKAGE_RECONSIDERABLE, look for
5992 // a matching child in the orphanage, as it is possible that they
5993 // succeed as a package.
5994 if (state.GetResult() ==
5996 LogPrint(
5998 "tx %s failed but reconsiderable, looking for child in "
5999 "orphanage\n",
6000 txid.ToString());
6001 if (auto package_to_validate{
6002 Find1P1CPackage(ptx, pfrom.GetId())}) {
6003 const auto package_result{ProcessNewPackage(
6004 m_chainman.ActiveChainstate(), m_mempool,
6005 package_to_validate->m_txns, /*test_accept=*/false)};
6007 "package evaluation for %s: %s (%s)\n",
6008 package_to_validate->ToString(),
6009 package_result.m_state.IsValid()
6010 ? "package accepted"
6011 : "package rejected",
6012 package_result.m_state.ToString());
6013 ProcessPackageResult(package_to_validate.value(),
6014 package_result);
6015 }
6016 }
6017
6018 if (state.GetResult() ==
6020 // Once added to the conflicting pool, a tx is considered
6021 // AlreadyHave, and we shouldn't request it anymore.
6022 m_txrequest.ForgetInvId(tx.GetId());
6023
6024 unsigned int nEvicted{0};
6025 // NO_THREAD_SAFETY_ANALYSIS because of g_msgproc_mutex required
6026 // in the lambda for m_rng
6027 m_mempool.withConflicting(
6028 [&](TxConflicting &conflicting) NO_THREAD_SAFETY_ANALYSIS {
6029 conflicting.AddTx(ptx, pfrom.GetId());
6030 nEvicted = conflicting.LimitTxs(
6031 m_opts.max_conflicting_txs, m_rng);
6032 });
6033
6034 if (nEvicted > 0) {
6036 "conflicting pool overflow, removed %u tx\n",
6037 nEvicted);
6038 }
6039 }
6040 } // Release cs_main
6041
6042 return;
6043 }
6044
6045 if (msg_type == NetMsgType::CMPCTBLOCK) {
6046 // Ignore cmpctblock received while importing
6047 if (m_chainman.m_blockman.LoadingBlocks()) {
6049 "Unexpected cmpctblock message received from peer %d\n",
6050 pfrom.GetId());
6051 return;
6052 }
6053
6054 CBlockHeaderAndShortTxIDs cmpctblock;
6055 try {
6056 vRecv >> cmpctblock;
6057 } catch (std::ios_base::failure &e) {
6058 // This block has non contiguous or overflowing indexes
6059 Misbehaving(*peer, "cmpctblock-bad-indexes");
6060 return;
6061 }
6062
6063 bool received_new_header = false;
6064 const auto blockhash = cmpctblock.header.GetHash();
6065
6066 {
6067 LOCK(cs_main);
6068
6069 const CBlockIndex *prev_block =
6070 m_chainman.m_blockman.LookupBlockIndex(
6071 cmpctblock.header.hashPrevBlock);
6072 if (!prev_block) {
6073 // Doesn't connect (or is genesis), instead of DoSing in
6074 // AcceptBlockHeader, request deeper headers
6075 if (!m_chainman.IsInitialBlockDownload()) {
6076 MaybeSendGetHeaders(
6077 pfrom, GetLocator(m_chainman.m_best_header), *peer);
6078 }
6079 return;
6080 }
6081 if (prev_block->nChainWork +
6082 CalculateHeadersWork({cmpctblock.header}) <
6083 GetAntiDoSWorkThreshold()) {
6084 // If we get a low-work header in a compact block, we can ignore
6085 // it.
6087 "Ignoring low-work compact block from peer %d\n",
6088 pfrom.GetId());
6089 return;
6090 }
6091
6092 if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) {
6093 received_new_header = true;
6094 }
6095 }
6096
6097 const CBlockIndex *pindex = nullptr;
6099 if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header},
6100 /*min_pow_checked=*/true, state,
6101 &pindex)) {
6102 if (state.IsInvalid()) {
6103 MaybePunishNodeForBlock(pfrom.GetId(), state,
6104 /*via_compact_block*/ true,
6105 "invalid header via cmpctblock");
6106 return;
6107 }
6108 }
6109
6110 if (received_new_header) {
6111 LogInfo("Saw new cmpctblock header hash=%s peer=%d\n",
6112 blockhash.ToString(), pfrom.GetId());
6113 }
6114
6115 // When we succeed in decoding a block's txids from a cmpctblock
6116 // message we typically jump to the BLOCKTXN handling code, with a
6117 // dummy (empty) BLOCKTXN message, to re-use the logic there in
6118 // completing processing of the putative block (without cs_main).
6119 bool fProcessBLOCKTXN = false;
6120 DataStream blockTxnMsg{};
6121
6122 // If we end up treating this as a plain headers message, call that as
6123 // well
6124 // without cs_main.
6125 bool fRevertToHeaderProcessing = false;
6126
6127 // Keep a CBlock for "optimistic" compactblock reconstructions (see
6128 // below)
6129 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6130 bool fBlockReconstructed = false;
6131
6132 {
6133 LOCK(cs_main);
6134
6135 // If AcceptBlockHeader returned true, it set pindex
6136 if (!pindex) {
6137 LogError(
6138 "cmpctblock: header accepted but no pindex for block %s\n",
6139 blockhash.ToString());
6140 // Nothing to do here
6141 return;
6142 }
6143
6144 UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
6145
6146 CNodeState *nodestate = State(pfrom.GetId());
6147
6148 // If this was a new header with more work than our tip, update the
6149 // peer's last block announcement time
6150 if (received_new_header &&
6151 pindex->nChainWork >
6152 m_chainman.ActiveChain().Tip()->nChainWork) {
6153 nodestate->m_last_block_announcement = GetTime();
6154 }
6155
6156 if (pindex->nStatus.hasData()) {
6157 // Nothing to do here
6158 return;
6159 }
6160
6161 auto range_flight =
6162 mapBlocksInFlight.equal_range(pindex->GetBlockHash());
6163 size_t already_in_flight =
6164 std::distance(range_flight.first, range_flight.second);
6165 bool requested_block_from_this_peer{false};
6166
6167 // Multimap ensures ordering of outstanding requests. It's either
6168 // empty or first in line.
6169 bool first_in_flight =
6170 already_in_flight == 0 ||
6171 (range_flight.first->second.first == pfrom.GetId());
6172
6173 while (range_flight.first != range_flight.second) {
6174 if (range_flight.first->second.first == pfrom.GetId()) {
6175 requested_block_from_this_peer = true;
6176 break;
6177 }
6178 range_flight.first++;
6179 }
6180
6181 if (pindex->nChainWork <=
6182 m_chainman.ActiveChain()
6183 .Tip()
6184 ->nChainWork || // We know something better
6185 pindex->nTx != 0) {
6186 // We had this block at some point, but pruned it
6187 if (requested_block_from_this_peer) {
6188 // We requested this block for some reason, but our mempool
6189 // will probably be useless so we just grab the block via
6190 // normal getdata.
6191 std::vector<CInv> vInv(1);
6192 vInv[0] = CInv(MSG_BLOCK, blockhash);
6193 MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
6194 }
6195 return;
6196 }
6197
6198 // If we're not close to tip yet, give up and let parallel block
6199 // fetch work its magic.
6200 if (!already_in_flight && !CanDirectFetch()) {
6201 return;
6202 }
6203
6204 // We want to be a bit conservative just to be extra careful about
6205 // DoS possibilities in compact block processing...
6206 if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
6207 if ((already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK &&
6208 nodestate->vBlocksInFlight.size() <
6210 requested_block_from_this_peer) {
6211 std::list<QueuedBlock>::iterator *queuedBlockIt = nullptr;
6212 if (!BlockRequested(config, pfrom.GetId(), *pindex,
6213 &queuedBlockIt)) {
6214 if (!(*queuedBlockIt)->partialBlock) {
6215 (*queuedBlockIt)
6216 ->partialBlock.reset(
6217 new PartiallyDownloadedBlock(config,
6218 &m_mempool));
6219 } else {
6220 // The block was already in flight using compact
6221 // blocks from the same peer.
6222 LogPrint(BCLog::NET, "Peer sent us compact block "
6223 "we were already syncing!\n");
6224 return;
6225 }
6226 }
6227
6228 PartiallyDownloadedBlock &partialBlock =
6229 *(*queuedBlockIt)->partialBlock;
6230 ReadStatus status =
6231 partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
6232 if (status == READ_STATUS_INVALID) {
6233 // Reset in-flight state in case Misbehaving does not
6234 // result in a disconnect
6235 RemoveBlockRequest(pindex->GetBlockHash(),
6236 pfrom.GetId());
6237 Misbehaving(*peer, "invalid compact block");
6238 return;
6239 } else if (status == READ_STATUS_FAILED) {
6240 if (first_in_flight) {
6241 // Duplicate txindices, the block is now in-flight,
6242 // so just request it.
6243 std::vector<CInv> vInv(1);
6244 vInv[0] = CInv(MSG_BLOCK, blockhash);
6245 MakeAndPushMessage(pfrom, NetMsgType::GETDATA,
6246 vInv);
6247 } else {
6248 // Give up for this peer and wait for other peer(s)
6249 RemoveBlockRequest(pindex->GetBlockHash(),
6250 pfrom.GetId());
6251 }
6252 return;
6253 }
6254
6256 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
6257 if (!partialBlock.IsTxAvailable(i)) {
6258 req.indices.push_back(i);
6259 }
6260 }
6261 if (req.indices.empty()) {
6262 // Dirty hack to jump to BLOCKTXN code (TODO: move
6263 // message handling into their own functions)
6265 txn.blockhash = blockhash;
6266 blockTxnMsg << txn;
6267 fProcessBLOCKTXN = true;
6268 } else if (first_in_flight) {
6269 // We will try to round-trip any compact blocks we get
6270 // on failure, as long as it's first...
6271 req.blockhash = pindex->GetBlockHash();
6272 MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
6273 } else if (pfrom.m_bip152_highbandwidth_to &&
6274 (!pfrom.IsInboundConn() ||
6275 IsBlockRequestedFromOutbound(blockhash) ||
6276 already_in_flight <
6278 // ... or it's a hb relay peer and:
6279 // - peer is outbound, or
6280 // - we already have an outbound attempt in flight (so
6281 // we'll take what we can get), or
6282 // - it's not the final parallel download slot (which we
6283 // may reserve for first outbound)
6284 req.blockhash = pindex->GetBlockHash();
6285 MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req);
6286 } else {
6287 // Give up for this peer and wait for other peer(s)
6288 RemoveBlockRequest(pindex->GetBlockHash(),
6289 pfrom.GetId());
6290 }
6291 } else {
6292 // This block is either already in flight from a different
6293 // peer, or this peer has too many blocks outstanding to
6294 // download from. Optimistically try to reconstruct anyway
6295 // since we might be able to without any round trips.
6296 PartiallyDownloadedBlock tempBlock(config, &m_mempool);
6297 ReadStatus status =
6298 tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
6299 if (status != READ_STATUS_OK) {
6300 // TODO: don't ignore failures
6301 return;
6302 }
6303 std::vector<CTransactionRef> dummy;
6304 status = tempBlock.FillBlock(*pblock, dummy);
6305 if (status == READ_STATUS_OK) {
6306 fBlockReconstructed = true;
6307 }
6308 }
6309 } else {
6310 if (requested_block_from_this_peer) {
6311 // We requested this block, but its far into the future, so
6312 // our mempool will probably be useless - request the block
6313 // normally.
6314 std::vector<CInv> vInv(1);
6315 vInv[0] = CInv(MSG_BLOCK, blockhash);
6316 MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv);
6317 return;
6318 } else {
6319 // If this was an announce-cmpctblock, we want the same
6320 // treatment as a header message.
6321 fRevertToHeaderProcessing = true;
6322 }
6323 }
6324 } // cs_main
6325
6326 if (fProcessBLOCKTXN) {
6327 return ProcessMessage(config, pfrom, NetMsgType::BLOCKTXN,
6328 blockTxnMsg, time_received, interruptMsgProc);
6329 }
6330
6331 if (fRevertToHeaderProcessing) {
6332 // Headers received from HB compact block peers are permitted to be
6333 // relayed before full validation (see BIP 152), so we don't want to
6334 // disconnect the peer if the header turns out to be for an invalid
6335 // block. Note that if a peer tries to build on an invalid chain,
6336 // that will be detected and the peer will be banned.
6337 return ProcessHeadersMessage(config, pfrom, *peer,
6338 {cmpctblock.header},
6339 /*via_compact_block=*/true);
6340 }
6341
6342 if (fBlockReconstructed) {
6343 // If we got here, we were able to optimistically reconstruct a
6344 // block that is in flight from some other peer.
6345 {
6346 LOCK(cs_main);
6347 mapBlockSource.emplace(pblock->GetHash(),
6348 std::make_pair(pfrom.GetId(), false));
6349 }
6350 // Setting force_processing to true means that we bypass some of
6351 // our anti-DoS protections in AcceptBlock, which filters
6352 // unrequested blocks that might be trying to waste our resources
6353 // (eg disk space). Because we only try to reconstruct blocks when
6354 // we're close to caught up (via the CanDirectFetch() requirement
6355 // above, combined with the behavior of not requesting blocks until
6356 // we have a chain with at least the minimum chain work), and we
6357 // ignore compact blocks with less work than our tip, it is safe to
6358 // treat reconstructed compact blocks as having been requested.
6359 ProcessBlock(config, pfrom, pblock, /*force_processing=*/true,
6360 /*min_pow_checked=*/true);
6361 // hold cs_main for CBlockIndex::IsValid()
6362 LOCK(cs_main);
6363 if (pindex->IsValid(BlockValidity::TRANSACTIONS)) {
6364 // Clear download state for this block, which is in process from
6365 // some other peer. We do this after calling. ProcessNewBlock so
6366 // that a malleated cmpctblock announcement can't be used to
6367 // interfere with block relay.
6368 RemoveBlockRequest(pblock->GetHash(), std::nullopt);
6369 }
6370 }
6371 return;
6372 }
6373
6374 if (msg_type == NetMsgType::BLOCKTXN) {
6375 // Ignore blocktxn received while importing
6376 if (m_chainman.m_blockman.LoadingBlocks()) {
6378 "Unexpected blocktxn message received from peer %d\n",
6379 pfrom.GetId());
6380 return;
6381 }
6382
6383 BlockTransactions resp;
6384 vRecv >> resp;
6385
6386 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6387 bool fBlockRead = false;
6388 {
6389 LOCK(cs_main);
6390
6391 auto range_flight = mapBlocksInFlight.equal_range(resp.blockhash);
6392 size_t already_in_flight =
6393 std::distance(range_flight.first, range_flight.second);
6394 bool requested_block_from_this_peer{false};
6395
6396 // Multimap ensures ordering of outstanding requests. It's either
6397 // empty or first in line.
6398 bool first_in_flight =
6399 already_in_flight == 0 ||
6400 (range_flight.first->second.first == pfrom.GetId());
6401
6402 while (range_flight.first != range_flight.second) {
6403 auto [node_id, block_it] = range_flight.first->second;
6404 if (node_id == pfrom.GetId() && block_it->partialBlock) {
6405 requested_block_from_this_peer = true;
6406 break;
6407 }
6408 range_flight.first++;
6409 }
6410
6411 if (!requested_block_from_this_peer) {
6413 "Peer %d sent us block transactions for block "
6414 "we weren't expecting\n",
6415 pfrom.GetId());
6416 return;
6417 }
6418
6419 PartiallyDownloadedBlock &partialBlock =
6420 *range_flight.first->second.second->partialBlock;
6421 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
6422 if (status == READ_STATUS_INVALID) {
6423 // Reset in-flight state in case of Misbehaving does not
6424 // result in a disconnect.
6425 RemoveBlockRequest(resp.blockhash, pfrom.GetId());
6426 Misbehaving(
6427 *peer,
6428 "invalid compact block/non-matching block transactions");
6429 return;
6430 } else if (status == READ_STATUS_FAILED) {
6431 if (first_in_flight) {
6432 // Might have collided, fall back to getdata now :(
6433 std::vector<CInv> invs;
6434 invs.push_back(CInv(MSG_BLOCK, resp.blockhash));
6435 MakeAndPushMessage(pfrom, NetMsgType::GETDATA, invs);
6436 } else {
6437 RemoveBlockRequest(resp.blockhash, pfrom.GetId());
6438 LogPrint(
6439 BCLog::NET,
6440 "Peer %d sent us a compact block but it failed to "
6441 "reconstruct, waiting on first download to complete\n",
6442 pfrom.GetId());
6443 return;
6444 }
6445 } else {
6446 // Block is either okay, or possibly we received
6447 // READ_STATUS_CHECKBLOCK_FAILED.
6448 // Note that CheckBlock can only fail for one of a few reasons:
6449 // 1. bad-proof-of-work (impossible here, because we've already
6450 // accepted the header)
6451 // 2. merkleroot doesn't match the transactions given (already
6452 // caught in FillBlock with READ_STATUS_FAILED, so
6453 // impossible here)
6454 // 3. the block is otherwise invalid (eg invalid coinbase,
6455 // block is too big, too many sigChecks, etc).
6456 // So if CheckBlock failed, #3 is the only possibility.
6457 // Under BIP 152, we don't DoS-ban unless proof of work is
6458 // invalid (we don't require all the stateless checks to have
6459 // been run). This is handled below, so just treat this as
6460 // though the block was successfully read, and rely on the
6461 // handling in ProcessNewBlock to ensure the block index is
6462 // updated, etc.
6463
6464 // it is now an empty pointer
6465 RemoveBlockRequest(resp.blockhash, pfrom.GetId());
6466 fBlockRead = true;
6467 // mapBlockSource is used for potentially punishing peers and
6468 // updating which peers send us compact blocks, so the race
6469 // between here and cs_main in ProcessNewBlock is fine.
6470 // BIP 152 permits peers to relay compact blocks after
6471 // validating the header only; we should not punish peers
6472 // if the block turns out to be invalid.
6473 mapBlockSource.emplace(resp.blockhash,
6474 std::make_pair(pfrom.GetId(), false));
6475 }
6476 } // Don't hold cs_main when we call into ProcessNewBlock
6477 if (fBlockRead) {
6478 // Since we requested this block (it was in mapBlocksInFlight),
6479 // force it to be processed, even if it would not be a candidate for
6480 // new tip (missing previous block, chain not long enough, etc)
6481 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
6482 // disk-space attacks), but this should be safe due to the
6483 // protections in the compact block handler -- see related comment
6484 // in compact block optimistic reconstruction handling.
6485 ProcessBlock(config, pfrom, pblock, /*force_processing=*/true,
6486 /*min_pow_checked=*/true);
6487 }
6488 return;
6489 }
6490
6491 if (msg_type == NetMsgType::HEADERS) {
6492 // Ignore headers received while importing
6493 if (m_chainman.m_blockman.LoadingBlocks()) {
6495 "Unexpected headers message received from peer %d\n",
6496 pfrom.GetId());
6497 return;
6498 }
6499
6500 std::vector<CBlockHeader> headers;
6501
6502 // Bypass the normal CBlock deserialization, as we don't want to risk
6503 // deserializing 2000 full blocks.
6504 unsigned int nCount = ReadCompactSize(vRecv);
6505 if (nCount > MAX_HEADERS_RESULTS) {
6506 Misbehaving(*peer,
6507 strprintf("too-many-headers: headers message size = %u",
6508 nCount));
6509 return;
6510 }
6511 headers.resize(nCount);
6512 for (unsigned int n = 0; n < nCount; n++) {
6513 vRecv >> headers[n];
6514 // Ignore tx count; assume it is 0.
6515 ReadCompactSize(vRecv);
6516 }
6517
6518 ProcessHeadersMessage(config, pfrom, *peer, std::move(headers),
6519 /*via_compact_block=*/false);
6520
6521 // Check if the headers presync progress needs to be reported to
6522 // validation. This needs to be done without holding the
6523 // m_headers_presync_mutex lock.
6524 if (m_headers_presync_should_signal.exchange(false)) {
6525 HeadersPresyncStats stats;
6526 {
6527 LOCK(m_headers_presync_mutex);
6528 auto it =
6529 m_headers_presync_stats.find(m_headers_presync_bestpeer);
6530 if (it != m_headers_presync_stats.end()) {
6531 stats = it->second;
6532 }
6533 }
6534 if (stats.second) {
6535 m_chainman.ReportHeadersPresync(
6536 stats.first, stats.second->first, stats.second->second);
6537 }
6538 }
6539
6540 return;
6541 }
6542
6543 if (msg_type == NetMsgType::BLOCK) {
6544 // Ignore block received while importing
6545 if (m_chainman.m_blockman.LoadingBlocks()) {
6547 "Unexpected block message received from peer %d\n",
6548 pfrom.GetId());
6549 return;
6550 }
6551
6552 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6553 vRecv >> *pblock;
6554
6555 LogPrint(BCLog::NET, "received block %s peer=%d\n",
6556 pblock->GetHash().ToString(), pfrom.GetId());
6557
6558 const CBlockIndex *prev_block{
6559 WITH_LOCK(m_chainman.GetMutex(),
6560 return m_chainman.m_blockman.LookupBlockIndex(
6561 pblock->hashPrevBlock))};
6562
6563 if (IsBlockMutated(/*block=*/*pblock)) {
6565 "Received mutated block from peer=%d\n", peer->m_id);
6566 Misbehaving(*peer, "mutated block");
6568 RemoveBlockRequest(pblock->GetHash(), peer->m_id));
6569 return;
6570 }
6571
6572 // Process all blocks from whitelisted peers, even if not requested,
6573 // unless we're still syncing with the network. Such an unrequested
6574 // block may still be processed, subject to the conditions in
6575 // AcceptBlock().
6576 bool forceProcessing = pfrom.HasPermission(NetPermissionFlags::NoBan) &&
6577 !m_chainman.IsInitialBlockDownload();
6578 const BlockHash hash = pblock->GetHash();
6579 bool min_pow_checked = false;
6580 {
6581 LOCK(cs_main);
6582 // Always process the block if we requested it, since we may
6583 // need it even when it's not a candidate for a new best tip.
6584 forceProcessing = IsBlockRequested(hash);
6585 RemoveBlockRequest(hash, pfrom.GetId());
6586 // mapBlockSource is only used for punishing peers and setting
6587 // which peers send us compact blocks, so the race between here and
6588 // cs_main in ProcessNewBlock is fine.
6589 mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
6590
6591 // Check work on this block against our anti-dos thresholds.
6592 if (prev_block &&
6593 prev_block->nChainWork +
6594 CalculateHeadersWork({pblock->GetBlockHeader()}) >=
6595 GetAntiDoSWorkThreshold()) {
6596 min_pow_checked = true;
6597 }
6598 }
6599 ProcessBlock(config, pfrom, pblock, forceProcessing, min_pow_checked);
6600 return;
6601 }
6602
6603 if (msg_type == NetMsgType::AVAHELLO) {
6604 if (!m_avalanche) {
6605 return;
6606 }
6607 {
6609 if (pfrom.m_avalanche_pubkey.has_value()) {
6610 LogPrint(
6612 "Ignoring avahello from peer %d: already in our node set\n",
6613 pfrom.GetId());
6614 return;
6615 }
6616
6617 avalanche::Delegation delegation;
6618 vRecv >> delegation;
6619
6620 // A delegation with an all zero limited id indicates that the peer
6621 // has no proof, so we're done.
6622 if (delegation.getLimitedProofId() != uint256::ZERO) {
6624 CPubKey pubkey;
6625 if (!delegation.verify(state, pubkey)) {
6626 Misbehaving(*peer, "invalid-delegation");
6627 return;
6628 }
6629 pfrom.m_avalanche_pubkey = std::move(pubkey);
6630
6631 HashWriter sighasher{};
6632 sighasher << delegation.getId();
6633 sighasher << pfrom.nRemoteHostNonce;
6634 sighasher << pfrom.GetLocalNonce();
6635 sighasher << pfrom.nRemoteExtraEntropy;
6636 sighasher << pfrom.GetLocalExtraEntropy();
6637
6639 vRecv >> sig;
6640 if (!(*pfrom.m_avalanche_pubkey)
6641 .VerifySchnorr(sighasher.GetHash(), sig)) {
6642 Misbehaving(*peer, "invalid-avahello-signature");
6643 return;
6644 }
6645
6646 // If we don't know this proof already, add it to the tracker so
6647 // it can be requested.
6648 const avalanche::ProofId proofid(delegation.getProofId());
6649 if (!AlreadyHaveProof(proofid)) {
6650 const bool preferred = isPreferredDownloadPeer(pfrom);
6651 LOCK(cs_proofrequest);
6652 AddProofAnnouncement(pfrom, proofid,
6653 GetTime<std::chrono::microseconds>(),
6654 preferred);
6655 }
6656
6657 uint32_t max_elements{AVALANCHE_MAX_ELEMENT_POLL_LEGACY};
6658 if (pfrom.GetCommonVersion() >=
6660 !vRecv.empty()) {
6661 vRecv >> max_elements;
6662 // max_elements below AVALANCHE_MAX_ELEMENT_POLL_LEGACY is
6663 // invalid
6664 if (max_elements < AVALANCHE_MAX_ELEMENT_POLL_LEGACY) {
6665 Misbehaving(*peer, "avahello-max-elements-too-low");
6666 return;
6667 }
6668 }
6669
6670 // Don't check the return value. If it fails we probably don't
6671 // know about the proof yet.
6672 m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
6673 return pm.addNode(pfrom.GetId(), proofid, max_elements);
6674 });
6675 }
6676
6677 pfrom.m_avalanche_enabled = true;
6678 }
6679
6680 // Send getavaaddr and getavaproofs to our avalanche outbound or
6681 // manual connections
6682 if (!pfrom.IsInboundConn()) {
6683 MakeAndPushMessage(pfrom, NetMsgType::GETAVAADDR);
6684 WITH_LOCK(peer->m_addr_token_bucket_mutex,
6685 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
6686
6687 if (peer->m_proof_relay && !m_chainman.IsInitialBlockDownload()) {
6688 MakeAndPushMessage(pfrom, NetMsgType::GETAVAPROOFS);
6689 peer->m_proof_relay->compactproofs_requested = true;
6690 }
6691 }
6692
6693 return;
6694 }
6695
6696 if (msg_type == NetMsgType::AVAPOLL) {
6697 if (!m_avalanche) {
6698 return;
6699 }
6700 const auto now = Now<SteadyMilliseconds>();
6701
6702 const auto last_poll = pfrom.m_last_poll;
6703 pfrom.m_last_poll = now;
6704
6705 if (now <
6706 last_poll + std::chrono::milliseconds(m_opts.avalanche_cooldown)) {
6708 "Ignoring repeated avapoll from peer %d: cooldown not "
6709 "elapsed\n",
6710 pfrom.GetId());
6711 return;
6712 }
6713
6714 const bool quorum_established = m_avalanche->isQuorumEstablished();
6715
6716 uint64_t round;
6717 Unserialize(vRecv, round);
6718
6719 unsigned int nCount = ReadCompactSize(vRecv);
6720 if (nCount > m_avalanche->getMaxElementPoll()) {
6721 Misbehaving(
6722 *peer,
6723 strprintf("too-many-ava-poll: poll message size = %u", nCount));
6724 return;
6725 }
6726
6727 std::vector<avalanche::Vote> votes;
6728 votes.reserve(nCount);
6729
6730 bool fPreconsensus{false};
6731 bool fStakingPreconsensus{false};
6732 {
6733 LOCK(::cs_main);
6734 const CBlockIndex *tip = m_chainman.ActiveTip();
6735 fPreconsensus = m_avalanche->isPreconsensusActivated(tip);
6736 fStakingPreconsensus =
6737 m_avalanche->isStakingPreconsensusActivated(tip);
6738 }
6739
6740 for (unsigned int n = 0; n < nCount; n++) {
6741 CInv inv;
6742 vRecv >> inv;
6743
6744 // Default vote for unknown inv type
6745 uint32_t vote = -1;
6746
6747 // We don't vote definitively until we have an established quorum
6748 if (!quorum_established) {
6749 votes.emplace_back(vote, inv.hash);
6750 continue;
6751 }
6752
6753 // If inv's type is known, get a vote for its hash
6754 switch (inv.type) {
6755 case MSG_TX: {
6756 if (fPreconsensus) {
6757 vote =
6758 GetAvalancheVoteForTx(*m_avalanche, TxId(inv.hash));
6759 }
6760 } break;
6761 case MSG_BLOCK: {
6762 vote = WITH_LOCK(cs_main, return GetAvalancheVoteForBlock(
6763 BlockHash(inv.hash)));
6764 } break;
6765 case MSG_AVA_PROOF: {
6767 *m_avalanche, avalanche::ProofId(inv.hash));
6768 } break;
6770 if (fStakingPreconsensus) {
6771 vote = m_avalanche->getStakeContenderStatus(
6773 }
6774 } break;
6775 default: {
6777 "poll inv type %d unknown from peer=%d\n",
6778 inv.type, pfrom.GetId());
6779 }
6780 }
6781
6782 votes.emplace_back(vote, inv.hash);
6783 }
6784
6785 // Send the query to the node.
6786 m_avalanche->sendResponse(
6787 &pfrom, avalanche::Response(round, m_opts.avalanche_cooldown,
6788 std::move(votes)));
6789 return;
6790 }
6791
6792 if (msg_type == NetMsgType::AVARESPONSE) {
6793 if (!m_avalanche) {
6794 return;
6795 }
6796 // As long as QUIC is not implemented, we need to sign response and
6797 // verify response's signatures in order to avoid any manipulation of
6798 // messages at the transport level.
6799 HashVerifier verifier(vRecv);
6801 verifier >> response;
6802
6804 vRecv >> sig;
6805
6806 {
6808 if (!pfrom.m_avalanche_pubkey.has_value() ||
6809 !(*pfrom.m_avalanche_pubkey)
6810 .VerifySchnorr(verifier.GetHash(), sig)) {
6811 Misbehaving(*peer, "invalid-ava-response-signature");
6812 return;
6813 }
6814 }
6815
6816 auto now = GetTime<std::chrono::seconds>();
6817
6818 std::vector<avalanche::VoteItemUpdate> updates;
6819 bool disconnect{false};
6820 std::string error;
6821 if (!m_avalanche->registerVotes(pfrom.GetId(), response, updates,
6822 disconnect, error)) {
6823 if (disconnect) {
6824 Misbehaving(*peer, error);
6825 return;
6826 }
6827
6828 // Otherwise the node may have got a network issue. Increase the
6829 // fault counter instead and only ban if we reached a threshold.
6830 // This allows for fault tolerance should there be a temporary
6831 // outage while still preventing DoS'ing behaviors, as the counter
6832 // is reset if no fault occured over some time period.
6835
6836 // Allow up to 12 messages before increasing the ban score. Since
6837 // the queries are cleared after 10s, this is at least 2 minutes
6838 // of network outage tolerance over the 1h window.
6839 if (pfrom.m_avalanche_message_fault_counter > 12) {
6840 LogPrint(
6842 "Repeated failure to register votes from peer %d: %s\n",
6843 pfrom.GetId(), error);
6845 if (pfrom.m_avalanche_message_fault_score > 100) {
6846 Misbehaving(*peer, error);
6847 }
6848 return;
6849 }
6850 }
6851
6852 // If no fault occurred within the last hour, reset the fault counter
6853 if (now > (pfrom.m_avalanche_last_message_fault.load() + 1h)) {
6855 }
6856
6857 pfrom.invsVoted(response.GetVotes().size());
6858
6859 auto logVoteUpdate = [](const auto &voteUpdate,
6860 const std::string &voteItemTypeStr,
6861 const auto &voteItemId) {
6862 std::string voteOutcome;
6863 bool alwaysPrint = false;
6864 switch (voteUpdate.getStatus()) {
6866 voteOutcome = "invalidated";
6867 alwaysPrint = true;
6868 break;
6870 voteOutcome = "rejected";
6871 break;
6873 voteOutcome = "accepted";
6874 break;
6876 voteOutcome = "finalized";
6877 // Don't log tx finalization unconditionally as it can be
6878 // quite spammy.
6879 alwaysPrint = voteItemTypeStr != "tx";
6880 break;
6882 voteOutcome = "stalled";
6883 alwaysPrint = true;
6884 break;
6885
6886 // No default case, so the compiler can warn about missing
6887 // cases
6888 }
6889
6890 // Always log the stake contenders to the avalanche category
6891 alwaysPrint &= (voteItemTypeStr != "contender");
6892
6893 if (alwaysPrint) {
6894 LogPrintf("Avalanche %s %s %s\n", voteOutcome, voteItemTypeStr,
6895 voteItemId.ToString());
6896 } else {
6897 // Only print these messages if -debug=avalanche is set
6898 LogPrint(BCLog::AVALANCHE, "Avalanche %s %s %s\n", voteOutcome,
6899 voteItemTypeStr, voteItemId.ToString());
6900 }
6901 };
6902
6903 bool shouldActivateBestChain = false;
6904
6905 bool fPreconsensus{false};
6906 bool fStakingPreconsensus{false};
6907 {
6908 LOCK(::cs_main);
6909 const CBlockIndex *tip = m_chainman.ActiveTip();
6910 fPreconsensus = m_avalanche->isPreconsensusActivated(tip);
6911 fStakingPreconsensus =
6912 m_avalanche->isStakingPreconsensusActivated(tip);
6913 }
6914
6915 for (const auto &u : updates) {
6916 const avalanche::AnyVoteItem &item = u.getVoteItem();
6917
6918 // Don't use a visitor here as we want to ignore unsupported item
6919 // types. This comes in handy when adding new types.
6920 if (auto pitem = std::get_if<const avalanche::ProofRef>(&item)) {
6921 avalanche::ProofRef proof = *pitem;
6922 const avalanche::ProofId &proofid = proof->getId();
6923
6924 logVoteUpdate(u, "proof", proofid);
6925
6926 auto rejectionMode =
6928 auto nextCooldownTimePoint = GetTime<std::chrono::seconds>();
6929 switch (u.getStatus()) {
6931 m_avalanche->withPeerManager(
6932 [&](avalanche::PeerManager &pm) {
6933 pm.setInvalid(proofid);
6934 });
6935 // Fallthrough
6937 // Invalidate mode removes the proof from all proof
6938 // pools
6939 rejectionMode =
6941 // Fallthrough
6943 if (!m_avalanche->withPeerManager(
6944 [&](avalanche::PeerManager &pm) {
6945 return pm.rejectProof(proofid,
6946 rejectionMode);
6947 })) {
6949 "ERROR: Failed to reject proof: %s\n",
6950 proofid.GetHex());
6951 }
6952 break;
6954 m_avalanche->setRecentlyFinalized(proofid);
6955 nextCooldownTimePoint += std::chrono::seconds(
6956 m_opts.avalanche_peer_replacement_cooldown);
6958 if (!m_avalanche->withPeerManager(
6959 [&](avalanche::PeerManager &pm) {
6960 pm.registerProof(
6961 proof,
6962 avalanche::PeerManager::
6963 RegistrationMode::FORCE_ACCEPT);
6964 return pm.forPeer(
6965 proofid,
6966 [&](const avalanche::Peer &peer) {
6967 pm.updateNextPossibleConflictTime(
6968 peer.peerid,
6969 nextCooldownTimePoint);
6970 if (u.getStatus() ==
6971 avalanche::VoteStatus::
6972 Finalized) {
6973 pm.setFinalized(peer.peerid);
6974 }
6975 // Only fail if the peer was not
6976 // created
6977 return true;
6978 });
6979 })) {
6981 "ERROR: Failed to accept proof: %s\n",
6982 proofid.GetHex());
6983 }
6984 break;
6985 }
6986 }
6987
6988 auto getBlockFromIndex = [this](const CBlockIndex *pindex)
6989 -> std::shared_ptr<const CBlock> {
6990 // First check if the block is cached before reading
6991 // from disk.
6992 std::shared_ptr<const CBlock> pblock = WITH_LOCK(
6993 m_most_recent_block_mutex, return m_most_recent_block);
6994
6995 if (!pblock || pblock->GetHash() != pindex->GetBlockHash()) {
6996 std::shared_ptr<CBlock> pblockRead =
6997 std::make_shared<CBlock>();
6998 if (!m_chainman.m_blockman.ReadBlock(*pblockRead,
6999 *pindex)) {
7000 LogError("getBlockFromIndex: cannot load block from "
7001 "disk %s\n",
7002 pindex->GetBlockHash().ToString());
7003 return nullptr;
7004 }
7005 pblock = pblockRead;
7006 }
7007 return pblock;
7008 };
7009
7010 if (auto pitem = std::get_if<const CBlockIndex *>(&item)) {
7011 CBlockIndex *pindex = const_cast<CBlockIndex *>(*pitem);
7012
7013 shouldActivateBestChain = true;
7014
7015 logVoteUpdate(u, "block", pindex->GetBlockHash());
7016
7017 switch (u.getStatus()) {
7020 m_chainman.ActiveChainstate().ParkBlock(state, pindex);
7021 if (!state.IsValid()) {
7022 LogPrintf("ERROR: Database error: %s\n",
7023 state.GetRejectReason());
7024 return;
7025 }
7026 } break;
7029 m_chainman.ActiveChainstate().ParkBlock(state, pindex);
7030 if (!state.IsValid()) {
7031 LogPrintf("ERROR: Database error: %s\n",
7032 state.GetRejectReason());
7033 return;
7034 }
7035
7036 auto pblock = getBlockFromIndex(pindex);
7037 if (!pblock) {
7038 LogError("avaresponse: failed to get invalidated "
7039 "block from index\n");
7040 break;
7041 }
7042
7043 WITH_LOCK(cs_main, GetMainSignals().BlockInvalidated(
7044 pindex, pblock));
7045 } break;
7047 LOCK(cs_main);
7048 m_chainman.ActiveChainstate().UnparkBlock(pindex);
7049 } break;
7051 m_avalanche->setRecentlyFinalized(
7052 pindex->GetBlockHash());
7053
7054 m_avalanche->cleanupStakingRewards(pindex->nHeight);
7055
7056 std::unique_ptr<node::CBlockTemplate> blockTemplate;
7057 {
7058 LOCK(cs_main);
7059 auto &chainstate = m_chainman.ActiveChainstate();
7060 chainstate.UnparkBlock(pindex);
7061
7062 const bool newlyFinalized =
7063 !chainstate.IsBlockAvalancheFinalized(pindex) &&
7064 chainstate.AvalancheFinalizeBlock(pindex,
7065 *m_avalanche);
7066
7067 // Skip if the block is already finalized, aka an
7068 // ancestor of the finalized tip.
7069 if (fPreconsensus && newlyFinalized) {
7070 // If the finalized block is not the tip, we
7071 // need to keep track of the transactions from
7072 // the non final blocks, so that we can check if
7073 // they were finalized by pre-consensus.
7074 // If these transactions were pruned from the
7075 // radix tree, their finalization status could
7076 // be lost in the case the non final blocks are
7077 // later rejected.
7078 CBlockIndex *tip = m_chainman.ActiveTip();
7079 std::unordered_set<TxId, SaltedTxIdHasher>
7080 confirmedTxIdsInNonFinalizedBlocks;
7081 bool missing_block = false;
7082 for (const CBlockIndex *block = tip;
7083 block != nullptr && block != pindex;
7084 block = block->pprev) {
7085 auto currentBlock =
7086 getBlockFromIndex(block);
7087 if (!currentBlock) {
7088 LogError(
7089 "avaresponse: failed to get "
7090 "finalized block descendant from "
7091 "index %s\n",
7092 block->GetBlockHash().ToString());
7093 missing_block = true;
7094 break;
7095 }
7096 for (const auto &tx : currentBlock->vtx) {
7097 confirmedTxIdsInNonFinalizedBlocks
7098 .insert(tx->GetId());
7099 }
7100 }
7101
7102 if (missing_block) {
7103 // If any block data is missing, the cleanup
7104 // procedure will leave us in an
7105 // inconsistent state. Better skip the
7106 // procedure entirely.
7107 break;
7108 }
7109
7110 // Remove the transactions that are not
7111 // confirmed
7112 LOCK(m_mempool.cs);
7113 m_mempool.removeForFinalizedBlock(
7114 confirmedTxIdsInNonFinalizedBlocks);
7115
7116 // Now add mempool transactions to the poll.
7117 // To determine which transaction to add, we
7118 // leverage the legacy block template
7119 // construction method and build a template with
7120 // the most valuable txs in it. These
7121 // transactions are sorted topologically;
7122 // parents come before children, so we can poll
7123 // for children first and optimize the number of
7124 // polls.
7125 node::BlockAssembler blockAssembler(
7126 config, chainstate, &m_mempool,
7127 m_avalanche);
7128 blockAssembler.pblocktemplate.reset(
7129 new node::CBlockTemplate());
7130
7131 if (blockAssembler.pblocktemplate) {
7132 blockAssembler.addTxs(m_mempool);
7133 blockTemplate = std::move(
7134 blockAssembler.pblocktemplate);
7135 }
7136 }
7137 } // release cs_main
7138
7139 if (blockTemplate) {
7140 // We could check if the tx is final already but
7141 // addToReconcile will skip the recently finalized
7142 // txs, so let's abuse this feature and avoid a tree
7143 // lookup for each tx as an optimization.
7144 for (const auto &templateEntry :
7145 reverse_iterate(blockTemplate->entries)) {
7146 m_avalanche->addToReconcile(templateEntry.tx);
7147 }
7148 }
7149 } break;
7151 // Fall back on Nakamoto consensus in the absence of
7152 // Avalanche votes for other competing or descendant
7153 // blocks.
7154 break;
7155 }
7156 }
7157
7158 if (fStakingPreconsensus) {
7159 if (auto pitem =
7160 std::get_if<const avalanche::StakeContenderId>(&item)) {
7161 const avalanche::StakeContenderId contenderId = *pitem;
7162 logVoteUpdate(u, "contender", contenderId);
7163
7164 switch (u.getStatus()) {
7167 m_avalanche->rejectStakeContender(contenderId);
7168 break;
7169 }
7171 m_avalanche->setRecentlyFinalized(contenderId);
7172 m_avalanche->finalizeStakeContender(contenderId);
7173 break;
7174 }
7176 m_avalanche->acceptStakeContender(contenderId);
7177 break;
7178 }
7180 break;
7181 }
7182 }
7183 }
7184
7185 if (!fPreconsensus) {
7186 continue;
7187 }
7188
7189 if (auto pitem = std::get_if<const CTransactionRef>(&item)) {
7190 const CTransactionRef tx = *pitem;
7191 assert(tx != nullptr);
7192
7193 const TxId &txid = tx->GetId();
7194 const auto status{u.getStatus()};
7195
7196 if (status != avalanche::VoteStatus::Finalized) {
7197 // Because we also want to log the parents txs of this
7198 // finalized tx, we log the finalization later.
7199 logVoteUpdate(u, "tx", txid);
7200 }
7201
7202 switch (status) {
7203 case avalanche::VoteStatus::Invalid: // Fallthrough
7205 // Remove from the mempool and the finalized tree, as
7206 // well as all the children txs. Note that removal from
7207 // the finalized tree is only a safety net and should
7208 // never happen.
7209 LOCK2(cs_main, m_mempool.cs);
7210
7211 std::shared_ptr<const std::vector<Coin>> spentCoins;
7212 if (status == avalanche::VoteStatus::Invalid) {
7213 // Get the spent coins before removing the tx from
7214 // the mempool.
7215 CCoinsViewMemPool coinViewMempool(
7216 &m_chainman.ActiveChainstate().CoinsTip(),
7217 m_mempool);
7218 CCoinsViewCache coinViewCache(&coinViewMempool);
7219 auto _spentCoins = GetSpentCoins(tx, coinViewCache);
7220 // spentCoins can be null here if the parent tx has
7221 // been invalidated already
7222 spentCoins =
7223 _spentCoins.has_value()
7224 ? std::make_shared<const std::vector<Coin>>(
7225 std::move(*_spentCoins))
7226 : nullptr;
7227 }
7228
7229 if (m_mempool.exists(txid)) {
7230 m_mempool.removeRecursive(
7232
7233 std::vector<CTransactionRef> conflictingTxs =
7234 m_mempool.withConflicting(
7235 [&tx](const TxConflicting &conflicting) {
7236 return conflicting.GetConflictTxs(tx);
7237 });
7238
7239 if (conflictingTxs.size() > 0) {
7240 // Pull the first tx only, erase the others so
7241 // they can be re-downloaded if needed.
7242 auto result = m_chainman.ProcessTransaction(
7243 conflictingTxs[0]);
7244 if (!result.m_state.IsValid()) {
7245 LogPrint(
7247 "Attempting to pull a now invalid "
7248 "conflicting tx %s to mempool\n",
7249 conflictingTxs[0]->GetId().ToString());
7250 }
7251 }
7252
7253 m_mempool.withConflicting(
7254 [&conflictingTxs,
7255 &tx](TxConflicting &conflicting) {
7256 for (const auto &conflictingTx :
7257 conflictingTxs) {
7258 conflicting.EraseTx(
7259 conflictingTx->GetId());
7260 }
7261
7262 // Note that we don't store the descendants,
7263 // which should be re-downloaded. This could
7264 // be optimized but we will have to manage
7265 // the topological ordering.
7266 conflicting.AddTx(tx, NO_NODE);
7267 });
7268 }
7269
7270 if (status == avalanche::VoteStatus::Invalid) {
7271 // Also remove from the conflicting pool. If it was
7272 // in the mempool (unlikely) we just moved it there.
7273 m_mempool.withConflicting(
7274 [&txid](TxConflicting &conflicting) {
7275 conflicting.EraseTx(txid);
7276 });
7277
7278 m_recent_rejects.insert(txid);
7279
7280 AddToCompactExtraTransactions(tx);
7281
7283 spentCoins);
7284 }
7285
7286 break;
7287 }
7289 // fallthrough
7291 {
7292 LOCK2(cs_main, m_mempool.cs);
7293 if (m_mempool.withConflicting(
7294 [&txid](const TxConflicting &conflicting) {
7295 return conflicting.HaveTx(txid);
7296 })) {
7297 // Swap conflicting txs from/to the mempool
7298 std::vector<CTransactionRef>
7299 mempool_conflicting_txs;
7300 for (const auto &txin : tx->vin) {
7301 // Find the conflicting txs
7302 if (CTransactionRef conflict =
7303 m_mempool.GetConflictTx(
7304 txin.prevout)) {
7305 mempool_conflicting_txs.push_back(
7306 std::move(conflict));
7307 }
7308 }
7309 m_mempool.removeConflicts(*tx);
7310
7311 auto result = m_chainman.ProcessTransaction(tx);
7312 if (!result.m_state.IsValid()) {
7313 LogError("accepted tx %s failed mempool "
7314 "acceptance: %s\n",
7315 txid.ToString(),
7316 result.m_state.ToString());
7317 break;
7318 }
7319
7320 m_mempool.withConflicting(
7321 [&txid, &mempool_conflicting_txs](
7322 TxConflicting &conflicting) {
7323 conflicting.EraseTx(txid);
7324 // Store the first tx only, the others
7325 // can be re-downloaded if needed.
7326 if (mempool_conflicting_txs.size() >
7327 0) {
7328 conflicting.AddTx(
7329 mempool_conflicting_txs[0],
7330 NO_NODE);
7331 }
7332 });
7333 }
7334 }
7335
7336 if (status == avalanche::VoteStatus::Finalized) {
7337 LOCK2(cs_main, m_mempool.cs);
7338 auto it = m_mempool.GetIter(txid);
7339 if (!it.has_value()) {
7340 LogPrint(
7342 "Error: finalized tx (%s) is not in the "
7343 "mempool\n",
7344 txid.ToString());
7345 break;
7346 }
7347
7348 std::vector<TxId> finalizedTxIds;
7349 m_mempool.setAvalancheFinalized(
7350 **it, m_chainparams.GetConsensus(),
7351 *Assert(m_chainman.ActiveTip()),
7352 finalizedTxIds);
7353
7354 for (const auto &finalized_txid : finalizedTxIds) {
7355 m_avalanche->setRecentlyFinalized(
7356 finalized_txid);
7357 // Log the parent tx being implicitely finalized
7358 // as well
7359 logVoteUpdate(u, "tx", finalized_txid);
7360 }
7361
7362 // NO_THREAD_SAFETY_ANALYSIS because
7363 // m_recent_rejects requires cs_main in the lambda
7364 m_mempool.withConflicting(
7365 [&](TxConflicting &conflicting)
7367 std::vector<CTransactionRef>
7368 conflictingTxs =
7369 conflicting.GetConflictTxs(tx);
7370 for (const auto &conflictingTx :
7371 conflictingTxs) {
7372 m_recent_rejects.insert(
7373 conflictingTx->GetId());
7374 conflicting.EraseTx(
7375 conflictingTx->GetId());
7376 }
7377 });
7378 }
7379
7380 break;
7381 }
7383 LOCK(cs_main);
7384
7385 // If the tx is stale, there is no point keeping it
7386 // around as it will no be mined. Let's remove it but
7387 // also forget we got it so it can be eventually
7388 // re-downloaded.
7389 {
7390 LOCK(m_mempool.cs);
7391 m_mempool.removeRecursive(
7393
7394 m_mempool.withConflicting(
7395 [&txid](TxConflicting &conflicting) {
7396 conflicting.EraseTx(txid);
7397 });
7398 }
7399
7400 // Make sure we can request this tx again
7401 m_txrequest.ForgetInvId(txid);
7402
7403 {
7404 // Save the stalled txids so that we can relay them
7405 // to our peers.
7406 LOCK(m_peer_mutex);
7407 for (auto &it : m_peer_map) {
7408 auto tx_relay = (*it.second).GetTxRelay();
7409 if (!tx_relay) {
7410 continue;
7411 }
7412
7413 LOCK(tx_relay->m_tx_inventory_mutex);
7414
7415 // We limit the size of the stalled txs set to
7416 // avoid unbounded memory growth. In practice,
7417 // this should not be an issue as stalled txs
7418 // should be few and far between. If we are at
7419 // the limit, remove the oldest entries.
7420 auto &stalled_by_time =
7421 tx_relay->m_avalanche_stalled_txids
7422 .get<by_time>();
7423 if (stalled_by_time.size() >=
7425 stalled_by_time.erase(
7426 stalled_by_time.begin()->timeAdded);
7427 }
7428
7429 tx_relay->m_avalanche_stalled_txids.insert(
7430 {txid, now});
7431 }
7432 }
7433
7434 AddToCompactExtraTransactions(tx);
7435
7436 break;
7437 }
7438 }
7439 }
7440 }
7441
7442 if (shouldActivateBestChain) {
7444 if (!m_chainman.ActiveChainstate().ActivateBestChain(
7445 state, /*pblock=*/nullptr, m_avalanche)) {
7446 LogPrintf("failed to activate chain (%s)\n", state.ToString());
7447 }
7448 }
7449
7450 return;
7451 }
7452
7453 if (msg_type == NetMsgType::AVAPROOF) {
7454 if (!m_avalanche) {
7455 return;
7456 }
7457 auto proof = RCUPtr<avalanche::Proof>::make();
7458 vRecv >> *proof;
7459
7460 ReceivedAvalancheProof(pfrom, *peer, proof);
7461
7462 return;
7463 }
7464
7465 if (msg_type == NetMsgType::GETAVAPROOFS) {
7466 if (!m_avalanche) {
7467 return;
7468 }
7469 if (peer->m_proof_relay == nullptr) {
7470 return;
7471 }
7472
7473 peer->m_proof_relay->lastSharedProofsUpdate =
7474 GetTime<std::chrono::seconds>();
7475
7476 peer->m_proof_relay->sharedProofs =
7477 m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
7478 return pm.getShareableProofsSnapshot();
7479 });
7480
7481 avalanche::CompactProofs compactProofs(
7482 peer->m_proof_relay->sharedProofs);
7483 MakeAndPushMessage(pfrom, NetMsgType::AVAPROOFS, compactProofs);
7484
7485 return;
7486 }
7487
7488 if (msg_type == NetMsgType::AVAPROOFS) {
7489 if (!m_avalanche) {
7490 return;
7491 }
7492 if (peer->m_proof_relay == nullptr) {
7493 return;
7494 }
7495
7496 // Only process the compact proofs if we requested them
7497 if (!peer->m_proof_relay->compactproofs_requested) {
7498 LogPrint(BCLog::AVALANCHE, "Ignoring unsollicited avaproofs\n");
7499 return;
7500 }
7501 peer->m_proof_relay->compactproofs_requested = false;
7502
7503 avalanche::CompactProofs compactProofs;
7504 try {
7505 vRecv >> compactProofs;
7506 } catch (std::ios_base::failure &e) {
7507 // This compact proofs have non contiguous or overflowing indexes
7508 Misbehaving(*peer, "avaproofs-bad-indexes");
7509 return;
7510 }
7511
7512 // If there are prefilled proofs, process them first
7513 for (const auto &prefilledProof : compactProofs.getPrefilledProofs()) {
7514 if (!ReceivedAvalancheProof(pfrom, *peer, prefilledProof.proof)) {
7515 // If we got an invalid proof, the peer is getting banned and we
7516 // can bail out.
7517 return;
7518 }
7519 }
7520
7521 // If there is no shortid, avoid parsing/responding/accounting for the
7522 // message.
7523 if (compactProofs.getShortIDs().size() == 0) {
7524 return;
7525 }
7526
7527 // To determine the chance that the number of entries in a bucket
7528 // exceeds N, we use the fact that the number of elements in a single
7529 // bucket is binomially distributed (with n = the number of shorttxids
7530 // S, and p = 1 / the number of buckets), that in the worst case the
7531 // number of buckets is equal to S (due to std::unordered_map having a
7532 // default load factor of 1.0), and that the chance for any bucket to
7533 // exceed N elements is at most buckets * (the chance that any given
7534 // bucket is above N elements). Thus:
7535 // P(max_elements_per_bucket > N) <=
7536 // S * (1 - cdf(binomial(n=S,p=1/S), N))
7537 // If we assume up to 21000000, allowing 15 elements per bucket should
7538 // only fail once per ~2.5 million avaproofs transfers (per peer and
7539 // connection).
7540 // TODO re-evaluate the bucket count to a more realistic value.
7541 // TODO: In the case of a shortid-collision, we should request all the
7542 // proofs which collided. For now, we only request one, which is not
7543 // that bad considering this event is expected to be very rare.
7544 auto shortIdProcessor =
7546 compactProofs.getShortIDs(), 15);
7547
7548 if (shortIdProcessor.hasOutOfBoundIndex()) {
7549 // This should be catched by deserialization, but catch it here as
7550 // well as a good measure.
7551 Misbehaving(*peer, "avaproofs-bad-indexes");
7552 return;
7553 }
7554 if (!shortIdProcessor.isEvenlyDistributed()) {
7555 // This is suspicious, don't ban but bail out
7556 return;
7557 }
7558
7559 std::vector<std::pair<avalanche::ProofId, bool>> remoteProofsStatus;
7560 m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
7561 pm.forEachPeer([&](const avalanche::Peer &peer) {
7562 assert(peer.proof);
7563 uint64_t shortid = compactProofs.getShortID(peer.getProofId());
7564
7565 int added =
7566 shortIdProcessor.matchKnownItem(shortid, peer.proof);
7567
7568 // No collision
7569 if (added >= 0) {
7570 // Because we know the proof, we can determine if our peer
7571 // has it (added = 1) or not (added = 0) and update the
7572 // remote proof status accordingly.
7573 remoteProofsStatus.emplace_back(peer.getProofId(),
7574 added > 0);
7575 }
7576
7577 // In order to properly determine which proof is missing, we
7578 // need to keep scanning for all our proofs.
7579 return true;
7580 });
7581 });
7582
7584 for (size_t i = 0; i < compactProofs.size(); i++) {
7585 if (shortIdProcessor.getItem(i) == nullptr) {
7586 req.indices.push_back(i);
7587 }
7588 }
7589
7590 MakeAndPushMessage(pfrom, NetMsgType::AVAPROOFSREQ, req);
7591
7592 const NodeId nodeid = pfrom.GetId();
7593
7594 // We want to keep a count of how many nodes we successfully requested
7595 // avaproofs from as this is used to determine when we are confident our
7596 // quorum is close enough to the other participants.
7597 m_avalanche->avaproofsSent(nodeid);
7598
7599 // Only save remote proofs from stakers
7601 return pfrom.m_avalanche_pubkey.has_value())) {
7602 m_avalanche->withPeerManager(
7603 [&remoteProofsStatus, nodeid](avalanche::PeerManager &pm) {
7604 for (const auto &[proofid, present] : remoteProofsStatus) {
7605 pm.saveRemoteProof(proofid, nodeid, present);
7606 }
7607 });
7608 }
7609
7610 return;
7611 }
7612
7613 if (msg_type == NetMsgType::AVAPROOFSREQ) {
7614 if (peer->m_proof_relay == nullptr) {
7615 return;
7616 }
7617
7618 avalanche::ProofsRequest proofreq;
7619 vRecv >> proofreq;
7620
7621 auto requestedIndiceIt = proofreq.indices.begin();
7622 uint32_t treeIndice = 0;
7623 peer->m_proof_relay->sharedProofs.forEachLeaf([&](const auto &proof) {
7624 if (requestedIndiceIt == proofreq.indices.end()) {
7625 // No more indice to process
7626 return false;
7627 }
7628
7629 if (treeIndice++ == *requestedIndiceIt) {
7630 MakeAndPushMessage(pfrom, NetMsgType::AVAPROOF, *proof);
7631 requestedIndiceIt++;
7632 }
7633
7634 return true;
7635 });
7636
7637 peer->m_proof_relay->sharedProofs = {};
7638 return;
7639 }
7640
7641 if (msg_type == NetMsgType::GETADDR) {
7642 // This asymmetric behavior for inbound and outbound connections was
7643 // introduced to prevent a fingerprinting attack: an attacker can send
7644 // specific fake addresses to users' AddrMan and later request them by
7645 // sending getaddr messages. Making nodes which are behind NAT and can
7646 // only make outgoing connections ignore the getaddr message mitigates
7647 // the attack.
7648 if (!pfrom.IsInboundConn()) {
7650 "Ignoring \"getaddr\" from %s connection. peer=%d\n",
7651 pfrom.ConnectionTypeAsString(), pfrom.GetId());
7652 return;
7653 }
7654
7655 // Since this must be an inbound connection, SetupAddressRelay will
7656 // never fail.
7657 Assume(SetupAddressRelay(pfrom, *peer));
7658
7659 // Only send one GetAddr response per connection to reduce resource
7660 // waste and discourage addr stamping of INV announcements.
7661 if (peer->m_getaddr_recvd) {
7662 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n",
7663 pfrom.GetId());
7664 return;
7665 }
7666 peer->m_getaddr_recvd = true;
7667
7668 peer->m_addrs_to_send.clear();
7669 std::vector<CAddress> vAddr;
7670 const size_t maxAddrToSend = m_opts.max_addr_to_send;
7672 vAddr = m_connman.GetAddresses(maxAddrToSend, MAX_PCT_ADDR_TO_SEND,
7673 /* network */ std::nullopt);
7674 } else {
7675 vAddr = m_connman.GetAddresses(pfrom, maxAddrToSend,
7677 }
7678 for (const CAddress &addr : vAddr) {
7679 PushAddress(*peer, addr);
7680 }
7681 return;
7682 }
7683
7684 if (msg_type == NetMsgType::GETAVAADDR) {
7685 auto now = GetTime<std::chrono::seconds>();
7686 if (now < pfrom.m_nextGetAvaAddr) {
7687 // Prevent a peer from exhausting our resources by spamming
7688 // getavaaddr messages.
7689 return;
7690 }
7691
7692 // Only accept a getavaaddr every GETAVAADDR_INTERVAL at most
7694
7695 if (!SetupAddressRelay(pfrom, *peer)) {
7697 "Ignoring getavaaddr message from %s peer=%d\n",
7698 pfrom.ConnectionTypeAsString(), pfrom.GetId());
7699 return;
7700 }
7701
7702 auto availabilityScoreComparator = [](const CNode *lhs,
7703 const CNode *rhs) {
7704 double scoreLhs = lhs->getAvailabilityScore();
7705 double scoreRhs = rhs->getAvailabilityScore();
7706
7707 if (scoreLhs != scoreRhs) {
7708 return scoreLhs > scoreRhs;
7709 }
7710
7711 return lhs < rhs;
7712 };
7713
7714 // Get up to MAX_ADDR_TO_SEND addresses of the nodes which are the
7715 // most active in the avalanche network. Account for 0 availability as
7716 // well so we can send addresses even if we did not start polling yet.
7717 std::set<const CNode *, decltype(availabilityScoreComparator)> avaNodes(
7718 availabilityScoreComparator);
7719 m_connman.ForEachNode([&](const CNode *pnode) {
7720 if (!pnode->m_avalanche_enabled ||
7721 pnode->getAvailabilityScore() < 0.) {
7722 return;
7723 }
7724
7725 avaNodes.insert(pnode);
7726 if (avaNodes.size() > m_opts.max_addr_to_send) {
7727 avaNodes.erase(std::prev(avaNodes.end()));
7728 }
7729 });
7730
7731 peer->m_addrs_to_send.clear();
7732 for (const CNode *pnode : avaNodes) {
7733 PushAddress(*peer, pnode->addr);
7734 }
7735
7736 return;
7737 }
7738
7739 if (msg_type == NetMsgType::MEMPOOL) {
7740 if (!(peer->m_our_services & NODE_BLOOM) &&
7744 "mempool request with bloom filters disabled, "
7745 "disconnect peer=%d\n",
7746 pfrom.GetId());
7747 pfrom.fDisconnect = true;
7748 }
7749 return;
7750 }
7751
7752 if (m_connman.OutboundTargetReached(false) &&
7756 "mempool request with bandwidth limit reached, "
7757 "disconnect peer=%d\n",
7758 pfrom.GetId());
7759 pfrom.fDisconnect = true;
7760 }
7761 return;
7762 }
7763
7764 if (auto tx_relay = peer->GetTxRelay()) {
7765 LOCK(tx_relay->m_tx_inventory_mutex);
7766 tx_relay->m_send_mempool = true;
7767 }
7768 return;
7769 }
7770
7771 if (msg_type == NetMsgType::PING) {
7772 if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
7773 uint64_t nonce = 0;
7774 vRecv >> nonce;
7775 // Echo the message back with the nonce. This allows for two useful
7776 // features:
7777 //
7778 // 1) A remote node can quickly check if the connection is
7779 // operational.
7780 // 2) Remote nodes can measure the latency of the network thread. If
7781 // this node is overloaded it won't respond to pings quickly and the
7782 // remote node can avoid sending us more work, like chain download
7783 // requests.
7784 //
7785 // The nonce stops the remote getting confused between different
7786 // pings: without it, if the remote node sends a ping once per
7787 // second and this node takes 5 seconds to respond to each, the 5th
7788 // ping the remote sends would appear to return very quickly.
7789 MakeAndPushMessage(pfrom, NetMsgType::PONG, nonce);
7790 }
7791 return;
7792 }
7793
7794 if (msg_type == NetMsgType::PONG) {
7795 const auto ping_end = time_received;
7796 uint64_t nonce = 0;
7797 size_t nAvail = vRecv.in_avail();
7798 bool bPingFinished = false;
7799 std::string sProblem;
7800
7801 if (nAvail >= sizeof(nonce)) {
7802 vRecv >> nonce;
7803
7804 // Only process pong message if there is an outstanding ping (old
7805 // ping without nonce should never pong)
7806 if (peer->m_ping_nonce_sent != 0) {
7807 if (nonce == peer->m_ping_nonce_sent) {
7808 // Matching pong received, this ping is no longer
7809 // outstanding
7810 bPingFinished = true;
7811 const auto ping_time = ping_end - peer->m_ping_start.load();
7812 if (ping_time.count() >= 0) {
7813 // Let connman know about this successful ping-pong
7814 pfrom.PongReceived(ping_time);
7815 } else {
7816 // This should never happen
7817 sProblem = "Timing mishap";
7818 }
7819 } else {
7820 // Nonce mismatches are normal when pings are overlapping
7821 sProblem = "Nonce mismatch";
7822 if (nonce == 0) {
7823 // This is most likely a bug in another implementation
7824 // somewhere; cancel this ping
7825 bPingFinished = true;
7826 sProblem = "Nonce zero";
7827 }
7828 }
7829 } else {
7830 sProblem = "Unsolicited pong without ping";
7831 }
7832 } else {
7833 // This is most likely a bug in another implementation somewhere;
7834 // cancel this ping
7835 bPingFinished = true;
7836 sProblem = "Short payload";
7837 }
7838
7839 if (!(sProblem.empty())) {
7841 "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
7842 pfrom.GetId(), sProblem, peer->m_ping_nonce_sent, nonce,
7843 nAvail);
7844 }
7845 if (bPingFinished) {
7846 peer->m_ping_nonce_sent = 0;
7847 }
7848 return;
7849 }
7850
7851 if (msg_type == NetMsgType::FILTERLOAD) {
7852 if (!(peer->m_our_services & NODE_BLOOM)) {
7854 "filterload received despite not offering bloom services "
7855 "from peer=%d; disconnecting\n",
7856 pfrom.GetId());
7857 pfrom.fDisconnect = true;
7858 return;
7859 }
7860 CBloomFilter filter;
7861 vRecv >> filter;
7862
7863 if (!filter.IsWithinSizeConstraints()) {
7864 // There is no excuse for sending a too-large filter
7865 Misbehaving(*peer, "too-large bloom filter");
7866 } else if (auto tx_relay = peer->GetTxRelay()) {
7867 {
7868 LOCK(tx_relay->m_bloom_filter_mutex);
7869 tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
7870 tx_relay->m_relay_txs = true;
7871 }
7872 pfrom.m_bloom_filter_loaded = true;
7873 }
7874 return;
7875 }
7876
7877 if (msg_type == NetMsgType::FILTERADD) {
7878 if (!(peer->m_our_services & NODE_BLOOM)) {
7880 "filteradd received despite not offering bloom services "
7881 "from peer=%d; disconnecting\n",
7882 pfrom.GetId());
7883 pfrom.fDisconnect = true;
7884 return;
7885 }
7886 std::vector<uint8_t> vData;
7887 vRecv >> vData;
7888
7889 // Nodes must NEVER send a data item > 520 bytes (the max size for a
7890 // script data object, and thus, the maximum size any matched object can
7891 // have) in a filteradd message.
7892 bool bad = false;
7893 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
7894 bad = true;
7895 } else if (auto tx_relay = peer->GetTxRelay()) {
7896 LOCK(tx_relay->m_bloom_filter_mutex);
7897 if (tx_relay->m_bloom_filter) {
7898 tx_relay->m_bloom_filter->insert(vData);
7899 } else {
7900 bad = true;
7901 }
7902 }
7903 if (bad) {
7904 // The structure of this code doesn't really allow for a good error
7905 // code. We'll go generic.
7906 Misbehaving(*peer, "bad filteradd message");
7907 }
7908 return;
7909 }
7910
7911 if (msg_type == NetMsgType::FILTERCLEAR) {
7912 if (!(peer->m_our_services & NODE_BLOOM)) {
7914 "filterclear received despite not offering bloom services "
7915 "from peer=%d; disconnecting\n",
7916 pfrom.GetId());
7917 pfrom.fDisconnect = true;
7918 return;
7919 }
7920 auto tx_relay = peer->GetTxRelay();
7921 if (!tx_relay) {
7922 return;
7923 }
7924
7925 {
7926 LOCK(tx_relay->m_bloom_filter_mutex);
7927 tx_relay->m_bloom_filter = nullptr;
7928 tx_relay->m_relay_txs = true;
7929 }
7930 pfrom.m_bloom_filter_loaded = false;
7931 pfrom.m_relays_txs = true;
7932 return;
7933 }
7934
7935 if (msg_type == NetMsgType::FEEFILTER) {
7936 Amount newFeeFilter = Amount::zero();
7937 vRecv >> newFeeFilter;
7938 if (MoneyRange(newFeeFilter)) {
7939 if (auto tx_relay = peer->GetTxRelay()) {
7940 tx_relay->m_fee_filter_received = newFeeFilter;
7941 }
7942 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n",
7943 CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
7944 }
7945 return;
7946 }
7947
7948 if (msg_type == NetMsgType::GETCFILTERS) {
7949 ProcessGetCFilters(pfrom, *peer, vRecv);
7950 return;
7951 }
7952
7953 if (msg_type == NetMsgType::GETCFHEADERS) {
7954 ProcessGetCFHeaders(pfrom, *peer, vRecv);
7955 return;
7956 }
7957
7958 if (msg_type == NetMsgType::GETCFCHECKPT) {
7959 ProcessGetCFCheckPt(pfrom, *peer, vRecv);
7960 return;
7961 }
7962
7963 if (msg_type == NetMsgType::NOTFOUND) {
7964 std::vector<CInv> vInv;
7965 vRecv >> vInv;
7966 // A peer might send up to 1 notfound per getdata request, but no more
7967 if (vInv.size() <= PROOF_REQUEST_PARAMS.max_peer_announcements +
7970 for (CInv &inv : vInv) {
7971 if (inv.IsMsgTx()) {
7972 // If we receive a NOTFOUND message for a tx we requested,
7973 // mark the announcement for it as completed in
7974 // InvRequestTracker.
7975 LOCK(::cs_main);
7976 m_txrequest.ReceivedResponse(pfrom.GetId(), TxId(inv.hash));
7977 continue;
7978 }
7979 if (inv.IsMsgProof()) {
7980 if (!m_avalanche) {
7981 continue;
7982 }
7983 LOCK(cs_proofrequest);
7984 m_proofrequest.ReceivedResponse(
7985 pfrom.GetId(), avalanche::ProofId(inv.hash));
7986 }
7987 }
7988 }
7989 return;
7990 }
7991
7992 // Ignore unknown commands for extensibility
7993 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n",
7994 SanitizeString(msg_type), pfrom.GetId());
7995 return;
7996}
7997
7998bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode &pnode, Peer &peer) {
7999 {
8000 LOCK(peer.m_misbehavior_mutex);
8001
8002 // There's nothing to do if the m_should_discourage flag isn't set
8003 if (!peer.m_should_discourage) {
8004 return false;
8005 }
8006
8007 peer.m_should_discourage = false;
8008 } // peer.m_misbehavior_mutex
8009
8011 // We never disconnect or discourage peers for bad behavior if they have
8012 // NetPermissionFlags::NoBan permission
8013 LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id);
8014 return false;
8015 }
8016
8017 if (pnode.IsManualConn()) {
8018 // We never disconnect or discourage manual peers for bad behavior
8019 LogPrintf("Warning: not punishing manually connected peer %d!\n",
8020 peer.m_id);
8021 return false;
8022 }
8023
8024 if (pnode.addr.IsLocal()) {
8025 // We disconnect local peers for bad behavior but don't discourage
8026 // (since that would discourage all peers on the same local address)
8028 "Warning: disconnecting but not discouraging %s peer %d!\n",
8029 pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
8030 pnode.fDisconnect = true;
8031 return true;
8032 }
8033
8034 // Normal case: Disconnect the peer and discourage all nodes sharing the
8035 // address
8036 LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n",
8037 peer.m_id);
8038 if (m_banman) {
8039 m_banman->Discourage(pnode.addr);
8040 }
8041 m_connman.DisconnectNode(pnode.addr);
8042 return true;
8043}
8044
8045bool PeerManagerImpl::ProcessMessages(const Config &config, CNode *pfrom,
8046 std::atomic<bool> &interruptMsgProc) {
8047 AssertLockHeld(g_msgproc_mutex);
8048
8049 PeerRef peer = GetPeerRef(pfrom->GetId());
8050 if (peer == nullptr) {
8051 return false;
8052 }
8053
8054 {
8055 LOCK(peer->m_getdata_requests_mutex);
8056 if (!peer->m_getdata_requests.empty()) {
8057 ProcessGetData(config, *pfrom, *peer, interruptMsgProc);
8058 }
8059 }
8060
8061 const bool processed_orphan = ProcessOrphanTx(config, *peer);
8062
8063 if (pfrom->fDisconnect) {
8064 return false;
8065 }
8066
8067 if (processed_orphan) {
8068 return true;
8069 }
8070
8071 // this maintains the order of responses and prevents m_getdata_requests to
8072 // grow unbounded
8073 {
8074 LOCK(peer->m_getdata_requests_mutex);
8075 if (!peer->m_getdata_requests.empty()) {
8076 return true;
8077 }
8078 }
8079
8080 // Don't bother if send buffer is too full to respond anyway
8081 if (pfrom->fPauseSend) {
8082 return false;
8083 }
8084
8085 auto poll_result{pfrom->PollMessage()};
8086 if (!poll_result) {
8087 // No message to process
8088 return false;
8089 }
8090
8091 CNetMessage &msg{poll_result->first};
8092 bool fMoreWork = poll_result->second;
8093
8094 TRACE6(net, inbound_message, pfrom->GetId(), pfrom->m_addr_name.c_str(),
8095 pfrom->ConnectionTypeAsString().c_str(), msg.m_type.c_str(),
8096 msg.m_recv.size(), msg.m_recv.data());
8097
8098 if (m_opts.capture_messages) {
8099 CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv),
8100 /*is_incoming=*/true);
8101 }
8102
8103 try {
8104 ProcessMessage(config, *pfrom, msg.m_type, msg.m_recv, msg.m_time,
8105 interruptMsgProc);
8106 if (interruptMsgProc) {
8107 return false;
8108 }
8109
8110 {
8111 LOCK(peer->m_getdata_requests_mutex);
8112 if (!peer->m_getdata_requests.empty()) {
8113 fMoreWork = true;
8114 }
8115 }
8116 // Does this peer has an orphan ready to reconsider?
8117 // (Note: we may have provided a parent for an orphan provided by
8118 // another peer that was already processed; in that case, the extra work
8119 // may not be noticed, possibly resulting in an unnecessary 100ms delay)
8120 if (m_mempool.withOrphanage([&peer](TxOrphanage &orphanage) {
8121 return orphanage.HaveTxToReconsider(peer->m_id);
8122 })) {
8123 fMoreWork = true;
8124 }
8125 } catch (const std::exception &e) {
8126 LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n",
8127 __func__, SanitizeString(msg.m_type), msg.m_message_size,
8128 e.what(), typeid(e).name());
8129 } catch (...) {
8130 LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n",
8131 __func__, SanitizeString(msg.m_type), msg.m_message_size);
8132 }
8133
8134 return fMoreWork;
8135}
8136
8137void PeerManagerImpl::ConsiderEviction(CNode &pto, Peer &peer,
8138 std::chrono::seconds time_in_seconds) {
8140
8141 CNodeState &state = *State(pto.GetId());
8142
8143 if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() &&
8144 state.fSyncStarted) {
8145 // This is an outbound peer subject to disconnection if they don't
8146 // announce a block with as much work as the current tip within
8147 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if their
8148 // chain has more work than ours, we should sync to it, unless it's
8149 // invalid, in which case we should find that out and disconnect from
8150 // them elsewhere).
8151 if (state.pindexBestKnownBlock != nullptr &&
8152 state.pindexBestKnownBlock->nChainWork >=
8153 m_chainman.ActiveChain().Tip()->nChainWork) {
8154 if (state.m_chain_sync.m_timeout != 0s) {
8155 state.m_chain_sync.m_timeout = 0s;
8156 state.m_chain_sync.m_work_header = nullptr;
8157 state.m_chain_sync.m_sent_getheaders = false;
8158 }
8159 } else if (state.m_chain_sync.m_timeout == 0s ||
8160 (state.m_chain_sync.m_work_header != nullptr &&
8161 state.pindexBestKnownBlock != nullptr &&
8162 state.pindexBestKnownBlock->nChainWork >=
8163 state.m_chain_sync.m_work_header->nChainWork)) {
8164 // Our best block known by this peer is behind our tip, and we're
8165 // either noticing that for the first time, OR this peer was able to
8166 // catch up to some earlier point where we checked against our tip.
8167 // Either way, set a new timeout based on current tip.
8168 state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
8169 state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
8170 state.m_chain_sync.m_sent_getheaders = false;
8171 } else if (state.m_chain_sync.m_timeout > 0s &&
8172 time_in_seconds > state.m_chain_sync.m_timeout) {
8173 // No evidence yet that our peer has synced to a chain with work
8174 // equal to that of our tip, when we first detected it was behind.
8175 // Send a single getheaders message to give the peer a chance to
8176 // update us.
8177 if (state.m_chain_sync.m_sent_getheaders) {
8178 // They've run out of time to catch up!
8179 LogPrintf(
8180 "Disconnecting outbound peer %d for old chain, best known "
8181 "block = %s\n",
8182 pto.GetId(),
8183 state.pindexBestKnownBlock != nullptr
8184 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
8185 : "<none>");
8186 pto.fDisconnect = true;
8187 } else {
8188 assert(state.m_chain_sync.m_work_header);
8189 // Here, we assume that the getheaders message goes out,
8190 // because it'll either go out or be skipped because of a
8191 // getheaders in-flight already, in which case the peer should
8192 // still respond to us with a sufficiently high work chain tip.
8193 MaybeSendGetHeaders(
8194 pto, GetLocator(state.m_chain_sync.m_work_header->pprev),
8195 peer);
8196 LogPrint(
8197 BCLog::NET,
8198 "sending getheaders to outbound peer=%d to verify chain "
8199 "work (current best known block:%s, benchmark blockhash: "
8200 "%s)\n",
8201 pto.GetId(),
8202 state.pindexBestKnownBlock != nullptr
8203 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
8204 : "<none>",
8205 state.m_chain_sync.m_work_header->GetBlockHash()
8206 .ToString());
8207 state.m_chain_sync.m_sent_getheaders = true;
8208 // Bump the timeout to allow a response, which could clear the
8209 // timeout (if the response shows the peer has synced), reset
8210 // the timeout (if the peer syncs to the required work but not
8211 // to our tip), or result in disconnect (if we advance to the
8212 // timeout and pindexBestKnownBlock has not sufficiently
8213 // progressed)
8214 state.m_chain_sync.m_timeout =
8215 time_in_seconds + HEADERS_RESPONSE_TIME;
8216 }
8217 }
8218 }
8219}
8220
8221void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) {
8222 // If we have any extra block-relay-only peers, disconnect the youngest
8223 // unless it's given us a block -- in which case, compare with the
8224 // second-youngest, and out of those two, disconnect the peer who least
8225 // recently gave us a block.
8226 // The youngest block-relay-only peer would be the extra peer we connected
8227 // to temporarily in order to sync our tip; see net.cpp.
8228 // Note that we use higher nodeid as a measure for most recent connection.
8229 if (m_connman.GetExtraBlockRelayCount() > 0) {
8230 std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0},
8231 next_youngest_peer{-1, 0};
8232
8233 m_connman.ForEachNode([&](CNode *pnode) {
8234 if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) {
8235 return;
8236 }
8237 if (pnode->GetId() > youngest_peer.first) {
8238 next_youngest_peer = youngest_peer;
8239 youngest_peer.first = pnode->GetId();
8240 youngest_peer.second = pnode->m_last_block_time;
8241 }
8242 });
8243
8244 NodeId to_disconnect = youngest_peer.first;
8245 if (youngest_peer.second > next_youngest_peer.second) {
8246 // Our newest block-relay-only peer gave us a block more recently;
8247 // disconnect our second youngest.
8248 to_disconnect = next_youngest_peer.first;
8249 }
8250
8251 m_connman.ForNode(
8252 to_disconnect,
8255 // Make sure we're not getting a block right now, and that we've
8256 // been connected long enough for this eviction to happen at
8257 // all. Note that we only request blocks from a peer if we learn
8258 // of a valid headers chain with at least as much work as our
8259 // tip.
8260 CNodeState *node_state = State(pnode->GetId());
8261 if (node_state == nullptr ||
8262 (now - pnode->m_connected >= MINIMUM_CONNECT_TIME &&
8263 node_state->vBlocksInFlight.empty())) {
8264 pnode->fDisconnect = true;
8266 "disconnecting extra block-relay-only peer=%d "
8267 "(last block received at time %d)\n",
8268 pnode->GetId(),
8270 return true;
8271 } else {
8272 LogPrint(
8273 BCLog::NET,
8274 "keeping block-relay-only peer=%d chosen for eviction "
8275 "(connect time: %d, blocks_in_flight: %d)\n",
8276 pnode->GetId(), count_seconds(pnode->m_connected),
8277 node_state->vBlocksInFlight.size());
8278 }
8279 return false;
8280 });
8281 }
8282
8283 // Check whether we have too many OUTBOUND_FULL_RELAY peers
8284 if (m_connman.GetExtraFullOutboundCount() <= 0) {
8285 return;
8286 }
8287
8288 // If we have more OUTBOUND_FULL_RELAY peers than we target, disconnect one.
8289 // Pick the OUTBOUND_FULL_RELAY peer that least recently announced us a new
8290 // block, with ties broken by choosing the more recent connection (higher
8291 // node id)
8292 NodeId worst_peer = -1;
8293 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
8294
8295 m_connman.ForEachNode([&](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(
8296 ::cs_main) {
8298
8299 // Only consider OUTBOUND_FULL_RELAY peers that are not already marked
8300 // for disconnection
8301 if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) {
8302 return;
8303 }
8304 CNodeState *state = State(pnode->GetId());
8305 if (state == nullptr) {
8306 // shouldn't be possible, but just in case
8307 return;
8308 }
8309 // Don't evict our protected peers
8310 if (state->m_chain_sync.m_protect) {
8311 return;
8312 }
8313 if (state->m_last_block_announcement < oldest_block_announcement ||
8314 (state->m_last_block_announcement == oldest_block_announcement &&
8315 pnode->GetId() > worst_peer)) {
8316 worst_peer = pnode->GetId();
8317 oldest_block_announcement = state->m_last_block_announcement;
8318 }
8319 });
8320
8321 if (worst_peer == -1) {
8322 return;
8323 }
8324
8325 bool disconnected = m_connman.ForNode(
8326 worst_peer, [&](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
8328
8329 // Only disconnect a peer that has been connected to us for some
8330 // reasonable fraction of our check-frequency, to give it time for
8331 // new information to have arrived. Also don't disconnect any peer
8332 // we're trying to download a block from.
8333 CNodeState &state = *State(pnode->GetId());
8334 if (now - pnode->m_connected > MINIMUM_CONNECT_TIME &&
8335 state.vBlocksInFlight.empty()) {
8337 "disconnecting extra outbound peer=%d (last block "
8338 "announcement received at time %d)\n",
8339 pnode->GetId(), oldest_block_announcement);
8340 pnode->fDisconnect = true;
8341 return true;
8342 } else {
8344 "keeping outbound peer=%d chosen for eviction "
8345 "(connect time: %d, blocks_in_flight: %d)\n",
8346 pnode->GetId(), count_seconds(pnode->m_connected),
8347 state.vBlocksInFlight.size());
8348 return false;
8349 }
8350 });
8351
8352 if (disconnected) {
8353 // If we disconnected an extra peer, that means we successfully
8354 // connected to at least one peer after the last time we detected a
8355 // stale tip. Don't try any more extra peers until we next detect a
8356 // stale tip, to limit the load we put on the network from these extra
8357 // connections.
8358 m_connman.SetTryNewOutboundPeer(false);
8359 }
8360}
8361
8362void PeerManagerImpl::CheckForStaleTipAndEvictPeers() {
8363 LOCK(cs_main);
8364
8365 auto now{GetTime<std::chrono::seconds>()};
8366
8367 EvictExtraOutboundPeers(now);
8368
8369 if (now > m_stale_tip_check_time) {
8370 // Check whether our tip is stale, and if so, allow using an extra
8371 // outbound peer.
8372 if (!m_chainman.m_blockman.LoadingBlocks() &&
8373 m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() &&
8374 TipMayBeStale()) {
8375 LogPrintf("Potential stale tip detected, will try using extra "
8376 "outbound peer (last tip update: %d seconds ago)\n",
8377 count_seconds(now - m_last_tip_update.load()));
8378 m_connman.SetTryNewOutboundPeer(true);
8379 } else if (m_connman.GetTryNewOutboundPeer()) {
8380 m_connman.SetTryNewOutboundPeer(false);
8381 }
8382 m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
8383 }
8384
8385 if (!m_initial_sync_finished && CanDirectFetch()) {
8386 m_connman.StartExtraBlockRelayPeers();
8387 m_initial_sync_finished = true;
8388 }
8389}
8390
8391void PeerManagerImpl::MaybeSendPing(CNode &node_to, Peer &peer,
8392 std::chrono::microseconds now) {
8393 if (m_connman.ShouldRunInactivityChecks(
8394 node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
8395 peer.m_ping_nonce_sent &&
8396 now > peer.m_ping_start.load() + TIMEOUT_INTERVAL) {
8397 // The ping timeout is using mocktime. To disable the check during
8398 // testing, increase -peertimeout.
8399 LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n",
8400 0.000001 * count_microseconds(now - peer.m_ping_start.load()),
8401 peer.m_id);
8402 node_to.fDisconnect = true;
8403 return;
8404 }
8405
8406 bool pingSend = false;
8407
8408 if (peer.m_ping_queued) {
8409 // RPC ping request by user
8410 pingSend = true;
8411 }
8412
8413 if (peer.m_ping_nonce_sent == 0 &&
8414 now > peer.m_ping_start.load() + PING_INTERVAL) {
8415 // Ping automatically sent as a latency probe & keepalive.
8416 pingSend = true;
8417 }
8418
8419 if (pingSend) {
8420 uint64_t nonce;
8421 do {
8422 nonce = FastRandomContext().rand64();
8423 } while (nonce == 0);
8424 peer.m_ping_queued = false;
8425 peer.m_ping_start = now;
8426 if (node_to.GetCommonVersion() > BIP0031_VERSION) {
8427 peer.m_ping_nonce_sent = nonce;
8428 MakeAndPushMessage(node_to, NetMsgType::PING, nonce);
8429 } else {
8430 // Peer is too old to support ping command with nonce, pong will
8431 // never arrive.
8432 peer.m_ping_nonce_sent = 0;
8433 MakeAndPushMessage(node_to, NetMsgType::PING);
8434 }
8435 }
8436}
8437
8438void PeerManagerImpl::MaybeSendAddr(CNode &node, Peer &peer,
8439 std::chrono::microseconds current_time) {
8440 // Nothing to do for non-address-relay peers
8441 if (!peer.m_addr_relay_enabled) {
8442 return;
8443 }
8444
8445 LOCK(peer.m_addr_send_times_mutex);
8446 if (fListen && !m_chainman.IsInitialBlockDownload() &&
8447 peer.m_next_local_addr_send < current_time) {
8448 // If we've sent before, clear the bloom filter for the peer, so
8449 // that our self-announcement will actually go out. This might
8450 // be unnecessary if the bloom filter has already rolled over
8451 // since our last self-announcement, but there is only a small
8452 // bandwidth cost that we can incur by doing this (which happens
8453 // once a day on average).
8454 if (peer.m_next_local_addr_send != 0us) {
8455 peer.m_addr_known->reset();
8456 }
8457 if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
8458 CAddress local_addr{*local_service, peer.m_our_services,
8459 Now<NodeSeconds>()};
8460 PushAddress(peer, local_addr);
8461 }
8462 peer.m_next_local_addr_send =
8463 current_time +
8464 m_rng.rand_exp_duration(AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
8465 }
8466
8467 // We sent an `addr` message to this peer recently. Nothing more to do.
8468 if (current_time <= peer.m_next_addr_send) {
8469 return;
8470 }
8471
8472 peer.m_next_addr_send =
8473 current_time + m_rng.rand_exp_duration(AVG_ADDRESS_BROADCAST_INTERVAL);
8474
8475 const size_t max_addr_to_send = m_opts.max_addr_to_send;
8476 if (!Assume(peer.m_addrs_to_send.size() <= max_addr_to_send)) {
8477 // Should be impossible since we always check size before adding to
8478 // m_addrs_to_send. Recover by trimming the vector.
8479 peer.m_addrs_to_send.resize(max_addr_to_send);
8480 }
8481
8482 // Remove addr records that the peer already knows about, and add new
8483 // addrs to the m_addr_known filter on the same pass.
8484 auto addr_already_known =
8485 [&peer](const CAddress &addr)
8486 EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) {
8487 bool ret = peer.m_addr_known->contains(addr.GetKey());
8488 if (!ret) {
8489 peer.m_addr_known->insert(addr.GetKey());
8490 }
8491 return ret;
8492 };
8493 peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(),
8494 peer.m_addrs_to_send.end(),
8495 addr_already_known),
8496 peer.m_addrs_to_send.end());
8497
8498 // No addr messages to send
8499 if (peer.m_addrs_to_send.empty()) {
8500 return;
8501 }
8502
8503 const char *msg_type;
8504 CNetAddr::Encoding ser_enc;
8505 if (peer.m_wants_addrv2) {
8506 msg_type = NetMsgType::ADDRV2;
8507 ser_enc = CNetAddr::Encoding::V2;
8508 } else {
8509 msg_type = NetMsgType::ADDR;
8510 ser_enc = CNetAddr::Encoding::V1;
8511 }
8512 MakeAndPushMessage(
8513 node, msg_type,
8515 peer.m_addrs_to_send));
8516 peer.m_addrs_to_send.clear();
8517
8518 // we only send the big addr message once
8519 if (peer.m_addrs_to_send.capacity() > 40) {
8520 peer.m_addrs_to_send.shrink_to_fit();
8521 }
8522}
8523
8524void PeerManagerImpl::MaybeSendSendHeaders(CNode &node, Peer &peer) {
8525 // Delay sending SENDHEADERS (BIP 130) until we're done with an
8526 // initial-headers-sync with this peer. Receiving headers announcements for
8527 // new blocks while trying to sync their headers chain is problematic,
8528 // because of the state tracking done.
8529 if (!peer.m_sent_sendheaders &&
8530 node.GetCommonVersion() >= SENDHEADERS_VERSION) {
8531 LOCK(cs_main);
8532 CNodeState &state = *State(node.GetId());
8533 if (state.pindexBestKnownBlock != nullptr &&
8534 state.pindexBestKnownBlock->nChainWork >
8535 m_chainman.MinimumChainWork()) {
8536 // Tell our peer we prefer to receive headers rather than inv's
8537 // We send this to non-NODE NETWORK peers as well, because even
8538 // non-NODE NETWORK peers can announce blocks (such as pruning
8539 // nodes)
8540 MakeAndPushMessage(node, NetMsgType::SENDHEADERS);
8541 peer.m_sent_sendheaders = true;
8542 }
8543 }
8544}
8545
8546void PeerManagerImpl::MaybeSendFeefilter(
8547 CNode &pto, Peer &peer, std::chrono::microseconds current_time) {
8548 if (m_opts.ignore_incoming_txs) {
8549 return;
8550 }
8551 if (pto.GetCommonVersion() < FEEFILTER_VERSION) {
8552 return;
8553 }
8554 // peers with the forcerelay permission should not filter txs to us
8556 return;
8557 }
8558 // Don't send feefilter messages to outbound block-relay-only peers since
8559 // they should never announce transactions to us, regardless of feefilter
8560 // state.
8561 if (pto.IsBlockOnlyConn()) {
8562 return;
8563 }
8564
8565 Amount currentFilter = m_mempool.GetMinFee().GetFeePerK();
8566
8567 if (m_chainman.IsInitialBlockDownload()) {
8568 // Received tx-inv messages are discarded when the active
8569 // chainstate is in IBD, so tell the peer to not send them.
8570 currentFilter = MAX_MONEY;
8571 } else {
8572 static const Amount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)};
8573 if (peer.m_fee_filter_sent == MAX_FILTER) {
8574 // Send the current filter if we sent MAX_FILTER previously
8575 // and made it out of IBD.
8576 peer.m_next_send_feefilter = 0us;
8577 }
8578 }
8579 if (current_time > peer.m_next_send_feefilter) {
8580 Amount filterToSend = m_fee_filter_rounder.round(currentFilter);
8581 // We always have a fee filter of at least the min relay fee
8582 filterToSend =
8583 std::max(filterToSend, m_mempool.m_min_relay_feerate.GetFeePerK());
8584 if (filterToSend != peer.m_fee_filter_sent) {
8585 MakeAndPushMessage(pto, NetMsgType::FEEFILTER, filterToSend);
8586 peer.m_fee_filter_sent = filterToSend;
8587 }
8588 peer.m_next_send_feefilter =
8589 current_time +
8590 m_rng.rand_exp_duration(AVG_FEEFILTER_BROADCAST_INTERVAL);
8591 }
8592 // If the fee filter has changed substantially and it's still more than
8593 // MAX_FEEFILTER_CHANGE_DELAY until scheduled broadcast, then move the
8594 // broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
8595 else if (current_time + MAX_FEEFILTER_CHANGE_DELAY <
8596 peer.m_next_send_feefilter &&
8597 (currentFilter < 3 * peer.m_fee_filter_sent / 4 ||
8598 currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
8599 peer.m_next_send_feefilter =
8600 current_time +
8601 FastRandomContext().randrange<std::chrono::microseconds>(
8603 }
8604}
8605
8606namespace {
8607class CompareInvMempoolOrder {
8608 CTxMemPool *mp;
8609
8610public:
8611 explicit CompareInvMempoolOrder(CTxMemPool *_mempool) : mp(_mempool) {}
8612
8613 bool operator()(std::set<TxId>::iterator a, std::set<TxId>::iterator b) {
8618 return mp->CompareTopologically(*b, *a);
8619 }
8620};
8621} // namespace
8622
8623bool PeerManagerImpl::RejectIncomingTxs(const CNode &peer) const {
8624 // block-relay-only peers may never send txs to us
8625 if (peer.IsBlockOnlyConn()) {
8626 return true;
8627 }
8628 if (peer.IsFeelerConn()) {
8629 return true;
8630 }
8631 // In -blocksonly mode, peers need the 'relay' permission to send txs to us
8632 if (m_opts.ignore_incoming_txs &&
8634 return true;
8635 }
8636 return false;
8637}
8638
8639bool PeerManagerImpl::SetupAddressRelay(const CNode &node, Peer &peer) {
8640 // We don't participate in addr relay with outbound block-relay-only
8641 // connections to prevent providing adversaries with the additional
8642 // information of addr traffic to infer the link.
8643 if (node.IsBlockOnlyConn()) {
8644 return false;
8645 }
8646
8647 if (!peer.m_addr_relay_enabled.exchange(true)) {
8648 // During version message processing (non-block-relay-only outbound
8649 // peers) or on first addr-related message we have received (inbound
8650 // peers), initialize m_addr_known.
8651 peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
8652 }
8653
8654 return true;
8655}
8656
8657bool PeerManagerImpl::SendMessages(const Config &config, CNode *pto) {
8658 AssertLockHeld(g_msgproc_mutex);
8659
8660 PeerRef peer = GetPeerRef(pto->GetId());
8661 if (!peer) {
8662 return false;
8663 }
8664 const Consensus::Params &consensusParams = m_chainparams.GetConsensus();
8665
8666 // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
8667 // disconnect misbehaving peers even before the version handshake is
8668 // complete.
8669 if (MaybeDiscourageAndDisconnect(*pto, *peer)) {
8670 return true;
8671 }
8672
8673 // Don't send anything until the version handshake is complete
8674 if (!pto->fSuccessfullyConnected || pto->fDisconnect) {
8675 return true;
8676 }
8677
8678 const auto current_time{GetTime<std::chrono::microseconds>()};
8679
8680 if (pto->IsAddrFetchConn() &&
8681 current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
8683 "addrfetch connection timeout; disconnecting peer=%d\n",
8684 pto->GetId());
8685 pto->fDisconnect = true;
8686 return true;
8687 }
8688
8689 MaybeSendPing(*pto, *peer, current_time);
8690
8691 // MaybeSendPing may have marked peer for disconnection
8692 if (pto->fDisconnect) {
8693 return true;
8694 }
8695
8696 bool sync_blocks_and_headers_from_peer = false;
8697
8698 MaybeSendAddr(*pto, *peer, current_time);
8699
8700 MaybeSendSendHeaders(*pto, *peer);
8701
8702 {
8703 LOCK(cs_main);
8704
8705 CNodeState &state = *State(pto->GetId());
8706
8707 // Start block sync
8708 if (m_chainman.m_best_header == nullptr) {
8709 m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
8710 }
8711
8712 // Determine whether we might try initial headers sync or parallel
8713 // block download from this peer -- this mostly affects behavior while
8714 // in IBD (once out of IBD, we sync from all peers).
8715 if (state.fPreferredDownload) {
8716 sync_blocks_and_headers_from_peer = true;
8717 } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) {
8718 // Typically this is an inbound peer. If we don't have any outbound
8719 // peers, or if we aren't downloading any blocks from such peers,
8720 // then allow block downloads from this peer, too.
8721 // We prefer downloading blocks from outbound peers to avoid
8722 // putting undue load on (say) some home user who is just making
8723 // outbound connections to the network, but if our only source of
8724 // the latest blocks is from an inbound peer, we have to be sure to
8725 // eventually download it (and not just wait indefinitely for an
8726 // outbound peer to have it).
8727 if (m_num_preferred_download_peers == 0 ||
8728 mapBlocksInFlight.empty()) {
8729 sync_blocks_and_headers_from_peer = true;
8730 }
8731 }
8732
8733 if (!state.fSyncStarted && CanServeBlocks(*peer) &&
8734 !m_chainman.m_blockman.LoadingBlocks()) {
8735 // Only actively request headers from a single peer, unless we're
8736 // close to today.
8737 if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) ||
8738 m_chainman.m_best_header->Time() > GetAdjustedTime() - 24h) {
8739 const CBlockIndex *pindexStart = m_chainman.m_best_header;
8748 if (pindexStart->pprev) {
8749 pindexStart = pindexStart->pprev;
8750 }
8751 if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) {
8752 LogPrint(
8753 BCLog::NET,
8754 "initial getheaders (%d) to peer=%d (startheight:%d)\n",
8755 pindexStart->nHeight, pto->GetId(),
8756 peer->m_starting_height);
8757
8758 state.fSyncStarted = true;
8759 peer->m_headers_sync_timeout =
8760 current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
8761 (
8762 // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to
8763 // microseconds before scaling to maintain precision
8764 std::chrono::microseconds{
8766 Ticks<std::chrono::seconds>(
8767 GetAdjustedTime() -
8768 m_chainman.m_best_header->Time()) /
8769 consensusParams.nPowTargetSpacing);
8770 nSyncStarted++;
8771 }
8772 }
8773 }
8774
8775 //
8776 // Try sending block announcements via headers
8777 //
8778 {
8779 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our list of block
8780 // hashes we're relaying, and our peer wants headers announcements,
8781 // then find the first header not yet known to our peer but would
8782 // connect, and send. If no header would connect, or if we have too
8783 // many blocks, or if the peer doesn't want headers, just add all to
8784 // the inv queue.
8785 LOCK(peer->m_block_inv_mutex);
8786 std::vector<CBlock> vHeaders;
8787 bool fRevertToInv =
8788 ((!peer->m_prefers_headers &&
8789 (!state.m_requested_hb_cmpctblocks ||
8790 peer->m_blocks_for_headers_relay.size() > 1)) ||
8791 peer->m_blocks_for_headers_relay.size() >
8793 // last header queued for delivery
8794 const CBlockIndex *pBestIndex = nullptr;
8795 // ensure pindexBestKnownBlock is up-to-date
8796 ProcessBlockAvailability(pto->GetId());
8797
8798 if (!fRevertToInv) {
8799 bool fFoundStartingHeader = false;
8800 // Try to find first header that our peer doesn't have, and then
8801 // send all headers past that one. If we come across an headers
8802 // that aren't on m_chainman.ActiveChain(), give up.
8803 for (const BlockHash &hash : peer->m_blocks_for_headers_relay) {
8804 const CBlockIndex *pindex =
8805 m_chainman.m_blockman.LookupBlockIndex(hash);
8806 assert(pindex);
8807 if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
8808 // Bail out if we reorged away from this block
8809 fRevertToInv = true;
8810 break;
8811 }
8812 if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
8813 // This means that the list of blocks to announce don't
8814 // connect to each other. This shouldn't really be
8815 // possible to hit during regular operation (because
8816 // reorgs should take us to a chain that has some block
8817 // not on the prior chain, which should be caught by the
8818 // prior check), but one way this could happen is by
8819 // using invalidateblock / reconsiderblock repeatedly on
8820 // the tip, causing it to be added multiple times to
8821 // m_blocks_for_headers_relay. Robustly deal with this
8822 // rare situation by reverting to an inv.
8823 fRevertToInv = true;
8824 break;
8825 }
8826 pBestIndex = pindex;
8827 if (fFoundStartingHeader) {
8828 // add this to the headers message
8829 vHeaders.push_back(pindex->GetBlockHeader());
8830 } else if (PeerHasHeader(&state, pindex)) {
8831 // Keep looking for the first new block.
8832 continue;
8833 } else if (pindex->pprev == nullptr ||
8834 PeerHasHeader(&state, pindex->pprev)) {
8835 // Peer doesn't have this header but they do have the
8836 // prior one. Start sending headers.
8837 fFoundStartingHeader = true;
8838 vHeaders.push_back(pindex->GetBlockHeader());
8839 } else {
8840 // Peer doesn't have this header or the prior one --
8841 // nothing will connect, so bail out.
8842 fRevertToInv = true;
8843 break;
8844 }
8845 }
8846 }
8847 if (!fRevertToInv && !vHeaders.empty()) {
8848 if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
8849 // We only send up to 1 block as header-and-ids, as
8850 // otherwise probably means we're doing an initial-ish-sync
8851 // or they're slow.
8853 "%s sending header-and-ids %s to peer=%d\n",
8854 __func__, vHeaders.front().GetHash().ToString(),
8855 pto->GetId());
8856
8857 std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
8858 {
8859 LOCK(m_most_recent_block_mutex);
8860 if (m_most_recent_block_hash ==
8861 pBestIndex->GetBlockHash()) {
8862 cached_cmpctblock_msg =
8864 *m_most_recent_compact_block);
8865 }
8866 }
8867 if (cached_cmpctblock_msg.has_value()) {
8868 PushMessage(*pto,
8869 std::move(cached_cmpctblock_msg.value()));
8870 } else {
8871 CBlock block;
8872 const bool ret{m_chainman.m_blockman.ReadBlock(
8873 block, *pBestIndex)};
8874 assert(ret);
8875 CBlockHeaderAndShortTxIDs cmpctblock(
8876 block, FastRandomContext().rand64());
8877 MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK,
8878 cmpctblock);
8879 }
8880 state.pindexBestHeaderSent = pBestIndex;
8881 } else if (peer->m_prefers_headers) {
8882 if (vHeaders.size() > 1) {
8884 "%s: %u headers, range (%s, %s), to peer=%d\n",
8885 __func__, vHeaders.size(),
8886 vHeaders.front().GetHash().ToString(),
8887 vHeaders.back().GetHash().ToString(),
8888 pto->GetId());
8889 } else {
8891 "%s: sending header %s to peer=%d\n", __func__,
8892 vHeaders.front().GetHash().ToString(),
8893 pto->GetId());
8894 }
8895 MakeAndPushMessage(*pto, NetMsgType::HEADERS, vHeaders);
8896 state.pindexBestHeaderSent = pBestIndex;
8897 } else {
8898 fRevertToInv = true;
8899 }
8900 }
8901 if (fRevertToInv) {
8902 // If falling back to using an inv, just try to inv the tip. The
8903 // last entry in m_blocks_for_headers_relay was our tip at some
8904 // point in the past.
8905 if (!peer->m_blocks_for_headers_relay.empty()) {
8906 const BlockHash &hashToAnnounce =
8907 peer->m_blocks_for_headers_relay.back();
8908 const CBlockIndex *pindex =
8909 m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
8910 assert(pindex);
8911
8912 // Warn if we're announcing a block that is not on the main
8913 // chain. This should be very rare and could be optimized
8914 // out. Just log for now.
8915 if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
8916 LogPrint(
8917 BCLog::NET,
8918 "Announcing block %s not on main chain (tip=%s)\n",
8919 hashToAnnounce.ToString(),
8920 m_chainman.ActiveChain()
8921 .Tip()
8922 ->GetBlockHash()
8923 .ToString());
8924 }
8925
8926 // If the peer's chain has this block, don't inv it back.
8927 if (!PeerHasHeader(&state, pindex)) {
8928 peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
8930 "%s: sending inv peer=%d hash=%s\n", __func__,
8931 pto->GetId(), hashToAnnounce.ToString());
8932 }
8933 }
8934 }
8935 peer->m_blocks_for_headers_relay.clear();
8936 }
8937 } // release cs_main
8938
8939 //
8940 // Message: inventory
8941 //
8942 std::vector<CInv> vInv;
8943 auto addInvAndMaybeFlush = [&](uint32_t type, const uint256 &hash) {
8944 vInv.emplace_back(type, hash);
8945 if (vInv.size() == MAX_INV_SZ) {
8946 MakeAndPushMessage(*pto, NetMsgType::INV, std::move(vInv));
8947 vInv.clear();
8948 }
8949 };
8950
8951 {
8952 LOCK(cs_main);
8953
8954 {
8955 LOCK(peer->m_block_inv_mutex);
8956
8957 vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(),
8959 config.GetMaxBlockSize() /
8960 1000000));
8961
8962 // Add blocks
8963 for (const BlockHash &hash : peer->m_blocks_for_inv_relay) {
8964 addInvAndMaybeFlush(MSG_BLOCK, hash);
8965 }
8966 peer->m_blocks_for_inv_relay.clear();
8967 }
8968
8969 auto computeNextInvSendTime =
8970 [&](std::chrono::microseconds &next)
8971 EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) -> bool {
8972 bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
8973
8974 if (next < current_time) {
8975 fSendTrickle = true;
8976 if (pto->IsInboundConn()) {
8977 next = NextInvToInbounds(
8979 } else {
8980 // Skip delay for outbound peers, as there is less privacy
8981 // concern for them.
8982 next = current_time;
8983 }
8984 }
8985
8986 return fSendTrickle;
8987 };
8988
8989 // Add proofs to inventory
8990 if (peer->m_proof_relay != nullptr) {
8991 LOCK(peer->m_proof_relay->m_proof_inventory_mutex);
8992
8993 if (computeNextInvSendTime(
8994 peer->m_proof_relay->m_next_inv_send_time)) {
8995 auto it =
8996 peer->m_proof_relay->m_proof_inventory_to_send.begin();
8997 while (it !=
8998 peer->m_proof_relay->m_proof_inventory_to_send.end()) {
8999 const avalanche::ProofId proofid = *it;
9000
9001 it = peer->m_proof_relay->m_proof_inventory_to_send.erase(
9002 it);
9003
9004 if (peer->m_proof_relay->m_proof_inventory_known_filter
9005 .contains(proofid)) {
9006 continue;
9007 }
9008
9009 peer->m_proof_relay->m_proof_inventory_known_filter.insert(
9010 proofid);
9011 addInvAndMaybeFlush(MSG_AVA_PROOF, proofid);
9012 peer->m_proof_relay->m_recently_announced_proofs.insert(
9013 proofid);
9014 }
9015 }
9016 }
9017
9018 if (auto tx_relay = peer->GetTxRelay()) {
9019 LOCK(tx_relay->m_tx_inventory_mutex);
9020 // Check whether periodic sends should happen
9021 const bool fSendTrickle =
9022 computeNextInvSendTime(tx_relay->m_next_inv_send_time);
9023
9024 // Time to send but the peer has requested we not relay
9025 // transactions.
9026 if (fSendTrickle) {
9027 LOCK(tx_relay->m_bloom_filter_mutex);
9028 if (!tx_relay->m_relay_txs) {
9029 tx_relay->m_tx_inventory_to_send.clear();
9030 }
9031 }
9032
9033 // Respond to BIP35 mempool requests
9034 if (fSendTrickle && tx_relay->m_send_mempool) {
9035 auto vtxinfo = m_mempool.infoAll();
9036 tx_relay->m_send_mempool = false;
9037 const CFeeRate filterrate{
9038 tx_relay->m_fee_filter_received.load()};
9039
9040 LOCK(tx_relay->m_bloom_filter_mutex);
9041
9042 for (const auto &txinfo : vtxinfo) {
9043 const TxId &txid = txinfo.tx->GetId();
9044 tx_relay->m_tx_inventory_to_send.erase(txid);
9045 // Don't send transactions that peers will not put into
9046 // their mempool
9047 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
9048 continue;
9049 }
9050 if (tx_relay->m_bloom_filter &&
9051 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
9052 *txinfo.tx)) {
9053 continue;
9054 }
9055 tx_relay->m_tx_inventory_known_filter.insert(txid);
9056 // Responses to MEMPOOL requests bypass the
9057 // m_recently_announced_invs filter.
9058 addInvAndMaybeFlush(MSG_TX, txid);
9059 }
9060 tx_relay->m_last_mempool_req =
9061 std::chrono::duration_cast<std::chrono::seconds>(
9062 current_time);
9063 }
9064
9065 // Determine transactions to relay
9066 if (fSendTrickle) {
9067 // Produce a vector with all candidates for sending
9068 std::vector<std::set<TxId>::iterator> vInvTx;
9069 vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
9070 for (std::set<TxId>::iterator it =
9071 tx_relay->m_tx_inventory_to_send.begin();
9072 it != tx_relay->m_tx_inventory_to_send.end(); it++) {
9073 vInvTx.push_back(it);
9074 }
9075 const CFeeRate filterrate{
9076 tx_relay->m_fee_filter_received.load()};
9077 // Send out the inventory in the order of admission to our
9078 // mempool, which is guaranteed to be a topological sort order.
9079 // A heap is used so that not all items need sorting if only a
9080 // few are being sent.
9081 CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool);
9082 std::make_heap(vInvTx.begin(), vInvTx.end(),
9083 compareInvMempoolOrder);
9084 // No reason to drain out at many times the network's
9085 // capacity, especially since we have many peers and some
9086 // will draw much shorter delays.
9087 unsigned int nRelayedTransactions = 0;
9088 LOCK(tx_relay->m_bloom_filter_mutex);
9089 while (!vInvTx.empty() &&
9090 nRelayedTransactions < INVENTORY_BROADCAST_MAX_PER_MB *
9091 config.GetMaxBlockSize() /
9092 1000000) {
9093 // Fetch the top element from the heap
9094 std::pop_heap(vInvTx.begin(), vInvTx.end(),
9095 compareInvMempoolOrder);
9096 std::set<TxId>::iterator it = vInvTx.back();
9097 vInvTx.pop_back();
9098 const TxId txid = *it;
9099 // Remove it from the to-be-sent set
9100 tx_relay->m_tx_inventory_to_send.erase(it);
9101 // Check if not in the filter already
9102 if (tx_relay->m_tx_inventory_known_filter.contains(txid) &&
9103 tx_relay->m_avalanche_stalled_txids.count(txid) == 0) {
9104 continue;
9105 }
9106 // Not in the mempool anymore? don't bother sending it.
9107 auto txinfo = m_mempool.info(txid);
9108 if (!txinfo.tx) {
9109 continue;
9110 }
9111 // Peer told you to not send transactions at that
9112 // feerate? Don't bother sending it.
9113 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
9114 continue;
9115 }
9116 if (tx_relay->m_bloom_filter &&
9117 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
9118 *txinfo.tx)) {
9119 continue;
9120 }
9121 // Send
9122 tx_relay->m_recently_announced_invs.insert(txid);
9123 addInvAndMaybeFlush(MSG_TX, txid);
9124 nRelayedTransactions++;
9125 tx_relay->m_tx_inventory_known_filter.insert(txid);
9126 tx_relay->m_avalanche_stalled_txids.erase(txid);
9127 }
9128 }
9129 }
9130 } // release cs_main
9131
9132 if (!vInv.empty()) {
9133 MakeAndPushMessage(*pto, NetMsgType::INV, vInv);
9134 }
9135
9136 {
9137 LOCK(cs_main);
9138
9139 CNodeState &state = *State(pto->GetId());
9140
9141 // Detect whether we're stalling
9142 auto stalling_timeout = m_block_stalling_timeout.load();
9143 if (state.m_stalling_since.count() &&
9144 state.m_stalling_since < current_time - stalling_timeout) {
9145 // Stalling only triggers when the block download window cannot
9146 // move. During normal steady state, the download window should be
9147 // much larger than the to-be-downloaded set of blocks, so
9148 // disconnection should only happen during initial block download.
9149 LogPrintf("Peer=%d is stalling block download, disconnecting\n",
9150 pto->GetId());
9151 pto->fDisconnect = true;
9152 // Increase timeout for the next peer so that we don't disconnect
9153 // multiple peers if our own bandwidth is insufficient.
9154 const auto new_timeout =
9155 std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX);
9156 if (stalling_timeout != new_timeout &&
9157 m_block_stalling_timeout.compare_exchange_strong(
9158 stalling_timeout, new_timeout)) {
9159 LogPrint(
9160 BCLog::NET,
9161 "Increased stalling timeout temporarily to %d seconds\n",
9162 count_seconds(new_timeout));
9163 }
9164 return true;
9165 }
9166 // In case there is a block that has been in flight from this peer for
9167 // block_interval * (1 + 0.5 * N) (with N the number of peers from which
9168 // we're downloading validated blocks), disconnect due to timeout.
9169 // We compensate for other peers to prevent killing off peers due to our
9170 // own downstream link being saturated. We only count validated
9171 // in-flight blocks so peers can't advertise non-existing block hashes
9172 // to unreasonably increase our timeout.
9173 if (state.vBlocksInFlight.size() > 0) {
9174 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
9175 int nOtherPeersWithValidatedDownloads =
9176 m_peers_downloading_from - 1;
9177 if (current_time >
9178 state.m_downloading_since +
9179 std::chrono::seconds{consensusParams.nPowTargetSpacing} *
9182 nOtherPeersWithValidatedDownloads)) {
9183 LogPrintf("Timeout downloading block %s from peer=%d, "
9184 "disconnecting\n",
9185 queuedBlock.pindex->GetBlockHash().ToString(),
9186 pto->GetId());
9187 pto->fDisconnect = true;
9188 return true;
9189 }
9190 }
9191
9192 // Check for headers sync timeouts
9193 if (state.fSyncStarted &&
9194 peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
9195 // Detect whether this is a stalling initial-headers-sync peer
9196 if (m_chainman.m_best_header->Time() <= GetAdjustedTime() - 24h) {
9197 if (current_time > peer->m_headers_sync_timeout &&
9198 nSyncStarted == 1 &&
9199 (m_num_preferred_download_peers -
9200 state.fPreferredDownload >=
9201 1)) {
9202 // Disconnect a peer (without NetPermissionFlags::NoBan
9203 // permission) if it is our only sync peer, and we have
9204 // others we could be using instead. Note: If all our peers
9205 // are inbound, then we won't disconnect our sync peer for
9206 // stalling; we have bigger problems if we can't get any
9207 // outbound peers.
9209 LogPrintf("Timeout downloading headers from peer=%d, "
9210 "disconnecting\n",
9211 pto->GetId());
9212 pto->fDisconnect = true;
9213 return true;
9214 } else {
9215 LogPrintf("Timeout downloading headers from noban "
9216 "peer=%d, not disconnecting\n",
9217 pto->GetId());
9218 // Reset the headers sync state so that we have a chance
9219 // to try downloading from a different peer. Note: this
9220 // will also result in at least one more getheaders
9221 // message to be sent to this peer (eventually).
9222 state.fSyncStarted = false;
9223 nSyncStarted--;
9224 peer->m_headers_sync_timeout = 0us;
9225 }
9226 }
9227 } else {
9228 // After we've caught up once, reset the timeout so we can't
9229 // trigger disconnect later.
9230 peer->m_headers_sync_timeout = std::chrono::microseconds::max();
9231 }
9232 }
9233
9234 // Check that outbound peers have reasonable chains GetTime() is used by
9235 // this anti-DoS logic so we can test this using mocktime.
9236 ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
9237 } // release cs_main
9238
9239 std::vector<CInv> vGetData;
9240
9241 //
9242 // Message: getdata (blocks)
9243 //
9244 {
9245 LOCK(cs_main);
9246
9247 CNodeState &state = *State(pto->GetId());
9248
9249 if (CanServeBlocks(*peer) &&
9250 ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) ||
9251 !m_chainman.IsInitialBlockDownload()) &&
9252 state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
9253 std::vector<const CBlockIndex *> vToDownload;
9254 NodeId staller = -1;
9255 auto get_inflight_budget = [&state]() {
9256 return std::max(
9258 static_cast<int>(state.vBlocksInFlight.size()));
9259 };
9260
9261 // If a snapshot chainstate is in use, we want to find its next
9262 // blocks before the background chainstate to prioritize getting to
9263 // network tip.
9264 FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload,
9265 staller);
9266 if (m_chainman.BackgroundSyncInProgress() &&
9267 !IsLimitedPeer(*peer)) {
9268 // If the background tip is not an ancestor of the snapshot
9269 // block, we need to start requesting blocks from their last
9270 // common ancestor.
9271 const CBlockIndex *from_tip =
9273 m_chainman.GetSnapshotBaseBlock());
9274
9275 TryDownloadingHistoricalBlocks(
9276 *peer, get_inflight_budget(), vToDownload, from_tip,
9277 Assert(m_chainman.GetSnapshotBaseBlock()));
9278 }
9279 for (const CBlockIndex *pindex : vToDownload) {
9280 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
9281 BlockRequested(config, pto->GetId(), *pindex);
9282 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n",
9283 pindex->GetBlockHash().ToString(), pindex->nHeight,
9284 pto->GetId());
9285 }
9286 if (state.vBlocksInFlight.empty() && staller != -1) {
9287 if (State(staller)->m_stalling_since == 0us) {
9288 State(staller)->m_stalling_since = current_time;
9289 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
9290 }
9291 }
9292 }
9293 } // release cs_main
9294
9295 auto addGetDataAndMaybeFlush = [&](uint32_t type, const uint256 &hash) {
9296 CInv inv(type, hash);
9297 LogPrint(BCLog::NET, "Requesting %s from peer=%d\n", inv.ToString(),
9298 pto->GetId());
9299 vGetData.push_back(std::move(inv));
9300 if (vGetData.size() >= MAX_GETDATA_SZ) {
9301 MakeAndPushMessage(*pto, NetMsgType::GETDATA, std::move(vGetData));
9302 vGetData.clear();
9303 }
9304 };
9305
9306 //
9307 // Message: getdata (proof)
9308 //
9309 if (m_avalanche) {
9310 LOCK(cs_proofrequest);
9311 std::vector<std::pair<NodeId, avalanche::ProofId>> expired;
9312 auto requestable =
9313 m_proofrequest.GetRequestable(pto->GetId(), current_time, &expired);
9314 for (const auto &entry : expired) {
9316 "timeout of inflight proof %s from peer=%d\n",
9317 entry.second.ToString(), entry.first);
9318 }
9319 for (const auto &proofid : requestable) {
9320 if (!AlreadyHaveProof(proofid)) {
9321 addGetDataAndMaybeFlush(MSG_AVA_PROOF, proofid);
9322 m_proofrequest.RequestedData(
9323 pto->GetId(), proofid,
9324 current_time + PROOF_REQUEST_PARAMS.getdata_interval);
9325 } else {
9326 // We have already seen this proof, no need to download.
9327 // This is just a belt-and-suspenders, as this should
9328 // already be called whenever a proof becomes
9329 // AlreadyHaveProof().
9330 m_proofrequest.ForgetInvId(proofid);
9331 }
9332 }
9333 }
9334
9335 //
9336 // Message: getdata (transactions)
9337 //
9338 {
9339 LOCK(cs_main);
9340 std::vector<std::pair<NodeId, TxId>> expired;
9341 auto requestable =
9342 m_txrequest.GetRequestable(pto->GetId(), current_time, &expired);
9343 for (const auto &entry : expired) {
9344 LogPrint(BCLog::NET, "timeout of inflight tx %s from peer=%d\n",
9345 entry.second.ToString(), entry.first);
9346 }
9347 for (const TxId &txid : requestable) {
9348 // Exclude m_recent_rejects_package_reconsiderable: we may be
9349 // requesting a missing parent that was previously rejected for
9350 // being too low feerate.
9351 if (!AlreadyHaveTx(txid, /*include_reconsiderable=*/false)) {
9352 addGetDataAndMaybeFlush(MSG_TX, txid);
9353 m_txrequest.RequestedData(
9354 pto->GetId(), txid,
9355 current_time + TX_REQUEST_PARAMS.getdata_interval);
9356 } else {
9357 // We have already seen this transaction, no need to download.
9358 // This is just a belt-and-suspenders, as this should already be
9359 // called whenever a transaction becomes AlreadyHaveTx().
9360 m_txrequest.ForgetInvId(txid);
9361 }
9362 }
9363
9364 if (!vGetData.empty()) {
9365 MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData);
9366 }
9367
9368 } // release cs_main
9369 MaybeSendFeefilter(*pto, *peer, current_time);
9370 return true;
9371}
9372
9373bool PeerManagerImpl::ReceivedAvalancheProof(CNode &node, Peer &peer,
9374 const avalanche::ProofRef &proof) {
9375 if (!proof) {
9376 LogError("ReceivedAvalancheProof: proof is null\n");
9377 return false;
9378 }
9379
9380 const avalanche::ProofId &proofid = proof->getId();
9381
9382 AddKnownProof(peer, proofid);
9383
9384 if (m_chainman.IsInitialBlockDownload()) {
9385 // We cannot reliably verify proofs during IBD, so bail out early and
9386 // keep the inventory as pending so it can be requested when the node
9387 // has synced.
9388 return true;
9389 }
9390
9391 const NodeId nodeid = node.GetId();
9392
9393 const bool isStaker = WITH_LOCK(node.cs_avalanche_pubkey,
9394 return node.m_avalanche_pubkey.has_value());
9395 auto saveProofIfStaker = [this, isStaker](const CNode &node,
9396 const avalanche::ProofId &proofid,
9397 const NodeId nodeid) -> bool {
9398 if (isStaker) {
9399 return m_avalanche->withPeerManager(
9400 [&](avalanche::PeerManager &pm) {
9401 return pm.saveRemoteProof(proofid, nodeid, true);
9402 });
9403 }
9404
9405 return false;
9406 };
9407
9408 {
9409 LOCK(cs_proofrequest);
9410 m_proofrequest.ReceivedResponse(nodeid, proofid);
9411
9412 if (AlreadyHaveProof(proofid)) {
9413 m_proofrequest.ForgetInvId(proofid);
9414 saveProofIfStaker(node, proofid, nodeid);
9415 return true;
9416 }
9417 }
9418
9419 // registerProof should not be called while cs_proofrequest because it
9420 // holds cs_main and that creates a potential deadlock during shutdown
9421
9423 if (m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
9424 return pm.registerProof(proof, state);
9425 })) {
9426 WITH_LOCK(cs_proofrequest, m_proofrequest.ForgetInvId(proofid));
9427 RelayProof(proofid);
9428
9429 node.m_last_proof_time = GetTime<std::chrono::seconds>();
9430
9431 LogPrint(BCLog::NET, "New avalanche proof: peer=%d, proofid %s\n",
9432 nodeid, proofid.ToString());
9433 }
9434
9436 m_avalanche->withPeerManager(
9437 [&](avalanche::PeerManager &pm) { pm.setInvalid(proofid); });
9438 Misbehaving(peer, state.GetRejectReason());
9439 return false;
9440 }
9441
9443 // This is possible that a proof contains a utxo we don't know yet, so
9444 // don't ban for this.
9445 return false;
9446 }
9447
9448 // Unlike other reasons we can expect lots of peers to send a proof that we
9449 // have dangling. In this case we don't want to print a lot of useless debug
9450 // message, the proof will be polled as soon as it's considered again.
9451 if (!m_avalanche->reconcileOrFinalize(proof) &&
9454 "Not polling the avalanche proof (%s): peer=%d, proofid %s\n",
9455 state.IsValid() ? "not-worth-polling"
9456 : state.GetRejectReason(),
9457 nodeid, proofid.ToString());
9458 }
9459
9460 saveProofIfStaker(node, proofid, nodeid);
9461 return true;
9462}
bool MoneyRange(const Amount nValue)
Definition: amount.h:177
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:176
@ READ_STATUS_OK
@ READ_STATUS_INVALID
@ READ_STATUS_FAILED
enum ReadStatus_t ReadStatus
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
BlockFilterType
Definition: blockfilter.h:88
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
@ CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:74
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:41
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:89
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:112
#define Assert(val)
Identity function.
Definition: check.h:87
#define Assume(val)
Assume is the identity function.
Definition: check.h:100
Stochastic address manager.
Definition: addrman.h:68
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
Definition: addrman.cpp:1322
void Good(const CService &addr, bool test_before_evict=true, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as accessible, possibly moving it from "new" to "tried".
Definition: addrman.cpp:1295
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
Definition: addrman.cpp:1290
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Definition: addrman.cpp:1326
Definition: banman.h:59
void Discourage(const CNetAddr &net_addr)
Definition: banman.cpp:116
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
Definition: banman.cpp:83
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
Definition: banman.cpp:78
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
bool LookupFilterHashRange(int start_height, const CBlockIndex *stop_index, std::vector< uint256 > &hashes_out) const
Get a range of filter hashes between two heights on a chain.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
std::vector< CTransactionRef > txn
std::vector< uint32_t > indices
A CService with information about it as peer.
Definition: protocol.h:442
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:554
static constexpr SerParams V1_NETWORK
Definition: protocol.h:495
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition: protocol.h:552
static constexpr SerParams V2_NETWORK
Definition: protocol.h:497
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
uint32_t nTime
Definition: block.h:29
BlockHash hashPrevBlock
Definition: block.h:27
Definition: block.h:60
std::string ToString() const
Definition: block.cpp:15
std::vector< CTransactionRef > vtx
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:191
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
CBlockHeader GetBlockHeader() const
Definition: blockindex.h:117
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
Definition: blockindex.h:154
int64_t GetBlockTime() const
Definition: blockindex.h:160
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:55
NodeSeconds Time() const
Definition: blockindex.h:156
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:62
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:97
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:44
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
Definition: bloom.cpp:93
An in-memory indexed chain of blocks.
Definition: chain.h:138
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:154
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:178
int Height() const
Return the maximal height in the chain.
Definition: chain.h:190
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:170
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
const CBlock & GenesisBlock() const
Definition: chainparams.h:112
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:98
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:358
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h: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:303
void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:828
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:272
bool CompareTopologically(const TxId &txida, const TxId &txidb) const
Definition: txmempool.cpp:506
TxMempoolInfo info(const TxId &txid) const
Definition: txmempool.cpp:689
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:817
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:538
CTransactionRef GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
Definition: txmempool.cpp:742
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:331
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:747
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:1170
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:1424
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1444
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:1305
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1431
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1438
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:1276
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1425
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:1314
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:1561
int64_t getAvaproofsNodeCounter() const
Definition: processor.h:358
bool sendHello(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Send a avahello message.
Definition: processor.cpp:751
void setRecentlyFinalized(const uint256 &itemId) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:521
size_t getMaxElementPoll() const
Definition: processor.h:422
bool isQuorumEstablished() LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:838
void cleanupStakingRewards(const int minHeight) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
Definition: processor.cpp:983
ProofRef getLocalProof() const
Definition: processor.cpp:773
void acceptStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1101
bool reconcileOrFinalize(const ProofRef &proof) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Wrapper around the addToReconcile for proofs that adds back the finalization flag to the peer if it i...
Definition: processor.cpp:460
int getStakeContenderStatus(const StakeContenderId &contenderId) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Track votes on stake contenders.
Definition: processor.cpp:1078
void sendDelayedAvahello() EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Definition: processor.cpp:756
void finalizeStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1106
bool isPreconsensusActivated(const CBlockIndex *pprev) const
Definition: processor.cpp:1557
auto withPeerManager(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.h:320
bool registerVotes(NodeId nodeid, const Response &response, std::vector< VoteItemUpdate > &updates, bool &disconnect, std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:565
void rejectStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1128
void avaproofsSent(NodeId nodeid) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:817
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:23
static constexpr Amount zero() noexcept
Definition: amount.h:36
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:108
std::vector< BlockHash > vHave
Definition: block.h:120
bool IsNull() const
Definition: block.h:135
std::chrono::microseconds m_ping_wait
Amount m_fee_filter_received
std::vector< int > vHeightInFlight
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
int64_t presync_height
ServiceFlags their_services
Parameters that influence chain consensus.
Definition: params.h:34
int64_t nPowTargetSpacing
Definition: params.h:85
std::chrono::seconds PowTargetSpacing() const
Definition: params.h:87
const std::chrono::seconds overloaded_peer_delay
How long to delay requesting data from overloaded peers (see max_peer_request_in_flight).
const size_t max_peer_announcements
Maximum number of inventories to consider for requesting, per peer.
const std::chrono::seconds nonpref_peer_delay
How long to delay requesting data from non-preferred peers.
const NetPermissionFlags bypass_request_limits_permissions
Permission flags a peer requires to bypass the request limits tracking limits and delay penalty.
const std::chrono::microseconds getdata_interval
How long to wait (in microseconds) before a data request from an additional peer.
const size_t max_peer_request_in_flight
Maximum number of in-flight data requests from a peer.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:194
const ResultType m_result_type
Result type.
Definition: validation.h:205
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:208
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:29
std::chrono::time_point< NodeClock > time_point
Definition: time.h:21
Validation result for package mempool acceptance.
Definition: validation.h:297
PackageValidationState m_state
Definition: validation.h:298
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:306
This is a radix tree storing values identified by a unique key.
Definition: radix.h:39
A TxId is the identifier of a transaction.
Definition: txid.h:14
std::chrono::seconds registration_time
Definition: peermanager.h:93
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:91
CMainSignals & GetMainSignals()