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