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