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