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