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