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 if (!Assume(m_avalanche)) {
3057 return false;
3058 }
3059
3060 auto localProof = m_avalanche->getLocalProof();
3061 if (localProof && localProof->getId() == proofid) {
3062 return true;
3063 }
3064
3065 return m_avalanche->withPeerManager([&proofid](avalanche::PeerManager &pm) {
3066 return pm.exists(proofid) || pm.isInvalid(proofid);
3067 });
3068}
3069
3070void PeerManagerImpl::SendPings() {
3071 LOCK(m_peer_mutex);
3072 for (auto &it : m_peer_map) {
3073 it.second->m_ping_queued = true;
3074 }
3075}
3076
3077void PeerManagerImpl::RelayTransaction(const TxId &txid) {
3078 LOCK(m_peer_mutex);
3079 for (auto &it : m_peer_map) {
3080 Peer &peer = *it.second;
3081 auto tx_relay = peer.GetTxRelay();
3082 if (!tx_relay) {
3083 continue;
3084 }
3085 LOCK(tx_relay->m_tx_inventory_mutex);
3086 // Only queue transactions for announcement once the version handshake
3087 // is completed. The time of arrival for these transactions is
3088 // otherwise at risk of leaking to a spy, if the spy is able to
3089 // distinguish transactions received during the handshake from the rest
3090 // in the announcement.
3091 if (tx_relay->m_next_inv_send_time == 0s) {
3092 continue;
3093 }
3094
3095 if (!tx_relay->m_tx_inventory_known_filter.contains(txid)) {
3096 tx_relay->m_tx_inventory_to_send.insert(txid);
3097 }
3098 }
3099}
3100
3101void PeerManagerImpl::RelayProof(const avalanche::ProofId &proofid) {
3102 LOCK(m_peer_mutex);
3103 for (auto &it : m_peer_map) {
3104 Peer &peer = *it.second;
3105
3106 if (!peer.m_proof_relay) {
3107 continue;
3108 }
3109 LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
3110 if (!peer.m_proof_relay->m_proof_inventory_known_filter.contains(
3111 proofid)) {
3112 peer.m_proof_relay->m_proof_inventory_to_send.insert(proofid);
3113 }
3114 }
3115}
3116
3117void PeerManagerImpl::RelayAddress(NodeId originator, const CAddress &addr,
3118 bool fReachable) {
3119 // We choose the same nodes within a given 24h window (if the list of
3120 // connected nodes does not change) and we don't relay to nodes that already
3121 // know an address. So within 24h we will likely relay a given address once.
3122 // This is to prevent a peer from unjustly giving their address better
3123 // propagation by sending it to us repeatedly.
3124
3125 if (!fReachable && !addr.IsRelayable()) {
3126 return;
3127 }
3128
3129 // Relay to a limited number of other nodes
3130 // Use deterministic randomness to send to the same nodes for 24 hours
3131 // at a time so the m_addr_knowns of the chosen nodes prevent repeats
3132 const uint64_t hash_addr{CServiceHash(0, 0)(addr)};
3134 // Adding address hash makes exact rotation time different per address,
3135 // while preserving periodicity.
3136 const uint64_t time_addr{
3137 (static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) /
3139
3140 const CSipHasher hasher{
3143 .Write(time_addr)};
3144
3145 // Relay reachable addresses to 2 peers. Unreachable addresses are relayed
3146 // randomly to 1 or 2 peers.
3147 unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
3148 std::array<std::pair<uint64_t, Peer *>, 2> best{
3149 {{0, nullptr}, {0, nullptr}}};
3150 assert(nRelayNodes <= best.size());
3151
3152 LOCK(m_peer_mutex);
3153
3154 for (auto &[id, peer] : m_peer_map) {
3155 if (peer->m_addr_relay_enabled && id != originator &&
3156 IsAddrCompatible(*peer, addr)) {
3157 uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
3158 for (unsigned int i = 0; i < nRelayNodes; i++) {
3159 if (hashKey > best[i].first) {
3160 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1,
3161 best.begin() + i + 1);
3162 best[i] = std::make_pair(hashKey, peer.get());
3163 break;
3164 }
3165 }
3166 }
3167 };
3168
3169 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
3170 PushAddress(*best[i].second, addr);
3171 }
3172}
3173
3174void PeerManagerImpl::ProcessGetBlockData(const Config &config, CNode &pfrom,
3175 Peer &peer, const CInv &inv) {
3176 const BlockHash hash(inv.hash);
3177
3178 std::shared_ptr<const CBlock> a_recent_block;
3179 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
3180 {
3181 LOCK(m_most_recent_block_mutex);
3184 }
3185
3186 bool need_activate_chain = false;
3187 {
3188 LOCK(cs_main);
3189 const CBlockIndex *pindex =
3190 m_chainman.m_blockman.LookupBlockIndex(hash);
3191 if (pindex) {
3192 if (pindex->HaveTxsDownloaded() &&
3193 !pindex->IsValid(BlockValidity::SCRIPTS) &&
3194 pindex->IsValid(BlockValidity::TREE)) {
3195 // If we have the block and all of its parents, but have not yet
3196 // validated it, we might be in the middle of connecting it (ie
3197 // in the unlock of cs_main before ActivateBestChain but after
3198 // AcceptBlock). In this case, we need to run ActivateBestChain
3199 // prior to checking the relay conditions below.
3200 need_activate_chain = true;
3201 }
3202 }
3203 } // release cs_main before calling ActivateBestChain
3204 if (need_activate_chain) {
3206 if (!m_chainman.ActiveChainstate().ActivateBestChain(
3207 state, a_recent_block, m_avalanche)) {
3208 LogPrint(BCLog::NET, "failed to activate chain (%s)\n",
3209 state.ToString());
3210 }
3211 }
3212
3213 LOCK(cs_main);
3214 const CBlockIndex *pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
3215 if (!pindex) {
3216 return;
3217 }
3218 if (!BlockRequestAllowed(pindex)) {
3220 "%s: ignoring request from peer=%i for old "
3221 "block that isn't in the main chain\n",
3222 __func__, pfrom.GetId());
3223 return;
3224 }
3225 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3226 // Disconnect node in case we have reached the outbound limit for serving
3227 // historical blocks.
3228 if (m_connman.OutboundTargetReached(true) &&
3229 (((m_chainman.m_best_header != nullptr) &&
3230 (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() >
3232 inv.IsMsgFilteredBlk()) &&
3233 // nodes with the download permission may exceed target
3234 !pfrom.HasPermission(NetPermissionFlags::Download)) {
3236 "historical block serving limit reached, disconnect peer=%d\n",
3237 pfrom.GetId());
3238 pfrom.fDisconnect = true;
3239 return;
3240 }
3241 // Avoid leaking prune-height by never sending blocks below the
3242 // NODE_NETWORK_LIMITED threshold.
3243 // Add two blocks buffer extension for possible races
3244 if (!pfrom.HasPermission(NetPermissionFlags::NoBan) &&
3245 ((((peer.m_our_services & NODE_NETWORK_LIMITED) ==
3247 ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) &&
3248 (m_chainman.ActiveChain().Tip()->nHeight - pindex->nHeight >
3249 (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2)))) {
3251 "Ignore block request below NODE_NETWORK_LIMITED "
3252 "threshold, disconnect peer=%d\n",
3253 pfrom.GetId());
3254
3255 // disconnect node and prevent it from stalling (would otherwise wait
3256 // for the missing block)
3257 pfrom.fDisconnect = true;
3258 return;
3259 }
3260 // Pruned nodes may have deleted the block, so check whether it's available
3261 // before trying to send.
3262 if (!pindex->nStatus.hasData()) {
3263 return;
3264 }
3265 std::shared_ptr<const CBlock> pblock;
3266 if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
3268 } else {
3269 // Send block from disk
3270 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
3271 if (!m_chainman.m_blockman.ReadBlockFromDisk(*pblockRead, *pindex)) {
3272 assert(!"cannot load block from disk");
3273 }
3275 }
3276 if (inv.IsMsgBlk()) {
3277 m_connman.PushMessage(&pfrom,
3279 } else if (inv.IsMsgFilteredBlk()) {
3280 bool sendMerkleBlock = false;
3282 if (auto tx_relay = peer.GetTxRelay()) {
3283 LOCK(tx_relay->m_bloom_filter_mutex);
3284 if (tx_relay->m_bloom_filter) {
3285 sendMerkleBlock = true;
3286 merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
3287 }
3288 }
3289 if (sendMerkleBlock) {
3290 m_connman.PushMessage(
3292 // CMerkleBlock just contains hashes, so also push any
3293 // transactions in the block the client did not see. This avoids
3294 // hurting performance by pointlessly requiring a round-trip.
3295 // Note that there is currently no way for a node to request any
3296 // single transactions we didn't send here - they must either
3297 // disconnect and retry or request the full block. Thus, the
3298 // protocol spec specified allows for us to provide duplicate
3299 // txn here, however we MUST always provide at least what the
3300 // remote peer needs.
3301 typedef std::pair<size_t, uint256> PairType;
3302 for (PairType &pair : merkleBlock.vMatchedTxn) {
3303 m_connman.PushMessage(
3304 &pfrom,
3305 msgMaker.Make(NetMsgType::TX, *pblock->vtx[pair.first]));
3306 }
3307 }
3308 // else
3309 // no response
3310 } else if (inv.IsMsgCmpctBlk()) {
3311 // If a peer is asking for old blocks, we're almost guaranteed they
3312 // won't have a useful mempool to match against a compact block, and
3313 // we don't feel like constructing the object for them, so instead
3314 // we respond with the full, non-compact block.
3315 int nSendFlags = 0;
3316 if (CanDirectFetch() &&
3317 pindex->nHeight >=
3318 m_chainman.ActiveChain().Height() - MAX_CMPCTBLOCK_DEPTH) {
3320 a_recent_compact_block->header.GetHash() ==
3321 pindex->GetBlockHash()) {
3322 m_connman.PushMessage(&pfrom,
3325 } else {
3327 m_connman.PushMessage(
3329 cmpctblock));
3330 }
3331 } else {
3332 m_connman.PushMessage(
3334 }
3335 }
3336
3337 {
3338 LOCK(peer.m_block_inv_mutex);
3339 // Trigger the peer node to send a getblocks request for the next
3340 // batch of inventory.
3341 if (hash == peer.m_continuation_block) {
3342 // Send immediately. This must send even if redundant, and
3343 // we want it right after the last block so they don't wait for
3344 // other stuff first.
3345 std::vector<CInv> vInv;
3346 vInv.push_back(CInv(
3347 MSG_BLOCK, m_chainman.ActiveChain().Tip()->GetBlockHash()));
3348 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::INV, vInv));
3349 peer.m_continuation_block = BlockHash();
3350 }
3351 }
3352}
3353
3355PeerManagerImpl::FindTxForGetData(const Peer &peer, const TxId &txid,
3356 const std::chrono::seconds mempool_req,
3357 const std::chrono::seconds now) {
3358 auto txinfo = m_mempool.info(txid);
3359 if (txinfo.tx) {
3360 // If a TX could have been INVed in reply to a MEMPOOL request,
3361 // or is older than UNCONDITIONAL_RELAY_DELAY, permit the request
3362 // unconditionally.
3363 if ((mempool_req.count() && txinfo.m_time <= mempool_req) ||
3364 txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
3365 return std::move(txinfo.tx);
3366 }
3367 }
3368
3369 {
3370 LOCK(cs_main);
3371
3372 // Otherwise, the transaction must have been announced recently.
3373 if (Assume(peer.GetTxRelay())
3374 ->m_recently_announced_invs.contains(txid)) {
3375 // If it was, it can be relayed from either the mempool...
3376 if (txinfo.tx) {
3377 return std::move(txinfo.tx);
3378 }
3379 // ... or the relay pool.
3380 auto mi = mapRelay.find(txid);
3381 if (mi != mapRelay.end()) {
3382 return mi->second;
3383 }
3384 }
3385 }
3386
3387 return {};
3388}
3389
3393PeerManagerImpl::FindProofForGetData(const Peer &peer,
3394 const avalanche::ProofId &proofid,
3395 const std::chrono::seconds now) {
3396 avalanche::ProofRef proof;
3397
3399 m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
3400 return pm.forPeer(proofid, [&](const avalanche::Peer &peer) {
3401 proof = peer.proof;
3402
3403 // If we know that proof for long enough, allow for requesting
3404 // it.
3405 return peer.registration_time <=
3407 });
3408 });
3409
3410 if (!proof) {
3411 // Always send our local proof if it gets requested, assuming it's
3412 // valid. This will make it easier to bind with peers upon startup where
3413 // the status of our proof is unknown pending for a block. Note that it
3414 // still needs to have been announced first (presumably via an avahello
3415 // message).
3416 proof = m_avalanche->getLocalProof();
3417 }
3418
3419 // We don't have this proof
3420 if (!proof) {
3421 return avalanche::ProofRef();
3422 }
3423
3425 return proof;
3426 }
3427
3428 // Otherwise, the proofs must have been announced recently.
3429 if (peer.m_proof_relay->m_recently_announced_proofs.contains(proofid)) {
3430 return proof;
3431 }
3432
3433 return avalanche::ProofRef();
3434}
3435
3436void PeerManagerImpl::ProcessGetData(
3437 const Config &config, CNode &pfrom, Peer &peer,
3438 const std::atomic<bool> &interruptMsgProc) {
3440
3441 auto tx_relay = peer.GetTxRelay();
3442
3443 std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
3444 std::vector<CInv> vNotFound;
3445 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3446
3447 const auto now{GetTime<std::chrono::seconds>()};
3448 // Get last mempool request time
3449 const auto mempool_req = tx_relay != nullptr
3450 ? tx_relay->m_last_mempool_req.load()
3451 : std::chrono::seconds::min();
3452
3453 // Process as many TX or AVA_PROOF items from the front of the getdata
3454 // queue as possible, since they're common and it's efficient to batch
3455 // process them.
3456 while (it != peer.m_getdata_requests.end()) {
3457 if (interruptMsgProc) {
3458 return;
3459 }
3460 // The send buffer provides backpressure. If there's no space in
3461 // the buffer, pause processing until the next call.
3462 if (pfrom.fPauseSend) {
3463 break;
3464 }
3465
3466 const CInv &inv = *it;
3467
3468 if (it->IsMsgProof()) {
3469 if (!m_avalanche) {
3470 vNotFound.push_back(inv);
3471 ++it;
3472 continue;
3473 }
3474 const avalanche::ProofId proofid(inv.hash);
3475 auto proof = FindProofForGetData(peer, proofid, now);
3476 if (proof) {
3477 m_connman.PushMessage(
3478 &pfrom, msgMaker.Make(NetMsgType::AVAPROOF, *proof));
3479 m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
3480 pm.removeUnbroadcastProof(proofid);
3481 });
3482 } else {
3483 vNotFound.push_back(inv);
3484 }
3485
3486 ++it;
3487 continue;
3488 }
3489
3490 if (it->IsMsgTx()) {
3491 if (tx_relay == nullptr) {
3492 // Ignore GETDATA requests for transactions from
3493 // block-relay-only peers and peers that asked us not to
3494 // announce transactions.
3495 continue;
3496 }
3497
3498 const TxId txid(inv.hash);
3499 CTransactionRef tx = FindTxForGetData(peer, txid, mempool_req, now);
3500 if (tx) {
3501 int nSendFlags = 0;
3502 m_connman.PushMessage(
3503 &pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *tx));
3504 m_mempool.RemoveUnbroadcastTx(txid);
3505 // As we're going to send tx, make sure its unconfirmed parents
3506 // are made requestable.
3507 std::vector<TxId> parent_ids_to_add;
3508 {
3509 LOCK(m_mempool.cs);
3510 auto txiter = m_mempool.GetIter(tx->GetId());
3511 if (txiter) {
3512 auto &pentry = *txiter;
3514 (*pentry)->GetMemPoolParentsConst();
3515 parent_ids_to_add.reserve(parents.size());
3516 for (const auto &parent : parents) {
3517 if (parent.get()->GetTime() >
3519 parent_ids_to_add.push_back(
3520 parent.get()->GetTx().GetId());
3521 }
3522 }
3523 }
3524 }
3525 for (const TxId &parent_txid : parent_ids_to_add) {
3526 // Relaying a transaction with a recent but unconfirmed
3527 // parent.
3528 if (WITH_LOCK(tx_relay->m_tx_inventory_mutex,
3529 return !tx_relay->m_tx_inventory_known_filter
3530 .contains(parent_txid))) {
3531 tx_relay->m_recently_announced_invs.insert(parent_txid);
3532 }
3533 }
3534 } else {
3535 vNotFound.push_back(inv);
3536 }
3537
3538 ++it;
3539 continue;
3540 }
3541
3542 // It's neither a proof nor a transaction
3543 break;
3544 }
3545
3546 // Only process one BLOCK item per call, since they're uncommon and can be
3547 // expensive to process.
3548 if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
3549 const CInv &inv = *it++;
3550 if (inv.IsGenBlkMsg()) {
3551 ProcessGetBlockData(config, pfrom, peer, inv);
3552 }
3553 // else: If the first item on the queue is an unknown type, we erase it
3554 // and continue processing the queue on the next call.
3555 }
3556
3557 peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
3558
3559 if (!vNotFound.empty()) {
3560 // Let the peer know that we didn't find what it asked for, so it
3561 // doesn't have to wait around forever. SPV clients care about this
3562 // message: it's needed when they are recursively walking the
3563 // dependencies of relevant unconfirmed transactions. SPV clients want
3564 // to do that because they want to know about (and store and rebroadcast
3565 // and risk analyze) the dependencies of transactions relevant to them,
3566 // without having to download the entire memory pool. Also, other nodes
3567 // can use these messages to automatically request a transaction from
3568 // some other peer that annnounced it, and stop waiting for us to
3569 // respond. In normal operation, we often send NOTFOUND messages for
3570 // parents of transactions that we relay; if a peer is missing a parent,
3571 // they may assume we have them and request the parents from us.
3572 m_connman.PushMessage(&pfrom,
3574 }
3575}
3576
3577void PeerManagerImpl::SendBlockTransactions(
3578 CNode &pfrom, Peer &peer, const CBlock &block,
3579 const BlockTransactionsRequest &req) {
3581 for (size_t i = 0; i < req.indices.size(); i++) {
3582 if (req.indices[i] >= block.vtx.size()) {
3583 Misbehaving(peer, 100, "getblocktxn with out-of-bounds tx indices");
3584 return;
3585 }
3586 resp.txn[i] = block.vtx[req.indices[i]];
3587 }
3588 LOCK(cs_main);
3589 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3590 int nSendFlags = 0;
3591 m_connman.PushMessage(
3593}
3594
3595bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader> &headers,
3597 Peer &peer) {
3598 // Do these headers have proof-of-work matching what's claimed?
3600 Misbehaving(peer, 100, "header with invalid proof of work");
3601 return false;
3602 }
3603
3604 // Are these headers connected to each other?
3606 Misbehaving(peer, 20, "non-continuous headers sequence");
3607 return false;
3608 }
3609 return true;
3610}
3611
3612arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold() {
3614 LOCK(cs_main);
3615 if (m_chainman.ActiveChain().Tip() != nullptr) {
3616 const CBlockIndex *tip = m_chainman.ActiveChain().Tip();
3617 // Use a 144 block buffer, so that we'll accept headers that fork from
3618 // near our tip.
3620 tip->nChainWork -
3621 std::min<arith_uint256>(144 * GetBlockProof(*tip), tip->nChainWork);
3622 }
3623 return std::max(near_chaintip_work, m_chainman.MinimumChainWork());
3624}
3625
3638void PeerManagerImpl::HandleFewUnconnectingHeaders(
3639 CNode &pfrom, Peer &peer, const std::vector<CBlockHeader> &headers) {
3640 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3641
3642 peer.m_num_unconnecting_headers_msgs++;
3643 // Try to fill in the missing headers.
3644 const CBlockIndex *best_header{
3645 WITH_LOCK(cs_main, return m_chainman.m_best_header)};
3647 LogPrint(
3648 BCLog::NET,
3649 "received header %s: missing prev block %s, sending getheaders "
3650 "(%d) to end (peer=%d, m_num_unconnecting_headers_msgs=%d)\n",
3651 headers[0].GetHash().ToString(),
3652 headers[0].hashPrevBlock.ToString(), best_header->nHeight,
3653 pfrom.GetId(), peer.m_num_unconnecting_headers_msgs);
3654 }
3655
3656 // Set hashLastUnknownBlock for this peer, so that if we
3657 // eventually get the headers - even from a different peer -
3658 // we can use this peer to download.
3660 UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash()));
3661
3662 // The peer may just be broken, so periodically assign DoS points if this
3663 // condition persists.
3664 if (peer.m_num_unconnecting_headers_msgs %
3666 0) {
3667 Misbehaving(peer, 20,
3668 strprintf("%d non-connecting headers",
3669 peer.m_num_unconnecting_headers_msgs));
3670 }
3671}
3672
3673bool PeerManagerImpl::CheckHeadersAreContinuous(
3674 const std::vector<CBlockHeader> &headers) const {
3676 for (const CBlockHeader &header : headers) {
3677 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
3678 return false;
3679 }
3680 hashLastBlock = header.GetHash();
3681 }
3682 return true;
3683}
3684
3685bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(
3686 Peer &peer, CNode &pfrom, std::vector<CBlockHeader> &headers) {
3687 if (peer.m_headers_sync) {
3688 auto result = peer.m_headers_sync->ProcessNextHeaders(
3690 if (result.request_more) {
3691 auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
3692 // If we were instructed to ask for a locator, it should not be
3693 // empty.
3694 Assume(!locator.vHave.empty());
3695 if (!locator.vHave.empty()) {
3696 // It should be impossible for the getheaders request to fail,
3697 // because we should have cleared the last getheaders timestamp
3698 // when processing the headers that triggered this call. But
3699 // it may be possible to bypass this via compactblock
3700 // processing, so check the result before logging just to be
3701 // safe.
3702 bool sent_getheaders =
3704 if (sent_getheaders) {
3706 "more getheaders (from %s) to peer=%d\n",
3707 locator.vHave.front().ToString(), pfrom.GetId());
3708 } else {
3710 "error sending next getheaders (from %s) to "
3711 "continue sync with peer=%d\n",
3712 locator.vHave.front().ToString(), pfrom.GetId());
3713 }
3714 }
3715 }
3716
3717 if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) {
3718 peer.m_headers_sync.reset(nullptr);
3719
3720 // Delete this peer's entry in m_headers_presync_stats.
3721 // If this is m_headers_presync_bestpeer, it will be replaced later
3722 // by the next peer that triggers the else{} branch below.
3723 LOCK(m_headers_presync_mutex);
3724 m_headers_presync_stats.erase(pfrom.GetId());
3725 } else {
3726 // Build statistics for this peer's sync.
3727 HeadersPresyncStats stats;
3728 stats.first = peer.m_headers_sync->GetPresyncWork();
3729 if (peer.m_headers_sync->GetState() ==
3731 stats.second = {peer.m_headers_sync->GetPresyncHeight(),
3732 peer.m_headers_sync->GetPresyncTime()};
3733 }
3734
3735 // Update statistics in stats.
3736 LOCK(m_headers_presync_mutex);
3737 m_headers_presync_stats[pfrom.GetId()] = stats;
3738 auto best_it =
3740 bool best_updated = false;
3741 if (best_it == m_headers_presync_stats.end()) {
3742 // If the cached best peer is outdated, iterate over all
3743 // remaining ones (including newly updated one) to find the best
3744 // one.
3745 NodeId peer_best{-1};
3746 const HeadersPresyncStats *stat_best{nullptr};
3747 for (const auto &[_peer, _stat] : m_headers_presync_stats) {
3748 if (!stat_best || _stat > *stat_best) {
3749 peer_best = _peer;
3750 stat_best = &_stat;
3751 }
3752 }
3754 best_updated = (peer_best == pfrom.GetId());
3755 } else if (best_it->first == pfrom.GetId() ||
3756 stats > best_it->second) {
3757 // pfrom was and remains the best peer, or pfrom just became
3758 // best.
3760 best_updated = true;
3761 }
3762 if (best_updated && stats.second.has_value()) {
3763 // If the best peer updated, and it is in its first phase,
3764 // signal.
3765 m_headers_presync_should_signal = true;
3766 }
3767 }
3768
3769 if (result.success) {
3770 // We only overwrite the headers passed in if processing was
3771 // successful.
3772 headers.swap(result.pow_validated_headers);
3773 }
3774
3775 return result.success;
3776 }
3777 // Either we didn't have a sync in progress, or something went wrong
3778 // processing these headers, or we are returning headers to the caller to
3779 // process.
3780 return false;
3781}
3782
3783bool PeerManagerImpl::TryLowWorkHeadersSync(
3784 Peer &peer, CNode &pfrom, const CBlockIndex *chain_start_header,
3785 std::vector<CBlockHeader> &headers) {
3786 // Calculate the total work on this chain.
3789
3790 // Our dynamic anti-DoS threshold (minimum work required on a headers chain
3791 // before we'll store it)
3792 arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
3793
3794 // Avoid DoS via low-difficulty-headers by only processing if the headers
3795 // are part of a chain with sufficient work.
3796 if (total_work < minimum_chain_work) {
3797 // Only try to sync with this peer if their headers message was full;
3798 // otherwise they don't have more headers after this so no point in
3799 // trying to sync their too-little-work chain.
3800 if (headers.size() == MAX_HEADERS_RESULTS) {
3801 // Note: we could advance to the last header in this set that is
3802 // known to us, rather than starting at the first header (which we
3803 // may already have); however this is unlikely to matter much since
3804 // ProcessHeadersMessage() already handles the case where all
3805 // headers in a received message are already known and are
3806 // ancestors of m_best_header or chainActive.Tip(), by skipping
3807 // this logic in that case. So even if the first header in this set
3808 // of headers is known, some header in this set must be new, so
3809 // advancing to the first unknown header would be a small effect.
3810 LOCK(peer.m_headers_sync_mutex);
3811 peer.m_headers_sync.reset(
3812 new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(),
3813 chain_start_header, minimum_chain_work));
3814
3815 // Now a HeadersSyncState object for tracking this synchronization
3816 // is created, process the headers using it as normal. Failures are
3817 // handled inside of IsContinuationOfLowWorkHeadersSync.
3819 } else {
3821 "Ignoring low-work chain (height=%u) from peer=%d\n",
3822 chain_start_header->nHeight + headers.size(),
3823 pfrom.GetId());
3824 }
3825 // The peer has not yet given us a chain that meets our work threshold,
3826 // so we want to prevent further processing of the headers in any case.
3827 headers = {};
3828 return true;
3829 }
3830
3831 return false;
3832}
3833
3834bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex *header) {
3835 return header != nullptr &&
3836 ((m_chainman.m_best_header != nullptr &&
3837 header ==
3838 m_chainman.m_best_header->GetAncestor(header->nHeight)) ||
3839 m_chainman.ActiveChain().Contains(header));
3840}
3841
3842bool PeerManagerImpl::MaybeSendGetHeaders(CNode &pfrom,
3843 const CBlockLocator &locator,
3844 Peer &peer) {
3845 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3846
3847 const auto current_time = NodeClock::now();
3848
3849 // Only allow a new getheaders message to go out if we don't have a recent
3850 // one already in-flight
3851 if (current_time - peer.m_last_getheaders_timestamp >
3853 m_connman.PushMessage(
3855 peer.m_last_getheaders_timestamp = current_time;
3856 return true;
3857 }
3858 return false;
3859}
3860
3867void PeerManagerImpl::HeadersDirectFetchBlocks(const Config &config,
3868 CNode &pfrom,
3869 const CBlockIndex &last_header) {
3870 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
3871
3872 LOCK(cs_main);
3873 CNodeState *nodestate = State(pfrom.GetId());
3874
3876 m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork) {
3877 std::vector<const CBlockIndex *> vToFetch;
3879 // Calculate all the blocks we'd need to switch to last_header, up to
3880 // a limit.
3881 while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) &&
3883 if (!pindexWalk->nStatus.hasData() &&
3884 !IsBlockRequested(pindexWalk->GetBlockHash())) {
3885 // We don't have this block, and it's not yet in flight.
3886 vToFetch.push_back(pindexWalk);
3887 }
3889 }
3890 // If pindexWalk still isn't on our main chain, we're looking at a
3891 // very large reorg at a time we think we're close to caught up to
3892 // the main chain -- this shouldn't really happen. Bail out on the
3893 // direct fetch and rely on parallel download instead.
3894 if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
3895 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
3896 last_header.GetBlockHash().ToString(),
3897 last_header.nHeight);
3898 } else {
3899 std::vector<CInv> vGetData;
3900 // Download as much as possible, from earliest to latest.
3901 for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
3902 if (nodestate->vBlocksInFlight.size() >=
3904 // Can't download any more from this peer
3905 break;
3906 }
3907 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3908 BlockRequested(config, pfrom.GetId(), *pindex);
3909 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
3910 pindex->GetBlockHash().ToString(), pfrom.GetId());
3911 }
3912 if (vGetData.size() > 1) {
3914 "Downloading blocks toward %s (%d) via headers "
3915 "direct fetch\n",
3916 last_header.GetBlockHash().ToString(),
3917 last_header.nHeight);
3918 }
3919 if (vGetData.size() > 0) {
3920 if (!m_opts.ignore_incoming_txs &&
3921 nodestate->m_provides_cmpctblocks && vGetData.size() == 1 &&
3922 mapBlocksInFlight.size() == 1 &&
3923 last_header.pprev->IsValid(BlockValidity::CHAIN)) {
3924 // In any case, we want to download using a compact
3925 // block, not a regular one.
3926 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
3927 }
3928 m_connman.PushMessage(
3930 }
3931 }
3932 }
3933}
3934
3940void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(
3941 CNode &pfrom, Peer &peer, const CBlockIndex &last_header,
3943 if (peer.m_num_unconnecting_headers_msgs > 0) {
3944 LogPrint(
3945 BCLog::NET,
3946 "peer=%d: resetting m_num_unconnecting_headers_msgs (%d -> 0)\n",
3947 pfrom.GetId(), peer.m_num_unconnecting_headers_msgs);
3948 }
3949 peer.m_num_unconnecting_headers_msgs = 0;
3950
3951 LOCK(cs_main);
3952
3953 CNodeState *nodestate = State(pfrom.GetId());
3954
3955 UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash());
3956
3957 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
3958 // because it is set in UpdateBlockAvailability. Some nullptr checks are
3959 // still present, however, as belt-and-suspenders.
3960
3961 if (received_new_header &&
3962 last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
3963 nodestate->m_last_block_announcement = GetTime();
3964 }
3965
3966 // If we're in IBD, we want outbound peers that will serve us a useful
3967 // chain. Disconnect peers that are on chains with insufficient work.
3968 if (m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
3970 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
3971 // headers to fetch from this peer.
3972 if (nodestate->pindexBestKnownBlock &&
3973 nodestate->pindexBestKnownBlock->nChainWork <
3974 m_chainman.MinimumChainWork()) {
3975 // This peer has too little work on their headers chain to help
3976 // us sync -- disconnect if it is an outbound disconnection
3977 // candidate.
3978 // Note: We compare their tip to the minimum chain work (rather than
3979 // m_chainman.ActiveChain().Tip()) because we won't start block
3980 // download until we have a headers chain that has at least
3981 // the minimum chain work, even if a peer has a chain past our tip,
3982 // as an anti-DoS measure.
3983 if (pfrom.IsOutboundOrBlockRelayConn()) {
3984 LogPrintf("Disconnecting outbound peer %d -- headers "
3985 "chain has insufficient work\n",
3986 pfrom.GetId());
3987 pfrom.fDisconnect = true;
3988 }
3989 }
3990 }
3991
3992 // If this is an outbound full-relay peer, check to see if we should
3993 // protect it from the bad/lagging chain logic.
3994 // Note that outbound block-relay peers are excluded from this
3995 // protection, and thus always subject to eviction under the bad/lagging
3996 // chain logic.
3997 // See ChainSyncTimeoutState.
3998 if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() &&
3999 nodestate->pindexBestKnownBlock != nullptr) {
4002 nodestate->pindexBestKnownBlock->nChainWork >=
4003 m_chainman.ActiveChain().Tip()->nChainWork &&
4004 !nodestate->m_chain_sync.m_protect) {
4005 LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n",
4006 pfrom.GetId());
4007 nodestate->m_chain_sync.m_protect = true;
4009 }
4010 }
4011}
4012
4013void PeerManagerImpl::ProcessHeadersMessage(const Config &config, CNode &pfrom,
4014 Peer &peer,
4015 std::vector<CBlockHeader> &&headers,
4016 bool via_compact_block) {
4017 size_t nCount = headers.size();
4018
4019 if (nCount == 0) {
4020 // Nothing interesting. Stop asking this peers for more headers.
4021 // If we were in the middle of headers sync, receiving an empty headers
4022 // message suggests that the peer suddenly has nothing to give us
4023 // (perhaps it reorged to our chain). Clear download state for this
4024 // peer.
4025 LOCK(peer.m_headers_sync_mutex);
4026 if (peer.m_headers_sync) {
4027 peer.m_headers_sync.reset(nullptr);
4028 LOCK(m_headers_presync_mutex);
4029 m_headers_presync_stats.erase(pfrom.GetId());
4030 }
4031 return;
4032 }
4033
4034 // Before we do any processing, make sure these pass basic sanity checks.
4035 // We'll rely on headers having valid proof-of-work further down, as an
4036 // anti-DoS criteria (note: this check is required before passing any
4037 // headers into HeadersSyncState).
4038 if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) {
4039 // Misbehaving() calls are handled within CheckHeadersPoW(), so we can
4040 // just return. (Note that even if a header is announced via compact
4041 // block, the header itself should be valid, so this type of error can
4042 // always be punished.)
4043 return;
4044 }
4045
4046 const CBlockIndex *pindexLast = nullptr;
4047
4048 // We'll set already_validated_work to true if these headers are
4049 // successfully processed as part of a low-work headers sync in progress
4050 // (either in PRESYNC or REDOWNLOAD phase).
4051 // If true, this will mean that any headers returned to us (ie during
4052 // REDOWNLOAD) can be validated without further anti-DoS checks.
4053 bool already_validated_work = false;
4054
4055 // If we're in the middle of headers sync, let it do its magic.
4056 bool have_headers_sync = false;
4057 {
4058 LOCK(peer.m_headers_sync_mutex);
4059
4062
4063 // The headers we passed in may have been:
4064 // - untouched, perhaps if no headers-sync was in progress, or some
4065 // failure occurred
4066 // - erased, such as if the headers were successfully processed and no
4067 // additional headers processing needs to take place (such as if we
4068 // are still in PRESYNC)
4069 // - replaced with headers that are now ready for validation, such as
4070 // during the REDOWNLOAD phase of a low-work headers sync.
4071 // So just check whether we still have headers that we need to process,
4072 // or not.
4073 if (headers.empty()) {
4074 return;
4075 }
4076
4077 have_headers_sync = !!peer.m_headers_sync;
4078 }
4079
4080 // Do these headers connect to something in our block index?
4083 headers[0].hashPrevBlock))};
4085
4088 // If this looks like it could be a BIP 130 block announcement, use
4089 // special logic for handling headers that don't connect, as this
4090 // could be benign.
4092 } else {
4093 Misbehaving(peer, 10, "invalid header received");
4094 }
4095 return;
4096 }
4097
4098 // If the headers we received are already in memory and an ancestor of
4099 // m_best_header or our tip, skip anti-DoS checks. These headers will not
4100 // use any more memory (and we are not leaking information that could be
4101 // used to fingerprint us).
4102 const CBlockIndex *last_received_header{nullptr};
4103 {
4104 LOCK(cs_main);
4106 m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash());
4109 }
4110 }
4111
4112 // If our peer has NetPermissionFlags::NoBan privileges, then bypass our
4113 // anti-DoS logic (this saves bandwidth when we connect to a trusted peer
4114 // on startup).
4115 if (pfrom.HasPermission(NetPermissionFlags::NoBan)) {
4117 }
4118
4119 // At this point, the headers connect to something in our block index.
4120 // Do anti-DoS checks to determine if we should process or store for later
4121 // processing.
4124 // If we successfully started a low-work headers sync, then there
4125 // should be no headers to process any further.
4126 Assume(headers.empty());
4127 return;
4128 }
4129
4130 // At this point, we have a set of headers with sufficient work on them
4131 // which can be processed.
4132
4133 // If we don't have the last header, then this peer will have given us
4134 // something new (if these headers are valid).
4136
4137 // Now process all the headers.
4139 if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true,
4140 state, &pindexLast)) {
4141 if (state.IsInvalid()) {
4143 "invalid header received");
4144 return;
4145 }
4146 }
4148
4149 // Consider fetching more headers if we are not using our headers-sync
4150 // mechanism.
4152 // Headers message had its maximum size; the peer may have more headers.
4154 LogPrint(
4155 BCLog::NET,
4156 "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
4157 pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
4158 }
4159 }
4160
4164
4165 // Consider immediately downloading blocks.
4167}
4168
4169void PeerManagerImpl::ProcessInvalidTx(NodeId nodeid,
4170 const CTransactionRef &ptx,
4171 const TxValidationState &state,
4173 AssertLockNotHeld(m_peer_mutex);
4174 AssertLockHeld(g_msgproc_mutex);
4176
4177 const TxId &txid = ptx->GetId();
4178
4179 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n",
4180 txid.ToString(), nodeid, state.ToString());
4181
4183 return;
4184 }
4185
4186 if (m_avalanche && m_avalanche->m_preConsensus &&
4188 return;
4189 }
4190
4192 // If the result is TX_PACKAGE_RECONSIDERABLE, add it to
4193 // m_recent_rejects_package_reconsiderable because we should not
4194 // download or submit this transaction by itself again, but may submit
4195 // it as part of a package later.
4197 } else {
4198 m_recent_rejects.insert(txid);
4199 }
4200 m_txrequest.ForgetInvId(txid);
4201
4204 }
4205
4206 MaybePunishNodeForTx(nodeid, state);
4207
4208 // If the tx failed in ProcessOrphanTx, it should be removed from the
4209 // orphanage unless the tx was still missing inputs. If the tx was not in
4210 // the orphanage, EraseTx does nothing and returns 0.
4211 if (m_mempool.withOrphanage([&txid](TxOrphanage &orphanage) {
4212 return orphanage.EraseTx(txid);
4213 }) > 0) {
4214 LogPrint(BCLog::TXPACKAGES, " removed orphan tx %s\n",
4215 txid.ToString());
4216 }
4217}
4218
4219void PeerManagerImpl::ProcessValidTx(NodeId nodeid, const CTransactionRef &tx) {
4220 AssertLockNotHeld(m_peer_mutex);
4221 AssertLockHeld(g_msgproc_mutex);
4223
4224 // As this version of the transaction was acceptable, we can forget about
4225 // any requests for it. No-op if the tx is not in txrequest.
4226 m_txrequest.ForgetInvId(tx->GetId());
4227
4228 m_mempool.withOrphanage([&tx](TxOrphanage &orphanage) {
4229 orphanage.AddChildrenToWorkSet(*tx);
4230 // If it came from the orphanage, remove it. No-op if the tx is not in
4231 // txorphanage.
4232 orphanage.EraseTx(tx->GetId());
4233 });
4234
4235 LogPrint(
4237 "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4238 nodeid, tx->GetId().ToString(), m_mempool.size(),
4239 m_mempool.DynamicMemoryUsage() / 1000);
4240
4241 RelayTransaction(tx->GetId());
4242}
4243
4244void PeerManagerImpl::ProcessPackageResult(
4245 const PackageToValidate &package_to_validate,
4247 AssertLockNotHeld(m_peer_mutex);
4248 AssertLockHeld(g_msgproc_mutex);
4250
4251 const auto &package = package_to_validate.m_txns;
4252 const auto &senders = package_to_validate.m_senders;
4253
4254 if (package_result.m_state.IsInvalid()) {
4256 }
4257 // We currently only expect to process 1-parent-1-child packages. Remove if
4258 // this changes.
4259 if (!Assume(package.size() == 2)) {
4260 return;
4261 }
4262
4263 // Iterate backwards to erase in-package descendants from the orphanage
4264 // before they become relevant in AddChildrenToWorkSet.
4265 auto package_iter = package.rbegin();
4266 auto senders_iter = senders.rbegin();
4267 while (package_iter != package.rend()) {
4268 const auto &tx = *package_iter;
4269 const NodeId nodeid = *senders_iter;
4270 const auto it_result{package_result.m_tx_results.find(tx->GetId())};
4271
4272 // It is not guaranteed that a result exists for every transaction.
4273 if (it_result != package_result.m_tx_results.end()) {
4274 const auto &tx_result = it_result->second;
4275 switch (tx_result.m_result_type) {
4277 ProcessValidTx(nodeid, tx);
4278 break;
4279 }
4281 // Don't add to vExtraTxnForCompact, as these transactions
4282 // should have already been added there when added to the
4283 // orphanage or rejected for TX_PACKAGE_RECONSIDERABLE.
4284 // This should be updated if package submission is ever used
4285 // for transactions that haven't already been validated
4286 // before.
4287 ProcessInvalidTx(nodeid, tx, tx_result.m_state,
4288 /*maybe_add_extra_compact_tx=*/false);
4289 break;
4290 }
4292 // AlreadyHaveTx() should be catching transactions that are
4293 // already in mempool.
4294 Assume(false);
4295 break;
4296 }
4297 }
4298 }
4299 package_iter++;
4300 senders_iter++;
4301 }
4302}
4303
4304std::optional<PeerManagerImpl::PackageToValidate>
4305PeerManagerImpl::Find1P1CPackage(const CTransactionRef &ptx, NodeId nodeid) {
4306 AssertLockNotHeld(m_peer_mutex);
4307 AssertLockHeld(g_msgproc_mutex);
4309
4310 const auto &parent_txid{ptx->GetId()};
4311
4313
4314 // Prefer children from this peer. This helps prevent censorship attempts in
4315 // which an attacker sends lots of fake children for the parent, and we
4316 // (unluckily) keep selecting the fake children instead of the real one
4317 // provided by the honest peer.
4318 const auto cpfp_candidates_same_peer{
4319 m_mempool.withOrphanage([&ptx, nodeid](const TxOrphanage &orphanage) {
4320 return orphanage.GetChildrenFromSamePeer(ptx, nodeid);
4321 })};
4322
4323 // These children should be sorted from newest to oldest.
4324 for (const auto &child : cpfp_candidates_same_peer) {
4328 return PeerManagerImpl::PackageToValidate{ptx, child, nodeid,
4329 nodeid};
4330 }
4331 }
4332
4333 // If no suitable candidate from the same peer is found, also try children
4334 // that were provided by a different peer. This is useful because sometimes
4335 // multiple peers announce both transactions to us, and we happen to
4336 // download them from different peers (we wouldn't have known that these 2
4337 // transactions are related). We still want to find 1p1c packages then.
4338 //
4339 // If we start tracking all announcers of orphans, we can restrict this
4340 // logic to parent + child pairs in which both were provided by the same
4341 // peer, i.e. delete this step.
4343 m_mempool.withOrphanage([&ptx, nodeid](const TxOrphanage &orphanage) {
4344 return orphanage.GetChildrenFromDifferentPeer(ptx, nodeid);
4345 })};
4346
4347 // Find the first 1p1c that hasn't already been rejected. We randomize the
4348 // order to not create a bias that attackers can use to delay package
4349 // acceptance.
4350 //
4351 // Create a random permutation of the indices.
4352 std::vector<size_t> tx_indices(cpfp_candidates_different_peer.size());
4353 std::iota(tx_indices.begin(), tx_indices.end(), 0);
4354 Shuffle(tx_indices.begin(), tx_indices.end(), m_rng);
4355
4356 for (const auto index : tx_indices) {
4357 // If we already tried a package and failed for any reason, the combined
4358 // hash was cached in m_recent_rejects_package_reconsiderable.
4359 const auto [child_tx, child_sender] =
4364 return PeerManagerImpl::PackageToValidate{ptx, child_tx, nodeid,
4365 child_sender};
4366 }
4367 }
4368 return std::nullopt;
4369}
4370
4371bool PeerManagerImpl::ProcessOrphanTx(const Config &config, Peer &peer) {
4372 AssertLockHeld(g_msgproc_mutex);
4373 LOCK(cs_main);
4374
4375 while (CTransactionRef porphanTx =
4376 m_mempool.withOrphanage([&peer](TxOrphanage &orphanage) {
4377 return orphanage.GetTxToReconsider(peer.m_id);
4378 })) {
4379 const MempoolAcceptResult result =
4380 m_chainman.ProcessTransaction(porphanTx);
4381 const TxValidationState &state = result.m_state;
4382 const TxId &orphanTxId = porphanTx->GetId();
4383
4385 LogPrint(BCLog::TXPACKAGES, " accepted orphan tx %s\n",
4386 orphanTxId.ToString());
4387 ProcessValidTx(peer.m_id, porphanTx);
4388 return true;
4389 }
4390
4393 " invalid orphan tx %s from peer=%d. %s\n",
4394 orphanTxId.ToString(), peer.m_id, state.ToString());
4395
4396 if (Assume(state.IsInvalid() &&
4398 state.GetResult() !=
4400 ProcessInvalidTx(peer.m_id, porphanTx, state,
4401 /*maybe_add_extra_compact_tx=*/false);
4402 }
4403
4404 return true;
4405 }
4406 }
4407
4408 return false;
4409}
4410
4411bool PeerManagerImpl::PrepareBlockFilterRequest(
4414 const CBlockIndex *&stop_index, BlockFilterIndex *&filter_index) {
4415 const bool supported_filter_type =
4417 (peer.m_our_services & NODE_COMPACT_FILTERS));
4418 if (!supported_filter_type) {
4420 "peer %d requested unsupported block filter type: %d\n",
4421 node.GetId(), static_cast<uint8_t>(filter_type));
4422 node.fDisconnect = true;
4423 return false;
4424 }
4425
4426 {
4427 LOCK(cs_main);
4429
4430 // Check that the stop block exists and the peer would be allowed to
4431 // fetch it.
4433 LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
4434 node.GetId(), stop_hash.ToString());
4435 node.fDisconnect = true;
4436 return false;
4437 }
4438 }
4439
4440 uint32_t stop_height = stop_index->nHeight;
4441 if (start_height > stop_height) {
4442 LogPrint(
4443 BCLog::NET,
4444 "peer %d sent invalid getcfilters/getcfheaders with " /* Continued
4445 */
4446 "start height %d and stop height %d\n",
4447 node.GetId(), start_height, stop_height);
4448 node.fDisconnect = true;
4449 return false;
4450 }
4453 "peer %d requested too many cfilters/cfheaders: %d / %d\n",
4455 node.fDisconnect = true;
4456 return false;
4457 }
4458
4459 filter_index = GetBlockFilterIndex(filter_type);
4460 if (!filter_index) {
4461 LogPrint(BCLog::NET, "Filter index for supported type %s not found\n",
4463 return false;
4464 }
4465
4466 return true;
4467}
4468
4469void PeerManagerImpl::ProcessGetCFilters(CNode &node, Peer &peer,
4470 CDataStream &vRecv) {
4474
4475 vRecv >> filter_type_ser >> start_height >> stop_hash;
4476
4478 static_cast<BlockFilterType>(filter_type_ser);
4479
4480 const CBlockIndex *stop_index;
4481 BlockFilterIndex *filter_index;
4484 filter_index)) {
4485 return;
4486 }
4487
4488 std::vector<BlockFilter> filters;
4489 if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
4491 "Failed to find block filter in index: filter_type=%s, "
4492 "start_height=%d, stop_hash=%s\n",
4494 stop_hash.ToString());
4495 return;
4496 }
4497
4498 for (const auto &filter : filters) {
4499 CSerializedNetMsg msg = CNetMsgMaker(node.GetCommonVersion())
4500 .Make(NetMsgType::CFILTER, filter);
4501 m_connman.PushMessage(&node, std::move(msg));
4502 }
4503}
4504
4505void PeerManagerImpl::ProcessGetCFHeaders(CNode &node, Peer &peer,
4506 CDataStream &vRecv) {
4510
4511 vRecv >> filter_type_ser >> start_height >> stop_hash;
4512
4514 static_cast<BlockFilterType>(filter_type_ser);
4515
4516 const CBlockIndex *stop_index;
4517 BlockFilterIndex *filter_index;
4520 filter_index)) {
4521 return;
4522 }
4523
4525 if (start_height > 0) {
4526 const CBlockIndex *const prev_block =
4527 stop_index->GetAncestor(static_cast<int>(start_height - 1));
4528 if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
4530 "Failed to find block filter header in index: "
4531 "filter_type=%s, block_hash=%s\n",
4533 prev_block->GetBlockHash().ToString());
4534 return;
4535 }
4536 }
4537
4538 std::vector<uint256> filter_hashes;
4539 if (!filter_index->LookupFilterHashRange(start_height, stop_index,
4540 filter_hashes)) {
4542 "Failed to find block filter hashes in index: filter_type=%s, "
4543 "start_height=%d, stop_hash=%s\n",
4545 stop_hash.ToString());
4546 return;
4547 }
4548
4549 CSerializedNetMsg msg =
4550 CNetMsgMaker(node.GetCommonVersion())
4552 stop_index->GetBlockHash(), prev_header, filter_hashes);
4553 m_connman.PushMessage(&node, std::move(msg));
4554}
4555
4556void PeerManagerImpl::ProcessGetCFCheckPt(CNode &node, Peer &peer,
4557 CDataStream &vRecv) {
4560
4561 vRecv >> filter_type_ser >> stop_hash;
4562
4564 static_cast<BlockFilterType>(filter_type_ser);
4565
4566 const CBlockIndex *stop_index;
4567 BlockFilterIndex *filter_index;
4569 node, peer, filter_type, /*start_height=*/0, stop_hash,
4570 /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
4571 stop_index, filter_index)) {
4572 return;
4573 }
4574
4575 std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
4576
4577 // Populate headers.
4579 for (int i = headers.size() - 1; i >= 0; i--) {
4580 int height = (i + 1) * CFCHECKPT_INTERVAL;
4582
4583 if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
4585 "Failed to find block filter header in index: "
4586 "filter_type=%s, block_hash=%s\n",
4588 block_index->GetBlockHash().ToString());
4589 return;
4590 }
4591 }
4592
4593 CSerializedNetMsg msg = CNetMsgMaker(node.GetCommonVersion())
4595 stop_index->GetBlockHash(), headers);
4596 m_connman.PushMessage(&node, std::move(msg));
4597}
4598
4609
4611PeerManagerImpl::GetAvalancheVoteForBlock(const BlockHash &hash) const {
4613
4614 const CBlockIndex *pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
4615
4616 // Unknown block.
4617 if (!pindex) {
4618 return -1;
4619 }
4620
4621 // Invalid block
4622 if (pindex->nStatus.isInvalid()) {
4623 return 1;
4624 }
4625
4626 // Parked block
4627 if (pindex->nStatus.isOnParkedChain()) {
4628 return 2;
4629 }
4630
4631 const CBlockIndex *pindexTip = m_chainman.ActiveChain().Tip();
4633
4634 // Active block.
4635 if (pindex == pindexFork) {
4636 return 0;
4637 }
4638
4639 // Fork block.
4640 if (pindexFork != pindexTip) {
4641 return 3;
4642 }
4643
4644 // Missing block data.
4645 if (!pindex->nStatus.hasData()) {
4646 return -2;
4647 }
4648
4649 // This block is built on top of the tip, we have the data, it
4650 // is pending connection or rejection.
4651 return -3;
4652};
4653
4654uint32_t PeerManagerImpl::GetAvalancheVoteForTx(const TxId &id) const {
4655 // Accepted in mempool, or in a recent block
4656 if (m_mempool.exists(id) ||
4657 WITH_LOCK(m_recent_confirmed_transactions_mutex,
4658 return m_recent_confirmed_transactions.contains(id))) {
4659 return 0;
4660 }
4661
4662 // Conflicting tx
4663 if (m_mempool.withConflicting([&id](const TxConflicting &conflicting) {
4664 return conflicting.HaveTx(id);
4665 })) {
4666 return 2;
4667 }
4668
4669 // Invalid tx
4670 if (m_recent_rejects.contains(id)) {
4671 return 1;
4672 }
4673
4674 // Orphan tx
4675 if (m_mempool.withOrphanage([&id](const TxOrphanage &orphanage) {
4676 return orphanage.HaveTx(id);
4677 })) {
4678 return -2;
4679 }
4680
4681 // Unknown tx
4682 return -1;
4683};
4684
4692 const avalanche::ProofId &id) {
4693 return avalanche.withPeerManager([&id](avalanche::PeerManager &pm) {
4694 // Rejected proof
4695 if (pm.isInvalid(id)) {
4696 return 1;
4697 }
4698
4699 // The proof is actively bound to a peer
4700 if (pm.isBoundToPeer(id)) {
4701 return 0;
4702 }
4703
4704 // Unknown proof
4705 if (!pm.exists(id)) {
4706 return -1;
4707 }
4708
4709 // Immature proof
4710 if (pm.isImmature(id)) {
4711 return 2;
4712 }
4713
4714 // Not immature, but in conflict with an actively bound proof
4715 if (pm.isInConflictingPool(id)) {
4716 return 3;
4717 }
4718
4719 // The proof is known, not rejected, not immature, not a conflict, but
4720 // for some reason unbound. This should not happen if the above pools
4721 // are managed correctly, but added for robustness.
4722 return -2;
4723 });
4724};
4725
4726void PeerManagerImpl::ProcessBlock(const Config &config, CNode &node,
4727 const std::shared_ptr<const CBlock> &block,
4728 bool force_processing,
4729 bool min_pow_checked) {
4730 bool new_block{false};
4732 &new_block, m_avalanche);
4733 if (new_block) {
4734 node.m_last_block_time = GetTime<std::chrono::seconds>();
4735 // In case this block came from a different peer than we requested
4736 // from, we can erase the block request now anyway (as we just stored
4737 // this block to disk).
4738 LOCK(cs_main);
4739 RemoveBlockRequest(block->GetHash(), std::nullopt);
4740 } else {
4741 LOCK(cs_main);
4742 mapBlockSource.erase(block->GetHash());
4743 }
4744}
4745
4746void PeerManagerImpl::ProcessMessage(
4747 const Config &config, CNode &pfrom, const std::string &msg_type,
4748 CDataStream &vRecv, const std::chrono::microseconds time_received,
4749 const std::atomic<bool> &interruptMsgProc) {
4750 AssertLockHeld(g_msgproc_mutex);
4751
4752 LogPrint(BCLog::NETDEBUG, "received: %s (%u bytes) peer=%d\n",
4753 SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
4754
4755 PeerRef peer = GetPeerRef(pfrom.GetId());
4756 if (peer == nullptr) {
4757 return;
4758 }
4759
4760 if (!m_avalanche && IsAvalancheMessageType(msg_type)) {
4762 "Avalanche is not initialized, ignoring %s message\n",
4763 msg_type);
4764 return;
4765 }
4766
4768 // Each connection can only send one version message
4769 if (pfrom.nVersion != 0) {
4770 Misbehaving(*peer, 1, "redundant version message");
4771 return;
4772 }
4773
4774 int64_t nTime;
4776 uint64_t nNonce = 1;
4777 ServiceFlags nServices;
4778 int nVersion;
4779 std::string cleanSubVer;
4780 int starting_height = -1;
4781 bool fRelay = true;
4783
4784 vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
4785 if (nTime < 0) {
4786 nTime = 0;
4787 }
4788 // Ignore the addrMe service bits sent by the peer
4789 vRecv.ignore(8);
4790 vRecv >> addrMe;
4791 if (!pfrom.IsInboundConn()) {
4792 m_addrman.SetServices(pfrom.addr, nServices);
4793 }
4794 if (pfrom.ExpectServicesFromConn() &&
4795 !HasAllDesirableServiceFlags(nServices)) {
4797 "peer=%d does not offer the expected services "
4798 "(%08x offered, %08x expected); disconnecting\n",
4799 pfrom.GetId(), nServices,
4800 GetDesirableServiceFlags(nServices));
4801 pfrom.fDisconnect = true;
4802 return;
4803 }
4804
4805 if (pfrom.IsAvalancheOutboundConnection() &&
4806 !(nServices & NODE_AVALANCHE)) {
4807 LogPrint(
4809 "peer=%d does not offer the avalanche service; disconnecting\n",
4810 pfrom.GetId());
4811 pfrom.fDisconnect = true;
4812 return;
4813 }
4814
4815 if (nVersion < MIN_PEER_PROTO_VERSION) {
4816 // disconnect from peers older than this proto version
4818 "peer=%d using obsolete version %i; disconnecting\n",
4819 pfrom.GetId(), nVersion);
4820 pfrom.fDisconnect = true;
4821 return;
4822 }
4823
4824 if (!vRecv.empty()) {
4825 // The version message includes information about the sending node
4826 // which we don't use:
4827 // - 8 bytes (service bits)
4828 // - 16 bytes (ipv6 address)
4829 // - 2 bytes (port)
4830 vRecv.ignore(26);
4831 vRecv >> nNonce;
4832 }
4833 if (!vRecv.empty()) {
4834 std::string strSubVer;
4835 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
4836 cleanSubVer = SanitizeString(strSubVer);
4837 }
4838 if (!vRecv.empty()) {
4839 vRecv >> starting_height;
4840 }
4841 if (!vRecv.empty()) {
4842 vRecv >> fRelay;
4843 }
4844 if (!vRecv.empty()) {
4845 vRecv >> nExtraEntropy;
4846 }
4847 // Disconnect if we connected to ourself
4848 if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce)) {
4849 LogPrintf("connected to self at %s, disconnecting\n",
4850 pfrom.addr.ToString());
4851 pfrom.fDisconnect = true;
4852 return;
4853 }
4854
4855 if (pfrom.IsInboundConn() && addrMe.IsRoutable()) {
4857 }
4858
4859 // Inbound peers send us their version message when they connect.
4860 // We send our version message in response.
4861 if (pfrom.IsInboundConn()) {
4862 PushNodeVersion(config, pfrom, *peer);
4863 }
4864
4865 // Change version
4866 const int greatest_common_version =
4867 std::min(nVersion, PROTOCOL_VERSION);
4868 pfrom.SetCommonVersion(greatest_common_version);
4869 pfrom.nVersion = nVersion;
4870
4872
4873 m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::VERACK));
4874
4875 // Signal ADDRv2 support (BIP155).
4877
4878 pfrom.m_has_all_wanted_services =
4879 HasAllDesirableServiceFlags(nServices);
4880 peer->m_their_services = nServices;
4881 pfrom.SetAddrLocal(addrMe);
4882 {
4883 LOCK(pfrom.m_subver_mutex);
4884 pfrom.cleanSubVer = cleanSubVer;
4885 }
4886 peer->m_starting_height = starting_height;
4887
4888 // Only initialize the m_tx_relay data structure if:
4889 // - this isn't an outbound block-relay-only connection; and
4890 // - this isn't an outbound feeler connection, and
4891 // - fRelay=true or we're offering NODE_BLOOM to this peer
4892 // (NODE_BLOOM means that the peer may turn on tx relay later)
4893 if (!pfrom.IsBlockOnlyConn() && !pfrom.IsFeelerConn() &&
4894 (fRelay || (peer->m_our_services & NODE_BLOOM))) {
4895 auto *const tx_relay = peer->SetTxRelay();
4896 {
4897 LOCK(tx_relay->m_bloom_filter_mutex);
4898 // set to true after we get the first filter* message
4899 tx_relay->m_relay_txs = fRelay;
4900 }
4901 if (fRelay) {
4902 pfrom.m_relays_txs = true;
4903 }
4904 }
4905
4906 pfrom.nRemoteHostNonce = nNonce;
4907 pfrom.nRemoteExtraEntropy = nExtraEntropy;
4908
4909 // Potentially mark this peer as a preferred download peer.
4910 {
4911 LOCK(cs_main);
4912 CNodeState *state = State(pfrom.GetId());
4913 state->fPreferredDownload =
4914 (!pfrom.IsInboundConn() ||
4915 pfrom.HasPermission(NetPermissionFlags::NoBan)) &&
4916 !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer);
4917 m_num_preferred_download_peers += state->fPreferredDownload;
4918 }
4919
4920 // Attempt to initialize address relay for outbound peers and use result
4921 // to decide whether to send GETADDR, so that we don't send it to
4922 // inbound or outbound block-relay-only peers.
4923 bool send_getaddr{false};
4924 if (!pfrom.IsInboundConn()) {
4926 }
4927 if (send_getaddr) {
4928 // Do a one-time address fetch to help populate/update our addrman.
4929 // If we're starting up for the first time, our addrman may be
4930 // pretty empty, so this mechanism is important to help us connect
4931 // to the network.
4932 // We skip this for block-relay-only peers. We want to avoid
4933 // potentially leaking addr information and we do not want to
4934 // indicate to the peer that we will participate in addr relay.
4936 .Make(NetMsgType::GETADDR));
4937 peer->m_getaddr_sent = true;
4938 // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND
4939 // addresses in response (bypassing the
4940 // MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
4941 WITH_LOCK(peer->m_addr_token_bucket_mutex,
4942 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
4943 }
4944
4945 if (!pfrom.IsInboundConn()) {
4946 // For non-inbound connections, we update the addrman to record
4947 // connection success so that addrman will have an up-to-date
4948 // notion of which peers are online and available.
4949 //
4950 // While we strive to not leak information about block-relay-only
4951 // connections via the addrman, not moving an address to the tried
4952 // table is also potentially detrimental because new-table entries
4953 // are subject to eviction in the event of addrman collisions. We
4954 // mitigate the information-leak by never calling
4955 // AddrMan::Connected() on block-relay-only peers; see
4956 // FinalizeNode().
4957 //
4958 // This moves an address from New to Tried table in Addrman,
4959 // resolves tried-table collisions, etc.
4960 m_addrman.Good(pfrom.addr);
4961 }
4962
4963 std::string remoteAddr;
4964 if (fLogIPs) {
4965 remoteAddr = ", peeraddr=" + pfrom.addr.ToString();
4966 }
4967
4969 "receive version message: [%s] %s: version %d, blocks=%d, "
4970 "us=%s, txrelay=%d, peer=%d%s\n",
4971 pfrom.addr.ToString(), cleanSubVer, pfrom.nVersion,
4972 peer->m_starting_height, addrMe.ToString(), fRelay,
4973 pfrom.GetId(), remoteAddr);
4974
4976 int64_t nTimeOffset = nTime - currentTime;
4977 pfrom.nTimeOffset = nTimeOffset;
4978 if (nTime < int64_t(m_chainparams.GenesisBlock().nTime)) {
4979 // Ignore time offsets that are improbable (before the Genesis
4980 // block) and may underflow our adjusted time.
4981 Misbehaving(*peer, 20,
4982 "Ignoring invalid timestamp in version message");
4983 } else if (!pfrom.IsInboundConn()) {
4984 // Don't use timedata samples from inbound peers to make it
4985 // harder for others to tamper with our adjusted time.
4986 AddTimeData(pfrom.addr, nTimeOffset);
4987 }
4988
4989 // Feeler connections exist only to verify if address is online.
4990 if (pfrom.IsFeelerConn()) {
4992 "feeler connection completed peer=%d; disconnecting\n",
4993 pfrom.GetId());
4994 pfrom.fDisconnect = true;
4995 }
4996 return;
4997 }
4998
4999 if (pfrom.nVersion == 0) {
5000 // Must have a version message before anything else
5001 Misbehaving(*peer, 10, "non-version message before version handshake");
5002 return;
5003 }
5004
5005 // At this point, the outgoing message serialization version can't change.
5006 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
5007
5009 if (pfrom.fSuccessfullyConnected) {
5011 "ignoring redundant verack message from peer=%d\n",
5012 pfrom.GetId());
5013 return;
5014 }
5015
5016 if (!pfrom.IsInboundConn()) {
5017 LogPrintf(
5018 "New outbound peer connected: version: %d, blocks=%d, "
5019 "peer=%d%s (%s)\n",
5020 pfrom.nVersion.load(), peer->m_starting_height, pfrom.GetId(),
5021 (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToString())
5022 : ""),
5024 }
5025
5026 if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) {
5027 // Tell our peer we are willing to provide version 1
5028 // cmpctblocks. However, we do not request new block announcements
5029 // using cmpctblock messages. We send this to non-NODE NETWORK peers
5030 // as well, because they may wish to request compact blocks from us.
5031 m_connman.PushMessage(
5032 &pfrom,
5033 msgMaker.Make(NetMsgType::SENDCMPCT, /*high_bandwidth=*/false,
5034 /*version=*/CMPCTBLOCKS_VERSION));
5035 }
5036
5037 if (m_avalanche) {
5038 if (m_avalanche->sendHello(&pfrom)) {
5039 auto localProof = m_avalanche->getLocalProof();
5040
5041 if (localProof) {
5042 AddKnownProof(*peer, localProof->getId());
5043 // Add our proof id to the list or the recently announced
5044 // proof INVs to this peer. This is used for filtering which
5045 // INV can be requested for download.
5046 peer->m_proof_relay->m_recently_announced_proofs.insert(
5047 localProof->getId());
5048 }
5049 }
5050 }
5051
5052 if (auto tx_relay = peer->GetTxRelay()) {
5053 // `TxRelay::m_tx_inventory_to_send` must be empty before the
5054 // version handshake is completed as
5055 // `TxRelay::m_next_inv_send_time` is first initialised in
5056 // `SendMessages` after the verack is received. Any transactions
5057 // received during the version handshake would otherwise
5058 // immediately be advertised without random delay, potentially
5059 // leaking the time of arrival to a spy.
5060 Assume(WITH_LOCK(tx_relay->m_tx_inventory_mutex,
5061 return tx_relay->m_tx_inventory_to_send.empty() &&
5062 tx_relay->m_next_inv_send_time == 0s));
5063 }
5064
5065 pfrom.fSuccessfullyConnected = true;
5066 return;
5067 }
5068
5069 if (!pfrom.fSuccessfullyConnected) {
5070 // Must have a verack message before anything else
5071 Misbehaving(*peer, 10, "non-verack message before version handshake");
5072 return;
5073 }
5074
5076 int stream_version = vRecv.GetVersion();
5078 // Add ADDRV2_FORMAT to the version so that the CNetAddr and
5079 // CAddress unserialize methods know that an address in v2 format is
5080 // coming.
5082 }
5083
5085 std::vector<CAddress> vAddr;
5086
5087 s >> vAddr;
5088
5089 if (!SetupAddressRelay(pfrom, *peer)) {
5090 LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n",
5091 msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
5092 return;
5093 }
5094
5095 if (vAddr.size() > m_opts.max_addr_to_send) {
5097 *peer, 20,
5098 strprintf("%s message size = %u", msg_type, vAddr.size()));
5099 return;
5100 }
5101
5102 // Store the new addresses
5103 std::vector<CAddress> vAddrOk;
5104 const auto current_a_time{Now<NodeSeconds>()};
5105
5106 // Update/increment addr rate limiting bucket.
5108 {
5109 LOCK(peer->m_addr_token_bucket_mutex);
5110 if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
5111 // Don't increment bucket if it's already full
5112 const auto time_diff =
5113 std::max(current_time - peer->m_addr_token_timestamp, 0us);
5114 const double increment =
5116 peer->m_addr_token_bucket =
5117 std::min<double>(peer->m_addr_token_bucket + increment,
5119 }
5120 }
5121 peer->m_addr_token_timestamp = current_time;
5122
5123 const bool rate_limited =
5124 !pfrom.HasPermission(NetPermissionFlags::Addr);
5125 uint64_t num_proc = 0;
5127 Shuffle(vAddr.begin(), vAddr.end(), m_rng);
5128 for (CAddress &addr : vAddr) {
5129 if (interruptMsgProc) {
5130 return;
5131 }
5132
5133 {
5134 LOCK(peer->m_addr_token_bucket_mutex);
5135 // Apply rate limiting.
5136 if (peer->m_addr_token_bucket < 1.0) {
5137 if (rate_limited) {
5139 continue;
5140 }
5141 } else {
5142 peer->m_addr_token_bucket -= 1.0;
5143 }
5144 }
5145
5146 // We only bother storing full nodes, though this may include things
5147 // which we would not make an outbound connection to, in part
5148 // because we may make feeler connections to them.
5149 if (!MayHaveUsefulAddressDB(addr.nServices) &&
5151 continue;
5152 }
5153
5154 if (addr.nTime <= NodeSeconds{100000000s} ||
5155 addr.nTime > current_a_time + 10min) {
5156 addr.nTime = current_a_time - 5 * 24h;
5157 }
5158 AddAddressKnown(*peer, addr);
5159 if (m_banman &&
5160 (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
5161 // Do not process banned/discouraged addresses beyond
5162 // remembering we received them
5163 continue;
5164 }
5165 ++num_proc;
5166 bool fReachable = IsReachable(addr);
5167 if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent &&
5168 vAddr.size() <= 10 && addr.IsRoutable()) {
5169 // Relay to a limited number of other nodes
5170 RelayAddress(pfrom.GetId(), addr, fReachable);
5171 }
5172 // Do not store addresses outside our network
5173 if (fReachable) {
5174 vAddrOk.push_back(addr);
5175 }
5176 }
5177 peer->m_addr_processed += num_proc;
5178 peer->m_addr_rate_limited += num_rate_limit;
5180 "Received addr: %u addresses (%u processed, %u rate-limited) "
5181 "from peer=%d\n",
5182 vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
5183
5184 m_addrman.Add(vAddrOk, pfrom.addr, 2h);
5185 if (vAddr.size() < 1000) {
5186 peer->m_getaddr_sent = false;
5187 }
5188
5189 // AddrFetch: Require multiple addresses to avoid disconnecting on
5190 // self-announcements
5191 if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
5193 "addrfetch connection completed peer=%d; disconnecting\n",
5194 pfrom.GetId());
5195 pfrom.fDisconnect = true;
5196 }
5197 return;
5198 }
5199
5201 peer->m_wants_addrv2 = true;
5202 return;
5203 }
5204
5206 peer->m_prefers_headers = true;
5207 return;
5208 }
5209
5211 bool sendcmpct_hb{false};
5213 vRecv >> sendcmpct_hb >> sendcmpct_version;
5214
5216 return;
5217 }
5218
5219 LOCK(cs_main);
5220 CNodeState *nodestate = State(pfrom.GetId());
5221 nodestate->m_provides_cmpctblocks = true;
5222 nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
5223 // save whether peer selects us as BIP152 high-bandwidth peer
5224 // (receiving sendcmpct(1) signals high-bandwidth,
5225 // sendcmpct(0) low-bandwidth)
5226 pfrom.m_bip152_highbandwidth_from = sendcmpct_hb;
5227 return;
5228 }
5229
5230 if (msg_type == NetMsgType::INV) {
5231 std::vector<CInv> vInv;
5232 vRecv >> vInv;
5233 if (vInv.size() > MAX_INV_SZ) {
5234 Misbehaving(*peer, 20,
5235 strprintf("inv message size = %u", vInv.size()));
5236 return;
5237 }
5238
5240
5242 std::optional<BlockHash> best_block;
5243
5244 auto logInv = [&](const CInv &inv, bool fAlreadyHave) {
5245 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(),
5246 fAlreadyHave ? "have" : "new", pfrom.GetId());
5247 };
5248
5249 for (CInv &inv : vInv) {
5250 if (interruptMsgProc) {
5251 return;
5252 }
5253
5254 if (inv.IsMsgStakeContender()) {
5255 // Ignore invs with stake contenders. This type is only used for
5256 // polling.
5257 continue;
5258 }
5259
5260 if (inv.IsMsgBlk()) {
5261 LOCK(cs_main);
5262 const bool fAlreadyHave = AlreadyHaveBlock(BlockHash(inv.hash));
5264
5265 BlockHash hash{inv.hash};
5266 UpdateBlockAvailability(pfrom.GetId(), hash);
5267 if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() &&
5268 !IsBlockRequested(hash)) {
5269 // Headers-first is the primary method of announcement on
5270 // the network. If a node fell back to sending blocks by
5271 // inv, it may be for a re-org, or because we haven't
5272 // completed initial headers sync. The final block hash
5273 // provided should be the highest, so send a getheaders and
5274 // then fetch the blocks we need to catch up.
5275 best_block = std::move(hash);
5276 }
5277
5278 continue;
5279 }
5280
5281 if (inv.IsMsgProof()) {
5282 if (!m_avalanche) {
5283 continue;
5284 }
5285 const avalanche::ProofId proofid(inv.hash);
5286 const bool fAlreadyHave = AlreadyHaveProof(proofid);
5288 AddKnownProof(*peer, proofid);
5289
5290 if (!fAlreadyHave && m_avalanche &&
5291 !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
5292 const bool preferred = isPreferredDownloadPeer(pfrom);
5293
5294 LOCK(cs_proofrequest);
5295 AddProofAnnouncement(pfrom, proofid, current_time,
5296 preferred);
5297 }
5298 continue;
5299 }
5300
5301 if (inv.IsMsgTx()) {
5302 LOCK(cs_main);
5303 const TxId txid(inv.hash);
5304 const bool fAlreadyHave =
5305 AlreadyHaveTx(txid, /*include_reconsiderable=*/true);
5307
5308 AddKnownTx(*peer, txid);
5309 if (reject_tx_invs) {
5311 "transaction (%s) inv sent in violation of "
5312 "protocol, disconnecting peer=%d\n",
5313 txid.ToString(), pfrom.GetId());
5314 pfrom.fDisconnect = true;
5315 return;
5316 } else if (!fAlreadyHave && !m_chainman.ActiveChainstate()
5317 .IsInitialBlockDownload()) {
5319 }
5320
5321 continue;
5322 }
5323
5325 "Unknown inv type \"%s\" received from peer=%d\n",
5326 inv.ToString(), pfrom.GetId());
5327 }
5328
5329 if (best_block) {
5330 // If we haven't started initial headers-sync with this peer, then
5331 // consider sending a getheaders now. On initial startup, there's a
5332 // reliability vs bandwidth tradeoff, where we are only trying to do
5333 // initial headers sync with one peer at a time, with a long
5334 // timeout (at which point, if the sync hasn't completed, we will
5335 // disconnect the peer and then choose another). In the meantime,
5336 // as new blocks are found, we are willing to add one new peer per
5337 // block to sync with as well, to sync quicker in the case where
5338 // our initial peer is unresponsive (but less bandwidth than we'd
5339 // use if we turned on sync with all peers).
5340 LOCK(::cs_main);
5341 CNodeState &state{*Assert(State(pfrom.GetId()))};
5342 if (state.fSyncStarted ||
5343 (!peer->m_inv_triggered_getheaders_before_sync &&
5346 pfrom, GetLocator(m_chainman.m_best_header), *peer)) {
5347 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n",
5348 m_chainman.m_best_header->nHeight,
5349 best_block->ToString(), pfrom.GetId());
5350 }
5351 if (!state.fSyncStarted) {
5352 peer->m_inv_triggered_getheaders_before_sync = true;
5353 // Update the last block hash that triggered a new headers
5354 // sync, so that we don't turn on headers sync with more
5355 // than 1 new peer every new block.
5357 }
5358 }
5359 }
5360
5361 return;
5362 }
5363
5365 std::vector<CInv> vInv;
5366 vRecv >> vInv;
5367 if (vInv.size() > MAX_INV_SZ) {
5368 Misbehaving(*peer, 20,
5369 strprintf("getdata message size = %u", vInv.size()));
5370 return;
5371 }
5372
5373 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n",
5374 vInv.size(), pfrom.GetId());
5375
5376 if (vInv.size() > 0) {
5377 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n",
5378 vInv[0].ToString(), pfrom.GetId());
5379 }
5380
5381 {
5382 LOCK(peer->m_getdata_requests_mutex);
5383 peer->m_getdata_requests.insert(peer->m_getdata_requests.end(),
5384 vInv.begin(), vInv.end());
5385 ProcessGetData(config, pfrom, *peer, interruptMsgProc);
5386 }
5387
5388 return;
5389 }
5390
5394 vRecv >> locator >> hashStop;
5395
5396 if (locator.vHave.size() > MAX_LOCATOR_SZ) {
5398 "getblocks locator size %lld > %d, disconnect peer=%d\n",
5399 locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
5400 pfrom.fDisconnect = true;
5401 return;
5402 }
5403
5404 // We might have announced the currently-being-connected tip using a
5405 // compact block, which resulted in the peer sending a getblocks
5406 // request, which we would otherwise respond to without the new block.
5407 // To avoid this situation we simply verify that we are on our best
5408 // known chain now. This is super overkill, but we handle it better
5409 // for getheaders requests, and there are no known nodes which support
5410 // compact blocks but still use getblocks to request blocks.
5411 {
5412 std::shared_ptr<const CBlock> a_recent_block;
5413 {
5414 LOCK(m_most_recent_block_mutex);
5416 }
5418 if (!m_chainman.ActiveChainstate().ActivateBestChain(
5419 state, a_recent_block, m_avalanche)) {
5420 LogPrint(BCLog::NET, "failed to activate chain (%s)\n",
5421 state.ToString());
5422 }
5423 }
5424
5425 LOCK(cs_main);
5426
5427 // Find the last block the caller has in the main chain
5428 const CBlockIndex *pindex =
5429 m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
5430
5431 // Send the rest of the chain
5432 if (pindex) {
5433 pindex = m_chainman.ActiveChain().Next(pindex);
5434 }
5435 int nLimit = 500;
5436 LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n",
5437 (pindex ? pindex->nHeight : -1),
5438 hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit,
5439 pfrom.GetId());
5440 for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) {
5441 if (pindex->GetBlockHash() == hashStop) {
5442 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n",
5443 pindex->nHeight, pindex->GetBlockHash().ToString());
5444 break;
5445 }
5446 // If pruning, don't inv blocks unless we have on disk and are
5447 // likely to still have for some reasonable time window (1 hour)
5448 // that block relay might require.
5449 const int nPrunedBlocksLikelyToHave =
5451 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
5452 if (m_chainman.m_blockman.IsPruneMode() &&
5453 (!pindex->nStatus.hasData() ||
5454 pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight -
5456 LogPrint(
5457 BCLog::NET,
5458 " getblocks stopping, pruned or too old block at %d %s\n",
5459 pindex->nHeight, pindex->GetBlockHash().ToString());
5460 break;
5461 }
5462 WITH_LOCK(
5463 peer->m_block_inv_mutex,
5464 peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
5465 if (--nLimit <= 0) {
5466 // When this block is requested, we'll send an inv that'll
5467 // trigger the peer to getblocks the next batch of inventory.
5468 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n",
5469 pindex->nHeight, pindex->GetBlockHash().ToString());
5470 WITH_LOCK(peer->m_block_inv_mutex, {
5471 peer->m_continuation_block = pindex->GetBlockHash();
5472 });
5473 break;
5474 }
5475 }
5476 return;
5477 }
5478
5481 vRecv >> req;
5482
5483 std::shared_ptr<const CBlock> recent_block;
5484 {
5485 LOCK(m_most_recent_block_mutex);
5488 }
5489 // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion
5490 }
5491 if (recent_block) {
5493 return;
5494 }
5495
5496 {
5497 LOCK(cs_main);
5498
5499 const CBlockIndex *pindex =
5500 m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
5501 if (!pindex || !pindex->nStatus.hasData()) {
5502 LogPrint(
5503 BCLog::NET,
5504 "Peer %d sent us a getblocktxn for a block we don't have\n",
5505 pfrom.GetId());
5506 return;
5507 }
5508
5509 if (pindex->nHeight >=
5510 m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
5511 CBlock block;
5512 const bool ret{
5513 m_chainman.m_blockman.ReadBlockFromDisk(block, *pindex)};
5514 assert(ret);
5515
5516 SendBlockTransactions(pfrom, *peer, block, req);
5517 return;
5518 }
5519 }
5520
5521 // If an older block is requested (should never happen in practice,
5522 // but can happen in tests) send a block response instead of a
5523 // blocktxn response. Sending a full block response instead of a
5524 // small blocktxn response is preferable in the case where a peer
5525 // might maliciously send lots of getblocktxn requests to trigger
5526 // expensive disk reads, because it will require the peer to
5527 // actually receive all the data read from disk over the network.
5529 "Peer %d sent us a getblocktxn for a block > %i deep\n",
5530 pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
5531 CInv inv;
5532 inv.type = MSG_BLOCK;
5533 inv.hash = req.blockhash;
5534 WITH_LOCK(peer->m_getdata_requests_mutex,
5535 peer->m_getdata_requests.push_back(inv));
5536 // The message processing loop will go around again (without pausing)
5537 // and we'll respond then (without cs_main)
5538 return;
5539 }
5540
5544 vRecv >> locator >> hashStop;
5545
5546 if (locator.vHave.size() > MAX_LOCATOR_SZ) {
5548 "getheaders locator size %lld > %d, disconnect peer=%d\n",
5549 locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
5550 pfrom.fDisconnect = true;
5551 return;
5552 }
5553
5554 if (m_chainman.m_blockman.LoadingBlocks()) {
5555 LogPrint(
5556 BCLog::NET,
5557 "Ignoring getheaders from peer=%d while importing/reindexing\n",
5558 pfrom.GetId());
5559 return;
5560 }
5561
5562 LOCK(cs_main);
5563
5564 // Note that if we were to be on a chain that forks from the
5565 // checkpointed chain, then serving those headers to a peer that has
5566 // seen the checkpointed chain would cause that peer to disconnect us.
5567 // Requiring that our chainwork exceed the minimum chainwork is a
5568 // protection against being fed a bogus chain when we started up for
5569 // the first time and getting partitioned off the honest network for
5570 // serving that chain to others.
5571 if (m_chainman.ActiveTip() == nullptr ||
5572 (m_chainman.ActiveTip()->nChainWork <
5573 m_chainman.MinimumChainWork() &&
5574 !pfrom.HasPermission(NetPermissionFlags::Download))) {
5576 "Ignoring getheaders from peer=%d because active chain "
5577 "has too little work; sending empty response\n",
5578 pfrom.GetId());
5579 // Just respond with an empty headers message, to tell the peer to
5580 // go away but not treat us as unresponsive.
5582 std::vector<CBlock>()));
5583 return;
5584 }
5585
5586 CNodeState *nodestate = State(pfrom.GetId());
5587 const CBlockIndex *pindex = nullptr;
5588 if (locator.IsNull()) {
5589 // If locator is null, return the hashStop block
5590 pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
5591 if (!pindex) {
5592 return;
5593 }
5594
5595 if (!BlockRequestAllowed(pindex)) {
5597 "%s: ignoring request from peer=%i for old block "
5598 "header that isn't in the main chain\n",
5599 __func__, pfrom.GetId());
5600 return;
5601 }
5602 } else {
5603 // Find the last block the caller has in the main chain
5604 pindex =
5605 m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator);
5606 if (pindex) {
5607 pindex = m_chainman.ActiveChain().Next(pindex);
5608 }
5609 }
5610
5611 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx
5612 // count at the end
5613 std::vector<CBlock> vHeaders;
5615 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n",
5616 (pindex ? pindex->nHeight : -1),
5617 hashStop.IsNull() ? "end" : hashStop.ToString(),
5618 pfrom.GetId());
5619 for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) {
5620 vHeaders.push_back(pindex->GetBlockHeader());
5621 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) {
5622 break;
5623 }
5624 }
5625 // pindex can be nullptr either if we sent
5626 // m_chainman.ActiveChain().Tip() OR if our peer has
5627 // m_chainman.ActiveChain().Tip() (and thus we are sending an empty
5628 // headers message). In both cases it's safe to update
5629 // pindexBestHeaderSent to be our tip.
5630 //
5631 // It is important that we simply reset the BestHeaderSent value here,
5632 // and not max(BestHeaderSent, newHeaderSent). We might have announced
5633 // the currently-being-connected tip using a compact block, which
5634 // resulted in the peer sending a headers request, which we respond to
5635 // without the new block. By resetting the BestHeaderSent, we ensure we
5636 // will re-announce the new block via headers (or compact blocks again)
5637 // in the SendMessages logic.
5638 nodestate->pindexBestHeaderSent =
5639 pindex ? pindex : m_chainman.ActiveChain().Tip();
5640 m_connman.PushMessage(&pfrom,
5642 return;
5643 }
5644
5645 if (msg_type == NetMsgType::TX) {
5646 if (RejectIncomingTxs(pfrom)) {
5648 "transaction sent in violation of protocol peer=%d\n",
5649 pfrom.GetId());
5650 pfrom.fDisconnect = true;
5651 return;
5652 }
5653
5654 // Stop processing the transaction early if we are still in IBD since we
5655 // don't have enough information to validate it yet. Sending unsolicited
5656 // transactions is not considered a protocol violation, so don't punish
5657 // the peer.
5658 if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
5659 return;
5660 }
5661
5663 vRecv >> ptx;
5664 const CTransaction &tx = *ptx;
5665 const TxId &txid = tx.GetId();
5666 AddKnownTx(*peer, txid);
5667
5668 bool shouldReconcileTx{false};
5669 {
5670 LOCK(cs_main);
5671
5672 m_txrequest.ReceivedResponse(pfrom.GetId(), txid);
5673
5674 if (AlreadyHaveTx(txid, /*include_reconsiderable=*/true)) {
5675 if (pfrom.HasPermission(NetPermissionFlags::ForceRelay)) {
5676 // Always relay transactions received from peers with
5677 // forcerelay permission, even if they were already in the
5678 // mempool, allowing the node to function as a gateway for
5679 // nodes hidden behind it.
5680 if (!m_mempool.exists(tx.GetId())) {
5681 LogPrintf(
5682 "Not relaying non-mempool transaction %s from "
5683 "forcerelay peer=%d\n",
5684 tx.GetId().ToString(), pfrom.GetId());
5685 } else {
5686 LogPrintf("Force relaying tx %s from peer=%d\n",
5687 tx.GetId().ToString(), pfrom.GetId());
5688 RelayTransaction(tx.GetId());
5689 }
5690 }
5691
5692 if (m_recent_rejects_package_reconsiderable.contains(txid)) {
5693 // When a transaction is already in
5694 // m_recent_rejects_package_reconsiderable, we shouldn't
5695 // submit it by itself again. However, look for a matching
5696 // child in the orphanage, as it is possible that they
5697 // succeed as a package.
5698 LogPrint(
5700 "found tx %s in reconsiderable rejects, looking for "
5701 "child in orphanage\n",
5702 txid.ToString());
5703 if (auto package_to_validate{
5704 Find1P1CPackage(ptx, pfrom.GetId())}) {
5706 m_chainman.ActiveChainstate(), m_mempool,
5707 package_to_validate->m_txns,
5708 /*test_accept=*/false)};
5710 "package evaluation for %s: %s (%s)\n",
5711 package_to_validate->ToString(),
5712 package_result.m_state.IsValid()
5713 ? "package accepted"
5714 : "package rejected",
5715 package_result.m_state.ToString());
5718 }
5719 }
5720 // If a tx is detected by m_recent_rejects it is ignored.
5721 // Because we haven't submitted the tx to our mempool, we won't
5722 // have computed a DoS score for it or determined exactly why we
5723 // consider it invalid.
5724 //
5725 // This means we won't penalize any peer subsequently relaying a
5726 // DoSy tx (even if we penalized the first peer who gave it to
5727 // us) because we have to account for m_recent_rejects showing
5728 // false positives. In other words, we shouldn't penalize a peer
5729 // if we aren't *sure* they submitted a DoSy tx.
5730 //
5731 // Note that m_recent_rejects doesn't just record DoSy or
5732 // invalid transactions, but any tx not accepted by the mempool,
5733 // which may be due to node policy (vs. consensus). So we can't
5734 // blanket penalize a peer simply for relaying a tx that our
5735 // m_recent_rejects has caught, regardless of false positives.
5736 return;
5737 }
5738
5739 const MempoolAcceptResult result =
5740 m_chainman.ProcessTransaction(ptx);
5741 const TxValidationState &state = result.m_state;
5742
5743 if (result.m_result_type ==
5745 ProcessValidTx(pfrom.GetId(), ptx);
5746 pfrom.m_last_tx_time = GetTime<std::chrono::seconds>();
5747 } else if (state.GetResult() ==
5749 // It may be the case that the orphans parents have all been
5750 // rejected.
5751 bool fRejectedParents = false;
5752
5753 // Deduplicate parent txids, so that we don't have to loop over
5754 // the same parent txid more than once down below.
5755 std::vector<TxId> unique_parents;
5756 unique_parents.reserve(tx.vin.size());
5757 for (const CTxIn &txin : tx.vin) {
5758 // We start with all parents, and then remove duplicates
5759 // below.
5760 unique_parents.push_back(txin.prevout.GetTxId());
5761 }
5762 std::sort(unique_parents.begin(), unique_parents.end());
5763 unique_parents.erase(
5764 std::unique(unique_parents.begin(), unique_parents.end()),
5765 unique_parents.end());
5766
5767 // Distinguish between parents in m_recent_rejects and
5768 // m_recent_rejects_package_reconsiderable. We can tolerate
5769 // having up to 1 parent in
5770 // m_recent_rejects_package_reconsiderable since we submit 1p1c
5771 // packages. However, fail immediately if any are in
5772 // m_recent_rejects.
5773 std::optional<TxId> rejected_parent_reconsiderable;
5774 for (const TxId &parent_txid : unique_parents) {
5775 if (m_recent_rejects.contains(parent_txid)) {
5776 fRejectedParents = true;
5777 break;
5778 }
5779
5781 parent_txid) &&
5782 !m_mempool.exists(parent_txid)) {
5783 // More than 1 parent in
5784 // m_recent_rejects_package_reconsiderable:
5785 // 1p1c will not be sufficient to accept this package,
5786 // so just give up here.
5787 if (rejected_parent_reconsiderable.has_value()) {
5788 fRejectedParents = true;
5789 break;
5790 }
5792 }
5793 }
5794 if (!fRejectedParents) {
5795 const auto current_time{
5797
5798 for (const TxId &parent_txid : unique_parents) {
5799 // FIXME: MSG_TX should use a TxHash, not a TxId.
5800 AddKnownTx(*peer, parent_txid);
5801 // Exclude m_recent_rejects_package_reconsiderable: the
5802 // missing parent may have been previously rejected for
5803 // being too low feerate. This orphan might CPFP it.
5805 /*include_reconsiderable=*/false)) {
5807 }
5808 }
5809
5810 // NO_THREAD_SAFETY_ANALYSIS because we can't annotate for
5811 // g_msgproc_mutex
5812 if (unsigned int nEvicted =
5813 m_mempool.withOrphanage(
5816 if (orphanage.AddTx(ptx,
5817 pfrom.GetId())) {
5818 AddToCompactExtraTransactions(ptx);
5819 }
5820 return orphanage.LimitTxs(
5821 m_opts.max_orphan_txs, m_rng);
5822 }) > 0) {
5824 "orphanage overflow, removed %u tx\n",
5825 nEvicted);
5826 }
5827
5828 // Once added to the orphan pool, a tx is considered
5829 // AlreadyHave, and we shouldn't request it anymore.
5830 m_txrequest.ForgetInvId(tx.GetId());
5831
5832 } else {
5834 "not keeping orphan with rejected parents %s\n",
5835 tx.GetId().ToString());
5836 // We will continue to reject this tx since it has rejected
5837 // parents so avoid re-requesting it from other peers.
5838 m_recent_rejects.insert(tx.GetId());
5839 m_txrequest.ForgetInvId(tx.GetId());
5840 }
5841 }
5842 if (state.IsInvalid()) {
5843 ProcessInvalidTx(pfrom.GetId(), ptx, state,
5844 /*maybe_add_extra_compact_tx=*/true);
5845 }
5846 // When a transaction fails for TX_PACKAGE_RECONSIDERABLE, look for
5847 // a matching child in the orphanage, as it is possible that they
5848 // succeed as a package.
5849 if (state.GetResult() ==
5851 LogPrint(
5853 "tx %s failed but reconsiderable, looking for child in "
5854 "orphanage\n",
5855 txid.ToString());
5856 if (auto package_to_validate{
5857 Find1P1CPackage(ptx, pfrom.GetId())}) {
5859 m_chainman.ActiveChainstate(), m_mempool,
5860 package_to_validate->m_txns, /*test_accept=*/false)};
5862 "package evaluation for %s: %s (%s)\n",
5863 package_to_validate->ToString(),
5864 package_result.m_state.IsValid()
5865 ? "package accepted"
5866 : "package rejected",
5867 package_result.m_state.ToString());
5870 }
5871 }
5872
5873 if (state.GetResult() ==
5875 // Once added to the conflicting pool, a tx is considered
5876 // AlreadyHave, and we shouldn't request it anymore.
5877 m_txrequest.ForgetInvId(tx.GetId());
5878
5879 unsigned int nEvicted{0};
5880 // NO_THREAD_SAFETY_ANALYSIS because of g_msgproc_mutex required
5881 // in the lambda for m_rng
5882 m_mempool.withConflicting(
5884 conflicting.AddTx(ptx, pfrom.GetId());
5885 nEvicted = conflicting.LimitTxs(
5886 m_opts.max_conflicting_txs, m_rng);
5887 shouldReconcileTx = conflicting.HaveTx(ptx->GetId());
5888 });
5889
5890 if (nEvicted > 0) {
5892 "conflicting pool overflow, removed %u tx\n",
5893 nEvicted);
5894 }
5895 }
5896 } // Release cs_main
5897
5898 if (m_avalanche && m_avalanche->m_preConsensus && shouldReconcileTx) {
5899 m_avalanche->addToReconcile(ptx);
5900 }
5901
5902 return;
5903 }
5904
5906 // Ignore cmpctblock received while importing
5907 if (m_chainman.m_blockman.LoadingBlocks()) {
5909 "Unexpected cmpctblock message received from peer %d\n",
5910 pfrom.GetId());
5911 return;
5912 }
5913
5915 try {
5916 vRecv >> cmpctblock;
5917 } catch (std::ios_base::failure &e) {
5918 // This block has non contiguous or overflowing indexes
5919 Misbehaving(*peer, 100, "cmpctblock-bad-indexes");
5920 return;
5921 }
5922
5923 bool received_new_header = false;
5924 const auto blockhash = cmpctblock.header.GetHash();
5925
5926 {
5927 LOCK(cs_main);
5928
5929 const CBlockIndex *prev_block =
5930 m_chainman.m_blockman.LookupBlockIndex(
5931 cmpctblock.header.hashPrevBlock);
5932 if (!prev_block) {
5933 // Doesn't connect (or is genesis), instead of DoSing in
5934 // AcceptBlockHeader, request deeper headers
5935 if (!m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
5937 pfrom, GetLocator(m_chainman.m_best_header), *peer);
5938 }
5939 return;
5940 }
5941 if (prev_block->nChainWork +
5944 // If we get a low-work header in a compact block, we can ignore
5945 // it.
5947 "Ignoring low-work compact block from peer %d\n",
5948 pfrom.GetId());
5949 return;
5950 }
5951
5952 if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) {
5953 received_new_header = true;
5954 }
5955 }
5956
5957 const CBlockIndex *pindex = nullptr;
5959 if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header},
5960 /*min_pow_checked=*/true, state,
5961 &pindex)) {
5962 if (state.IsInvalid()) {
5963 MaybePunishNodeForBlock(pfrom.GetId(), state,
5964 /*via_compact_block*/ true,
5965 "invalid header via cmpctblock");
5966 return;
5967 }
5968 }
5969
5970 if (received_new_header) {
5972 "Saw new cmpctblock header hash=%s peer=%d\n",
5973 blockhash.ToString(), pfrom.GetId());
5974 }
5975
5976 // When we succeed in decoding a block's txids from a cmpctblock
5977 // message we typically jump to the BLOCKTXN handling code, with a
5978 // dummy (empty) BLOCKTXN message, to re-use the logic there in
5979 // completing processing of the putative block (without cs_main).
5980 bool fProcessBLOCKTXN = false;
5982
5983 // If we end up treating this as a plain headers message, call that as
5984 // well
5985 // without cs_main.
5986 bool fRevertToHeaderProcessing = false;
5987
5988 // Keep a CBlock for "optimistic" compactblock reconstructions (see
5989 // below)
5990 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
5991 bool fBlockReconstructed = false;
5992
5993 {
5994 LOCK(cs_main);
5995 // If AcceptBlockHeader returned true, it set pindex
5996 assert(pindex);
5997 UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
5998
5999 CNodeState *nodestate = State(pfrom.GetId());
6000
6001 // If this was a new header with more work than our tip, update the
6002 // peer's last block announcement time
6003 if (received_new_header &&
6004 pindex->nChainWork >
6005 m_chainman.ActiveChain().Tip()->nChainWork) {
6006 nodestate->m_last_block_announcement = GetTime();
6007 }
6008
6009 if (pindex->nStatus.hasData()) {
6010 // Nothing to do here
6011 return;
6012 }
6013
6014 auto range_flight =
6015 mapBlocksInFlight.equal_range(pindex->GetBlockHash());
6016 size_t already_in_flight =
6017 std::distance(range_flight.first, range_flight.second);
6019
6020 // Multimap ensures ordering of outstanding requests. It's either
6021 // empty or first in line.
6022 bool first_in_flight =
6023 already_in_flight == 0 ||
6024 (range_flight.first->second.first == pfrom.GetId());
6025
6026 while (range_flight.first != range_flight.second) {
6027 if (range_flight.first->second.first == pfrom.GetId()) {
6029 break;
6030 }
6031 range_flight.first++;
6032 }
6033
6034 if (pindex->nChainWork <=
6035 m_chainman.ActiveChain()
6036 .Tip()
6037 ->nChainWork || // We know something better
6038 pindex->nTx != 0) {
6039 // We had this block at some point, but pruned it
6041 // We requested this block for some reason, but our mempool
6042 // will probably be useless so we just grab the block via
6043 // normal getdata.
6044 std::vector<CInv> vInv(1);
6045 vInv[0] = CInv(MSG_BLOCK, blockhash);
6046 m_connman.PushMessage(
6048 }
6049 return;
6050 }
6051
6052 // If we're not close to tip yet, give up and let parallel block
6053 // fetch work its magic.
6054 if (!already_in_flight && !CanDirectFetch()) {
6055 return;
6056 }
6057
6058 // We want to be a bit conservative just to be extra careful about
6059 // DoS possibilities in compact block processing...
6060 if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
6062 nodestate->vBlocksInFlight.size() <
6065 std::list<QueuedBlock>::iterator *queuedBlockIt = nullptr;
6066 if (!BlockRequested(config, pfrom.GetId(), *pindex,
6067 &queuedBlockIt)) {
6068 if (!(*queuedBlockIt)->partialBlock) {
6069 (*queuedBlockIt)
6070 ->partialBlock.reset(
6071 new PartiallyDownloadedBlock(config,
6072 &m_mempool));
6073 } else {
6074 // The block was already in flight using compact
6075 // blocks from the same peer.
6076 LogPrint(BCLog::NET, "Peer sent us compact block "
6077 "we were already syncing!\n");
6078 return;
6079 }
6080 }
6081
6082 PartiallyDownloadedBlock &partialBlock =
6083 *(*queuedBlockIt)->partialBlock;
6084 ReadStatus status =
6086 if (status == READ_STATUS_INVALID) {
6087 // Reset in-flight state in case Misbehaving does not
6088 // result in a disconnect
6090 pfrom.GetId());
6091 Misbehaving(*peer, 100, "invalid compact block");
6092 return;
6093 } else if (status == READ_STATUS_FAILED) {
6094 if (first_in_flight) {
6095 // Duplicate txindices, the block is now in-flight,
6096 // so just request it.
6097 std::vector<CInv> vInv(1);
6098 vInv[0] = CInv(MSG_BLOCK, blockhash);
6099 m_connman.PushMessage(
6100 &pfrom,
6102 } else {
6103 // Give up for this peer and wait for other peer(s)
6105 pfrom.GetId());
6106 }
6107 return;
6108 }
6109
6111 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
6112 if (!partialBlock.IsTxAvailable(i)) {
6113 req.indices.push_back(i);
6114 }
6115 }
6116 if (req.indices.empty()) {
6117 // Dirty hack to jump to BLOCKTXN code (TODO: move
6118 // message handling into their own functions)
6120 txn.blockhash = blockhash;
6121 blockTxnMsg << txn;
6122 fProcessBLOCKTXN = true;
6123 } else if (first_in_flight) {
6124 // We will try to round-trip any compact blocks we get
6125 // on failure, as long as it's first...
6126 req.blockhash = pindex->GetBlockHash();
6127 m_connman.PushMessage(
6128 &pfrom,
6130 } else if (pfrom.m_bip152_highbandwidth_to &&
6131 (!pfrom.IsInboundConn() ||
6132 IsBlockRequestedFromOutbound(blockhash) ||
6135 // ... or it's a hb relay peer and:
6136 // - peer is outbound, or
6137 // - we already have an outbound attempt in flight (so
6138 // we'll take what we can get), or
6139 // - it's not the final parallel download slot (which we
6140 // may reserve for first outbound)
6141 req.blockhash = pindex->GetBlockHash();
6142 m_connman.PushMessage(
6143 &pfrom,
6145 } else {
6146 // Give up for this peer and wait for other peer(s)
6148 pfrom.GetId());
6149 }
6150 } else {
6151 // This block is either already in flight from a different
6152 // peer, or this peer has too many blocks outstanding to
6153 // download from. Optimistically try to reconstruct anyway
6154 // since we might be able to without any round trips.
6155 PartiallyDownloadedBlock tempBlock(config, &m_mempool);
6156 ReadStatus status =
6158 if (status != READ_STATUS_OK) {
6159 // TODO: don't ignore failures
6160 return;
6161 }
6162 std::vector<CTransactionRef> dummy;
6163 status = tempBlock.FillBlock(*pblock, dummy);
6164 if (status == READ_STATUS_OK) {
6165 fBlockReconstructed = true;
6166 }
6167 }
6168 } else {
6170 // We requested this block, but its far into the future, so
6171 // our mempool will probably be useless - request the block
6172 // normally.
6173 std::vector<CInv> vInv(1);
6174 vInv[0] = CInv(MSG_BLOCK, blockhash);
6175 m_connman.PushMessage(
6177 return;
6178 } else {
6179 // If this was an announce-cmpctblock, we want the same
6180 // treatment as a header message.
6182 }
6183 }
6184 } // cs_main
6185
6186 if (fProcessBLOCKTXN) {
6187 return ProcessMessage(config, pfrom, NetMsgType::BLOCKTXN,
6188 blockTxnMsg, time_received, interruptMsgProc);
6189 }
6190
6192 // Headers received from HB compact block peers are permitted to be
6193 // relayed before full validation (see BIP 152), so we don't want to
6194 // disconnect the peer if the header turns out to be for an invalid
6195 // block. Note that if a peer tries to build on an invalid chain,
6196 // that will be detected and the peer will be banned.
6197 return ProcessHeadersMessage(config, pfrom, *peer,
6198 {cmpctblock.header},
6199 /*via_compact_block=*/true);
6200 }
6201
6202 if (fBlockReconstructed) {
6203 // If we got here, we were able to optimistically reconstruct a
6204 // block that is in flight from some other peer.
6205 {
6206 LOCK(cs_main);
6207 mapBlockSource.emplace(pblock->GetHash(),
6208 std::make_pair(pfrom.GetId(), false));
6209 }
6210 // Setting force_processing to true means that we bypass some of
6211 // our anti-DoS protections in AcceptBlock, which filters
6212 // unrequested blocks that might be trying to waste our resources
6213 // (eg disk space). Because we only try to reconstruct blocks when
6214 // we're close to caught up (via the CanDirectFetch() requirement
6215 // above, combined with the behavior of not requesting blocks until
6216 // we have a chain with at least the minimum chain work), and we
6217 // ignore compact blocks with less work than our tip, it is safe to
6218 // treat reconstructed compact blocks as having been requested.
6219 ProcessBlock(config, pfrom, pblock, /*force_processing=*/true,
6220 /*min_pow_checked=*/true);
6221 // hold cs_main for CBlockIndex::IsValid()
6222 LOCK(cs_main);
6223 if (pindex->IsValid(BlockValidity::TRANSACTIONS)) {
6224 // Clear download state for this block, which is in process from
6225 // some other peer. We do this after calling. ProcessNewBlock so
6226 // that a malleated cmpctblock announcement can't be used to
6227 // interfere with block relay.
6228 RemoveBlockRequest(pblock->GetHash(), std::nullopt);
6229 }
6230 }
6231 return;
6232 }
6233
6235 // Ignore blocktxn received while importing
6236 if (m_chainman.m_blockman.LoadingBlocks()) {
6238 "Unexpected blocktxn message received from peer %d\n",
6239 pfrom.GetId());
6240 return;
6241 }
6242
6244 vRecv >> resp;
6245
6246 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6247 bool fBlockRead = false;
6248 {
6249 LOCK(cs_main);
6250
6251 auto range_flight = mapBlocksInFlight.equal_range(resp.blockhash);
6252 size_t already_in_flight =
6253 std::distance(range_flight.first, range_flight.second);
6255
6256 // Multimap ensures ordering of outstanding requests. It's either
6257 // empty or first in line.
6258 bool first_in_flight =
6259 already_in_flight == 0 ||
6260 (range_flight.first->second.first == pfrom.GetId());
6261
6262 while (range_flight.first != range_flight.second) {
6263 auto [node_id, block_it] = range_flight.first->second;
6264 if (node_id == pfrom.GetId() && block_it->partialBlock) {
6266 break;
6267 }
6268 range_flight.first++;
6269 }
6270
6273 "Peer %d sent us block transactions for block "
6274 "we weren't expecting\n",
6275 pfrom.GetId());
6276 return;
6277 }
6278
6279 PartiallyDownloadedBlock &partialBlock =
6280 *range_flight.first->second.second->partialBlock;
6281 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
6282 if (status == READ_STATUS_INVALID) {
6283 // Reset in-flight state in case of Misbehaving does not
6284 // result in a disconnect.
6285 RemoveBlockRequest(resp.blockhash, pfrom.GetId());
6287 *peer, 100,
6288 "invalid compact block/non-matching block transactions");
6289 return;
6290 } else if (status == READ_STATUS_FAILED) {
6291 if (first_in_flight) {
6292 // Might have collided, fall back to getdata now :(
6293 std::vector<CInv> invs;
6294 invs.push_back(CInv(MSG_BLOCK, resp.blockhash));
6295 m_connman.PushMessage(
6296 &pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
6297 } else {
6298 RemoveBlockRequest(resp.blockhash, pfrom.GetId());
6299 LogPrint(
6300 BCLog::NET,
6301 "Peer %d sent us a compact block but it failed to "
6302 "reconstruct, waiting on first download to complete\n",
6303 pfrom.GetId());
6304 return;
6305 }
6306 } else {
6307 // Block is either okay, or possibly we received
6308 // READ_STATUS_CHECKBLOCK_FAILED.
6309 // Note that CheckBlock can only fail for one of a few reasons:
6310 // 1. bad-proof-of-work (impossible here, because we've already
6311 // accepted the header)
6312 // 2. merkleroot doesn't match the transactions given (already
6313 // caught in FillBlock with READ_STATUS_FAILED, so
6314 // impossible here)
6315 // 3. the block is otherwise invalid (eg invalid coinbase,
6316 // block is too big, too many sigChecks, etc).
6317 // So if CheckBlock failed, #3 is the only possibility.
6318 // Under BIP 152, we don't DoS-ban unless proof of work is
6319 // invalid (we don't require all the stateless checks to have
6320 // been run). This is handled below, so just treat this as
6321 // though the block was successfully read, and rely on the
6322 // handling in ProcessNewBlock to ensure the block index is
6323 // updated, etc.
6324
6325 // it is now an empty pointer
6326 RemoveBlockRequest(resp.blockhash, pfrom.GetId());
6327 fBlockRead = true;
6328 // mapBlockSource is used for potentially punishing peers and
6329 // updating which peers send us compact blocks, so the race
6330 // between here and cs_main in ProcessNewBlock is fine.
6331 // BIP 152 permits peers to relay compact blocks after
6332 // validating the header only; we should not punish peers
6333 // if the block turns out to be invalid.
6334 mapBlockSource.emplace(resp.blockhash,
6335 std::make_pair(pfrom.GetId(), false));
6336 }
6337 } // Don't hold cs_main when we call into ProcessNewBlock
6338 if (fBlockRead) {
6339 // Since we requested this block (it was in mapBlocksInFlight),
6340 // force it to be processed, even if it would not be a candidate for
6341 // new tip (missing previous block, chain not long enough, etc)
6342 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
6343 // disk-space attacks), but this should be safe due to the
6344 // protections in the compact block handler -- see related comment
6345 // in compact block optimistic reconstruction handling.
6346 ProcessBlock(config, pfrom, pblock, /*force_processing=*/true,
6347 /*min_pow_checked=*/true);
6348 }
6349 return;
6350 }
6351
6353 // Ignore headers received while importing
6354 if (m_chainman.m_blockman.LoadingBlocks()) {
6356 "Unexpected headers message received from peer %d\n",
6357 pfrom.GetId());
6358 return;
6359 }
6360
6361 // Assume that this is in response to any outstanding getheaders
6362 // request we may have sent, and clear out the time of our last request
6363 peer->m_last_getheaders_timestamp = {};
6364
6365 std::vector<CBlockHeader> headers;
6366
6367 // Bypass the normal CBlock deserialization, as we don't want to risk
6368 // deserializing 2000 full blocks.
6369 unsigned int nCount = ReadCompactSize(vRecv);
6371 Misbehaving(*peer, 20,
6372 strprintf("too-many-headers: headers message size = %u",
6373 nCount));
6374 return;
6375 }
6376 headers.resize(nCount);
6377 for (unsigned int n = 0; n < nCount; n++) {
6378 vRecv >> headers[n];
6379 // Ignore tx count; assume it is 0.
6380 ReadCompactSize(vRecv);
6381 }
6382
6383 ProcessHeadersMessage(config, pfrom, *peer, std::move(headers),
6384 /*via_compact_block=*/false);
6385
6386 // Check if the headers presync progress needs to be reported to
6387 // validation. This needs to be done without holding the
6388 // m_headers_presync_mutex lock.
6389 if (m_headers_presync_should_signal.exchange(false)) {
6390 HeadersPresyncStats stats;
6391 {
6392 LOCK(m_headers_presync_mutex);
6393 auto it =
6395 if (it != m_headers_presync_stats.end()) {
6396 stats = it->second;
6397 }
6398 }
6399 if (stats.second) {
6400 m_chainman.ReportHeadersPresync(
6401 stats.first, stats.second->first, stats.second->second);
6402 }
6403 }
6404
6405 return;
6406 }
6407
6408 if (msg_type == NetMsgType::BLOCK) {
6409 // Ignore block received while importing
6410 if (m_chainman.m_blockman.LoadingBlocks()) {
6412 "Unexpected block message received from peer %d\n",
6413 pfrom.GetId());
6414 return;
6415 }
6416
6417 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6418 vRecv >> *pblock;
6419
6420 LogPrint(BCLog::NET, "received block %s peer=%d\n",
6421 pblock->GetHash().ToString(), pfrom.GetId());
6422
6423 // Process all blocks from whitelisted peers, even if not requested,
6424 // unless we're still syncing with the network. Such an unrequested
6425 // block may still be processed, subject to the conditions in
6426 // AcceptBlock().
6427 bool forceProcessing =
6428 pfrom.HasPermission(NetPermissionFlags::NoBan) &&
6429 !m_chainman.ActiveChainstate().IsInitialBlockDownload();
6430 const BlockHash hash = pblock->GetHash();
6431 bool min_pow_checked = false;
6432 {
6433 LOCK(cs_main);
6434 // Always process the block if we requested it, since we may
6435 // need it even when it's not a candidate for a new best tip.
6437 RemoveBlockRequest(hash, pfrom.GetId());
6438 // mapBlockSource is only used for punishing peers and setting
6439 // which peers send us compact blocks, so the race between here and
6440 // cs_main in ProcessNewBlock is fine.
6441 mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
6442
6443 // Check work on this block against our anti-dos thresholds.
6444 const CBlockIndex *prev_block =
6445 m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock);
6446 if (prev_block &&
6447 prev_block->nChainWork +
6448 CalculateHeadersWork({pblock->GetBlockHeader()}) >=
6450 min_pow_checked = true;
6451 }
6452 }
6454 return;
6455 }
6456
6458 if (!m_avalanche) {
6459 return;
6460 }
6461 {
6462 LOCK(pfrom.cs_avalanche_pubkey);
6463 if (pfrom.m_avalanche_pubkey.has_value()) {
6464 LogPrint(
6466 "Ignoring avahello from peer %d: already in our node set\n",
6467 pfrom.GetId());
6468 return;
6469 }
6470
6471 avalanche::Delegation delegation;
6472 vRecv >> delegation;
6473
6474 // A delegation with an all zero limited id indicates that the peer
6475 // has no proof, so we're done.
6476 if (delegation.getLimitedProofId() != uint256::ZERO) {
6478 CPubKey pubkey;
6479 if (!delegation.verify(state, pubkey)) {
6480 Misbehaving(*peer, 100, "invalid-delegation");
6481 return;
6482 }
6483 pfrom.m_avalanche_pubkey = std::move(pubkey);
6484
6486 sighasher << delegation.getId();
6487 sighasher << pfrom.nRemoteHostNonce;
6488 sighasher << pfrom.GetLocalNonce();
6489 sighasher << pfrom.nRemoteExtraEntropy;
6490 sighasher << pfrom.GetLocalExtraEntropy();
6491
6493 vRecv >> sig;
6494 if (!(*pfrom.m_avalanche_pubkey)
6495 .VerifySchnorr(sighasher.GetHash(), sig)) {
6496 Misbehaving(*peer, 100, "invalid-avahello-signature");
6497 return;
6498 }
6499
6500 // If we don't know this proof already, add it to the tracker so
6501 // it can be requested.
6502 const avalanche::ProofId proofid(delegation.getProofId());
6503 if (!AlreadyHaveProof(proofid)) {
6504 const bool preferred = isPreferredDownloadPeer(pfrom);
6505 LOCK(cs_proofrequest);
6506 AddProofAnnouncement(pfrom, proofid,
6508 preferred);
6509 }
6510
6511 // Don't check the return value. If it fails we probably don't
6512 // know about the proof yet.
6513 m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
6514 return pm.addNode(pfrom.GetId(), proofid);
6515 });
6516 }
6517
6518 pfrom.m_avalanche_enabled = true;
6519 }
6520
6521 // Send getavaaddr and getavaproofs to our avalanche outbound or
6522 // manual connections
6523 if (!pfrom.IsInboundConn()) {
6524 m_connman.PushMessage(&pfrom,
6526 WITH_LOCK(peer->m_addr_token_bucket_mutex,
6527 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
6528
6529 if (peer->m_proof_relay &&
6530 !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
6531 m_connman.PushMessage(&pfrom,
6533 peer->m_proof_relay->compactproofs_requested = true;
6534 }
6535 }
6536
6537 return;
6538 }
6539
6541 if (!m_avalanche) {
6542 return;
6543 }
6544 const auto now = Now<SteadyMilliseconds>();
6545
6546 const auto last_poll = pfrom.m_last_poll;
6547 pfrom.m_last_poll = now;
6548
6549 if (now <
6550 last_poll + std::chrono::milliseconds(m_opts.avalanche_cooldown)) {
6552 "Ignoring repeated avapoll from peer %d: cooldown not "
6553 "elapsed\n",
6554 pfrom.GetId());
6555 return;
6556 }
6557
6558 const bool quorum_established = m_avalanche->isQuorumEstablished();
6559
6560 uint64_t round;
6561 Unserialize(vRecv, round);
6562
6563 unsigned int nCount = ReadCompactSize(vRecv);
6566 *peer, 20,
6567 strprintf("too-many-ava-poll: poll message size = %u", nCount));
6568 return;
6569 }
6570
6571 std::vector<avalanche::Vote> votes;
6572 votes.reserve(nCount);
6573
6574 for (unsigned int n = 0; n < nCount; n++) {
6575 CInv inv;
6576 vRecv >> inv;
6577
6578 // Default vote for unknown inv type
6579 uint32_t vote = -1;
6580
6581 // We don't vote definitively until we have an established quorum
6582 if (!quorum_established) {
6583 votes.emplace_back(vote, inv.hash);
6584 continue;
6585 }
6586
6587 // If inv's type is known, get a vote for its hash
6588 switch (inv.type) {
6589 case MSG_TX: {
6590 if (m_opts.avalanche_preconsensus) {
6592 TxId(inv.hash)));
6593 }
6594 } break;
6595 case MSG_BLOCK: {
6597 BlockHash(inv.hash)));
6598 } break;
6599 case MSG_AVA_PROOF: {
6601 *m_avalanche, avalanche::ProofId(inv.hash));
6602 } break;
6604 if (m_opts.avalanche_staking_preconsensus) {
6605 vote = m_avalanche->getStakeContenderStatus(
6607 }
6608 } break;
6609 default: {
6611 "poll inv type %d unknown from peer=%d\n",
6612 inv.type, pfrom.GetId());
6613 }
6614 }
6615
6616 votes.emplace_back(vote, inv.hash);
6617 }
6618
6619 // Send the query to the node.
6620 m_avalanche->sendResponse(
6621 &pfrom, avalanche::Response(round, m_opts.avalanche_cooldown,
6622 std::move(votes)));
6623 return;
6624 }
6625
6627 if (!m_avalanche) {
6628 return;
6629 }
6630 // As long as QUIC is not implemented, we need to sign response and
6631 // verify response's signatures in order to avoid any manipulation of
6632 // messages at the transport level.
6635 verifier >> response;
6636
6638 vRecv >> sig;
6639
6640 {
6641 LOCK(pfrom.cs_avalanche_pubkey);
6642 if (!pfrom.m_avalanche_pubkey.has_value() ||
6643 !(*pfrom.m_avalanche_pubkey)
6644 .VerifySchnorr(verifier.GetHash(), sig)) {
6645 Misbehaving(*peer, 100, "invalid-ava-response-signature");
6646 return;
6647 }
6648 }
6649
6650 auto now = GetTime<std::chrono::seconds>();
6651
6652 std::vector<avalanche::VoteItemUpdate> updates;
6653 int banscore{0};
6654 std::string error;
6655 if (!m_avalanche->registerVotes(pfrom.GetId(), response, updates,
6656 banscore, error)) {
6657 if (banscore > 0) {
6658 // If the banscore was set, just increase the node ban score
6659 Misbehaving(*peer, banscore, error);
6660 return;
6661 }
6662
6663 // Otherwise the node may have got a network issue. Increase the
6664 // fault counter instead and only ban if we reached a threshold.
6665 // This allows for fault tolerance should there be a temporary
6666 // outage while still preventing DoS'ing behaviors, as the counter
6667 // is reset if no fault occured over some time period.
6668 pfrom.m_avalanche_message_fault_counter++;
6669 pfrom.m_avalanche_last_message_fault = now;
6670
6671 // Allow up to 12 messages before increasing the ban score. Since
6672 // the queries are cleared after 10s, this is at least 2 minutes
6673 // of network outage tolerance over the 1h window.
6674 if (pfrom.m_avalanche_message_fault_counter > 12) {
6675 Misbehaving(*peer, 2, error);
6676 return;
6677 }
6678 }
6679
6680 // If no fault occurred within the last hour, reset the fault counter
6681 if (now > (pfrom.m_avalanche_last_message_fault.load() + 1h)) {
6682 pfrom.m_avalanche_message_fault_counter = 0;
6683 }
6684
6685 pfrom.invsVoted(response.GetVotes().size());
6686
6687 auto logVoteUpdate = [](const auto &voteUpdate,
6688 const std::string &voteItemTypeStr,
6689 const auto &voteItemId) {
6690 std::string voteOutcome;
6691 bool alwaysPrint = false;
6692 switch (voteUpdate.getStatus()) {
6694 voteOutcome = "invalidated";
6695 alwaysPrint = true;
6696 break;
6698 voteOutcome = "rejected";
6699 break;
6701 voteOutcome = "accepted";
6702 break;
6704 voteOutcome = "finalized";
6705 alwaysPrint = true;
6706 break;
6708 voteOutcome = "stalled";
6709 alwaysPrint = true;
6710 break;
6711
6712 // No default case, so the compiler can warn about missing
6713 // cases
6714 }
6715
6716 if (alwaysPrint) {
6717 LogPrintf("Avalanche %s %s %s\n", voteOutcome, voteItemTypeStr,
6718 voteItemId.ToString());
6719 } else {
6720 // Only print these messages if -debug=avalanche is set
6721 LogPrint(BCLog::AVALANCHE, "Avalanche %s %s %s\n", voteOutcome,
6722 voteItemTypeStr, voteItemId.ToString());
6723 }
6724 };
6725
6726 bool shouldActivateBestChain = false;
6727
6728 for (const auto &u : updates) {
6729 const avalanche::AnyVoteItem &item = u.getVoteItem();
6730
6731 // Don't use a visitor here as we want to ignore unsupported item
6732 // types. This comes in handy when adding new types.
6733 if (auto pitem = std::get_if<const avalanche::ProofRef>(&item)) {
6734 avalanche::ProofRef proof = *pitem;
6735 const avalanche::ProofId &proofid = proof->getId();
6736
6737 logVoteUpdate(u, "proof", proofid);
6738
6739 auto rejectionMode =
6742 switch (u.getStatus()) {
6744 m_avalanche->withPeerManager(
6746 pm.setInvalid(proofid);
6747 });
6748 // Fallthrough
6750 // Invalidate mode removes the proof from all proof
6751 // pools
6754 // Fallthrough
6756 if (!m_avalanche->withPeerManager(
6758 return pm.rejectProof(proofid,
6759 rejectionMode);
6760 })) {
6762 "ERROR: Failed to reject proof: %s\n",
6763 proofid.GetHex());
6764 }
6765 break;
6767 nextCooldownTimePoint += std::chrono::seconds(
6768 m_opts.avalanche_peer_replacement_cooldown);
6770 if (!m_avalanche->withPeerManager(
6772 pm.registerProof(
6773 proof,
6774 avalanche::PeerManager::
6775 RegistrationMode::FORCE_ACCEPT);
6776 return pm.forPeer(
6777 proofid,
6778 [&](const avalanche::Peer &peer) {
6779 pm.updateNextPossibleConflictTime(
6780 peer.peerid,
6781 nextCooldownTimePoint);
6782 if (u.getStatus() ==
6783 avalanche::VoteStatus::
6784 Finalized) {
6785 pm.setFinalized(peer.peerid);
6786 }
6787 // Only fail if the peer was not
6788 // created
6789 return true;
6790 });
6791 })) {
6793 "ERROR: Failed to accept proof: %s\n",
6794 proofid.GetHex());
6795 }
6796 break;
6797 }
6798 }
6799
6800 auto getBlockFromIndex = [this](const CBlockIndex *pindex) {
6801 // First check if the block is cached before reading
6802 // from disk.
6803 std::shared_ptr<const CBlock> pblock = WITH_LOCK(
6804 m_most_recent_block_mutex, return m_most_recent_block);
6805
6806 if (!pblock || pblock->GetHash() != pindex->GetBlockHash()) {
6807 std::shared_ptr<CBlock> pblockRead =
6808 std::make_shared<CBlock>();
6809 if (!m_chainman.m_blockman.ReadBlockFromDisk(*pblockRead,
6810 *pindex)) {
6811 assert(!"cannot load block from disk");
6812 }
6814 }
6815 return pblock;
6816 };
6817
6818 if (auto pitem = std::get_if<const CBlockIndex *>(&item)) {
6819 CBlockIndex *pindex = const_cast<CBlockIndex *>(*pitem);
6820
6822
6823 logVoteUpdate(u, "block", pindex->GetBlockHash());
6824
6825 switch (u.getStatus()) {
6828 m_chainman.ActiveChainstate().ParkBlock(state, pindex);
6829 if (!state.IsValid()) {
6830 LogPrintf("ERROR: Database error: %s\n",
6831 state.GetRejectReason());
6832 return;
6833 }
6834 } break;
6837 m_chainman.ActiveChainstate().ParkBlock(state, pindex);
6838 if (!state.IsValid()) {
6839 LogPrintf("ERROR: Database error: %s\n",
6840 state.GetRejectReason());
6841 return;
6842 }
6843
6844 auto pblock = getBlockFromIndex(pindex);
6845 assert(pblock);
6846
6847 WITH_LOCK(cs_main, GetMainSignals().BlockInvalidated(
6848 pindex, pblock));
6849 } break;
6851 LOCK(cs_main);
6852 m_chainman.ActiveChainstate().UnparkBlock(pindex);
6853 } break;
6855 {
6856 LOCK(cs_main);
6857 m_chainman.ActiveChainstate().UnparkBlock(pindex);
6858 }
6859
6860 if (m_opts.avalanche_preconsensus) {
6861 auto pblock = getBlockFromIndex(pindex);
6862 assert(pblock);
6863
6864 LOCK(m_mempool.cs);
6865 m_mempool.removeForFinalizedBlock(pblock->vtx);
6866 }
6867
6868 m_chainman.ActiveChainstate().AvalancheFinalizeBlock(
6869 pindex, *m_avalanche);
6870 } break;
6872 // Fall back on Nakamoto consensus in the absence of
6873 // Avalanche votes for other competing or descendant
6874 // blocks.
6875 break;
6876 }
6877 }
6878
6879 if (!m_opts.avalanche_preconsensus) {
6880 continue;
6881 }
6882
6883 if (auto pitem = std::get_if<const CTransactionRef>(&item)) {
6884 const CTransactionRef tx = *pitem;
6885 assert(tx != nullptr);
6886
6887 const TxId &txid = tx->GetId();
6888 logVoteUpdate(u, "tx", txid);
6889
6890 switch (u.getStatus()) {
6892 // Remove from the mempool and the finalized tree, as
6893 // well as all the children txs. Note that removal from
6894 // the finalized tree is only a safety net and should
6895 // never happen.
6896 LOCK2(cs_main, m_mempool.cs);
6897 if (m_mempool.exists(txid)) {
6898 m_mempool.removeRecursive(
6900
6901 std::vector<CTransactionRef> conflictingTxs =
6902 m_mempool.withConflicting(
6903 [&tx](const TxConflicting &conflicting) {
6904 return conflicting.GetConflictTxs(tx);
6905 });
6906
6907 if (conflictingTxs.size() > 0) {
6908 // Pull the first tx only, erase the others so
6909 // they can be re-downloaded if needed.
6910 auto result = m_chainman.ProcessTransaction(
6911 conflictingTxs[0]);
6912 assert(result.m_state.IsValid());
6913 }
6914
6915 m_mempool.withConflicting(
6917 &tx](TxConflicting &conflicting) {
6918 for (const auto &conflictingTx :
6920 conflicting.EraseTx(
6921 conflictingTx->GetId());
6922 }
6923
6924 // Note that we don't store the descendants,
6925 // which should be re-downloaded. This could
6926 // be optimized but we will have to manage
6927 // the topological ordering.
6928 conflicting.AddTx(tx, NO_NODE);
6929 });
6930 }
6931
6932 break;
6933 }
6935 m_mempool.withConflicting(
6936 [&txid](TxConflicting &conflicting) {
6937 conflicting.EraseTx(txid);
6938 });
6939 WITH_LOCK(cs_main, m_recent_rejects.insert(txid));
6940 break;
6941 }
6943 // fallthrough
6945 {
6946 LOCK2(cs_main, m_mempool.cs);
6947 if (m_mempool.withConflicting(
6948 [&txid](const TxConflicting &conflicting) {
6949 return conflicting.HaveTx(txid);
6950 })) {
6951 // Swap conflicting txs from/to the mempool
6952 std::vector<CTransactionRef>
6954 for (const auto &txin : tx->vin) {
6955 // Find the conflicting txs
6957 m_mempool.GetConflictTx(
6958 txin.prevout)) {
6959 mempool_conflicting_txs.push_back(
6960 std::move(conflict));
6961 }
6962 }
6963 m_mempool.removeConflicts(*tx);
6964
6965 auto result = m_chainman.ProcessTransaction(tx);
6966 assert(result.m_state.IsValid());
6967
6968 m_mempool.withConflicting(
6969 [&txid, &mempool_conflicting_txs](
6971 conflicting.EraseTx(txid);
6972 // Store the first tx only, the others
6973 // can be re-downloaded if needed.
6974 if (mempool_conflicting_txs.size() >
6975 0) {
6976 conflicting.AddTx(
6977 mempool_conflicting_txs[0],
6978 NO_NODE);
6979 }
6980 });
6981 }
6982 }
6983
6984 if (u.getStatus() == avalanche::VoteStatus::Finalized) {
6985 LOCK2(cs_main, m_mempool.cs);
6986 auto it = m_mempool.GetIter(txid);
6987 if (!it.has_value()) {
6988 LogPrint(
6990 "Error: finalized tx (%s) is not in the "
6991 "mempool\n",
6992 txid.ToString());
6993 break;
6994 }
6995
6996 m_mempool.setAvalancheFinalized(**it);
6997
6998 // NO_THREAD_SAFETY_ANALYSIS because
6999 // m_recent_rejects requires cs_main in the lambda
7000 m_mempool.withConflicting(
7003 std::vector<CTransactionRef>
7005 conflicting.GetConflictTxs(tx);
7006 for (const auto &conflictingTx :
7008 m_recent_rejects.insert(
7009 conflictingTx->GetId());
7010 conflicting.EraseTx(
7011 conflictingTx->GetId());
7012 }
7013 });
7014 }
7015
7016 break;
7017 }
7019 break;
7020 }
7021 }
7022 }
7023
7026 if (!m_chainman.ActiveChainstate().ActivateBestChain(
7027 state, /*pblock=*/nullptr, m_avalanche)) {
7028 LogPrintf("failed to activate chain (%s)\n", state.ToString());
7029 }
7030 }
7031
7032 return;
7033 }
7034
7036 if (!m_avalanche) {
7037 return;
7038 }
7039 auto proof = RCUPtr<avalanche::Proof>::make();
7040 vRecv >> *proof;
7041
7042 ReceivedAvalancheProof(pfrom, *peer, proof);
7043
7044 return;
7045 }
7046
7048 if (!m_avalanche) {
7049 return;
7050 }
7051 if (peer->m_proof_relay == nullptr) {
7052 return;
7053 }
7054
7055 peer->m_proof_relay->lastSharedProofsUpdate =
7057
7058 peer->m_proof_relay->sharedProofs =
7059 m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
7060 return pm.getShareableProofsSnapshot();
7061 });
7062
7064 peer->m_proof_relay->sharedProofs);
7065 m_connman.PushMessage(
7067
7068 return;
7069 }
7070
7072 if (!m_avalanche) {
7073 return;
7074 }
7075 if (peer->m_proof_relay == nullptr) {
7076 return;
7077 }
7078
7079 // Only process the compact proofs if we requested them
7080 if (!peer->m_proof_relay->compactproofs_requested) {
7081 LogPrint(BCLog::AVALANCHE, "Ignoring unsollicited avaproofs\n");
7082 return;
7083 }
7084 peer->m_proof_relay->compactproofs_requested = false;
7085
7087 try {
7088 vRecv >> compactProofs;
7089 } catch (std::ios_base::failure &e) {
7090 // This compact proofs have non contiguous or overflowing indexes
7091 Misbehaving(*peer, 100, "avaproofs-bad-indexes");
7092 return;
7093 }
7094
7095 // If there are prefilled proofs, process them first
7096 std::set<uint32_t> prefilledIndexes;
7097 for (const auto &prefilledProof : compactProofs.getPrefilledProofs()) {
7098 if (!ReceivedAvalancheProof(pfrom, *peer, prefilledProof.proof)) {
7099 // If we got an invalid proof, the peer is getting banned and we
7100 // can bail out.
7101 return;
7102 }
7103 }
7104
7105 // If there is no shortid, avoid parsing/responding/accounting for the
7106 // message.
7107 if (compactProofs.getShortIDs().size() == 0) {
7108 return;
7109 }
7110
7111 // To determine the chance that the number of entries in a bucket
7112 // exceeds N, we use the fact that the number of elements in a single
7113 // bucket is binomially distributed (with n = the number of shorttxids
7114 // S, and p = 1 / the number of buckets), that in the worst case the
7115 // number of buckets is equal to S (due to std::unordered_map having a
7116 // default load factor of 1.0), and that the chance for any bucket to
7117 // exceed N elements is at most buckets * (the chance that any given
7118 // bucket is above N elements). Thus:
7119 // P(max_elements_per_bucket > N) <=
7120 // S * (1 - cdf(binomial(n=S,p=1/S), N))
7121 // If we assume up to 21000000, allowing 15 elements per bucket should
7122 // only fail once per ~2.5 million avaproofs transfers (per peer and
7123 // connection).
7124 // TODO re-evaluate the bucket count to a more realistic value.
7125 // TODO: In the case of a shortid-collision, we should request all the
7126 // proofs which collided. For now, we only request one, which is not
7127 // that bad considering this event is expected to be very rare.
7128 auto shortIdProcessor =
7130 compactProofs.getShortIDs(), 15);
7131
7132 if (shortIdProcessor.hasOutOfBoundIndex()) {
7133 // This should be catched by deserialization, but catch it here as
7134 // well as a good measure.
7135 Misbehaving(*peer, 100, "avaproofs-bad-indexes");
7136 return;
7137 }
7138 if (!shortIdProcessor.isEvenlyDistributed()) {
7139 // This is suspicious, don't ban but bail out
7140 return;
7141 }
7142
7143 std::vector<std::pair<avalanche::ProofId, bool>> remoteProofsStatus;
7144 m_avalanche->withPeerManager([&](const avalanche::PeerManager &pm) {
7145 pm.forEachPeer([&](const avalanche::Peer &peer) {
7146 assert(peer.proof);
7147 uint64_t shortid = compactProofs.getShortID(peer.getProofId());
7148
7149 int added =
7150 shortIdProcessor.matchKnownItem(shortid, peer.proof);
7151
7152 // No collision
7153 if (added >= 0) {
7154 // Because we know the proof, we can determine if our peer
7155 // has it (added = 1) or not (added = 0) and update the
7156 // remote proof status accordingly.
7157 remoteProofsStatus.emplace_back(peer.getProofId(),
7158 added > 0);
7159 }
7160
7161 // In order to properly determine which proof is missing, we
7162 // need to keep scanning for all our proofs.
7163 return true;
7164 });
7165 });
7166
7168 for (size_t i = 0; i < compactProofs.size(); i++) {
7169 if (shortIdProcessor.getItem(i) == nullptr) {
7170 req.indices.push_back(i);
7171 }
7172 }
7173
7174 m_connman.PushMessage(&pfrom,
7176
7177 const NodeId nodeid = pfrom.GetId();
7178
7179 // We want to keep a count of how many nodes we successfully requested
7180 // avaproofs from as this is used to determine when we are confident our
7181 // quorum is close enough to the other participants.
7182 m_avalanche->avaproofsSent(nodeid);
7183
7184 // Only save remote proofs from stakers
7185 if (WITH_LOCK(pfrom.cs_avalanche_pubkey,
7186 return pfrom.m_avalanche_pubkey.has_value())) {
7187 m_avalanche->withPeerManager(
7189 for (const auto &[proofid, present] : remoteProofsStatus) {
7190 pm.saveRemoteProof(proofid, nodeid, present);
7191 }
7192 });
7193 }
7194
7195 return;
7196 }
7197
7199 if (peer->m_proof_relay == nullptr) {
7200 return;
7201 }
7202
7204 vRecv >> proofreq;
7205
7206 auto requestedIndiceIt = proofreq.indices.begin();
7207 uint32_t treeIndice = 0;
7208 peer->m_proof_relay->sharedProofs.forEachLeaf([&](const auto &proof) {
7209 if (requestedIndiceIt == proofreq.indices.end()) {
7210 // No more indice to process
7211 return false;
7212 }
7213
7214 if (treeIndice++ == *requestedIndiceIt) {
7215 m_connman.PushMessage(
7216 &pfrom, msgMaker.Make(NetMsgType::AVAPROOF, *proof));
7218 }
7219
7220 return true;
7221 });
7222
7223 peer->m_proof_relay->sharedProofs = {};
7224 return;
7225 }
7226
7228 // This asymmetric behavior for inbound and outbound connections was
7229 // introduced to prevent a fingerprinting attack: an attacker can send
7230 // specific fake addresses to users' AddrMan and later request them by
7231 // sending getaddr messages. Making nodes which are behind NAT and can
7232 // only make outgoing connections ignore the getaddr message mitigates
7233 // the attack.
7234 if (!pfrom.IsInboundConn()) {
7236 "Ignoring \"getaddr\" from %s connection. peer=%d\n",
7237 pfrom.ConnectionTypeAsString(), pfrom.GetId());
7238 return;
7239 }
7240
7241 // Since this must be an inbound connection, SetupAddressRelay will
7242 // never fail.
7244
7245 // Only send one GetAddr response per connection to reduce resource
7246 // waste and discourage addr stamping of INV announcements.
7247 if (peer->m_getaddr_recvd) {
7248 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n",
7249 pfrom.GetId());
7250 return;
7251 }
7252 peer->m_getaddr_recvd = true;
7253
7254 peer->m_addrs_to_send.clear();
7255 std::vector<CAddress> vAddr;
7256 const size_t maxAddrToSend = m_opts.max_addr_to_send;
7257 if (pfrom.HasPermission(NetPermissionFlags::Addr)) {
7259 /* network */ std::nullopt);
7260 } else {
7261 vAddr = m_connman.GetAddresses(pfrom, maxAddrToSend,
7263 }
7264 for (const CAddress &addr : vAddr) {
7265 PushAddress(*peer, addr);
7266 }
7267 return;
7268 }
7269
7271 auto now = GetTime<std::chrono::seconds>();
7272 if (now < pfrom.m_nextGetAvaAddr) {
7273 // Prevent a peer from exhausting our resources by spamming
7274 // getavaaddr messages.
7275 return;
7276 }
7277
7278 // Only accept a getavaaddr every GETAVAADDR_INTERVAL at most
7279 pfrom.m_nextGetAvaAddr = now + GETAVAADDR_INTERVAL;
7280
7281 if (!SetupAddressRelay(pfrom, *peer)) {
7283 "Ignoring getavaaddr message from %s peer=%d\n",
7284 pfrom.ConnectionTypeAsString(), pfrom.GetId());
7285 return;
7286 }
7287
7288 auto availabilityScoreComparator = [](const CNode *lhs,
7289 const CNode *rhs) {
7290 double scoreLhs = lhs->getAvailabilityScore();
7291 double scoreRhs = rhs->getAvailabilityScore();
7292
7293 if (scoreLhs != scoreRhs) {
7294 return scoreLhs > scoreRhs;
7295 }
7296
7297 return lhs < rhs;
7298 };
7299
7300 // Get up to MAX_ADDR_TO_SEND addresses of the nodes which are the
7301 // most active in the avalanche network. Account for 0 availability as
7302 // well so we can send addresses even if we did not start polling yet.
7303 std::set<const CNode *, decltype(availabilityScoreComparator)> avaNodes(
7305 m_connman.ForEachNode([&](const CNode *pnode) {
7306 if (!pnode->m_avalanche_enabled ||
7307 pnode->getAvailabilityScore() < 0.) {
7308 return;
7309 }
7310
7311 avaNodes.insert(pnode);
7312 if (avaNodes.size() > m_opts.max_addr_to_send) {
7313 avaNodes.erase(std::prev(avaNodes.end()));
7314 }
7315 });
7316
7317 peer->m_addrs_to_send.clear();
7318 for (const CNode *pnode : avaNodes) {
7319 PushAddress(*peer, pnode->addr);
7320 }
7321
7322 return;
7323 }
7324
7326 if (!(peer->m_our_services & NODE_BLOOM) &&
7327 !pfrom.HasPermission(NetPermissionFlags::Mempool)) {
7328 if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) {
7330 "mempool request with bloom filters disabled, "
7331 "disconnect peer=%d\n",
7332 pfrom.GetId());
7333 pfrom.fDisconnect = true;
7334 }
7335 return;
7336 }
7337
7338 if (m_connman.OutboundTargetReached(false) &&
7339 !pfrom.HasPermission(NetPermissionFlags::Mempool)) {
7340 if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) {
7342 "mempool request with bandwidth limit reached, "
7343 "disconnect peer=%d\n",
7344 pfrom.GetId());
7345 pfrom.fDisconnect = true;
7346 }
7347 return;
7348 }
7349
7350 if (auto tx_relay = peer->GetTxRelay()) {
7351 LOCK(tx_relay->m_tx_inventory_mutex);
7352 tx_relay->m_send_mempool = true;
7353 }
7354 return;
7355 }
7356
7357 if (msg_type == NetMsgType::PING) {
7358 if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
7359 uint64_t nonce = 0;
7360 vRecv >> nonce;
7361 // Echo the message back with the nonce. This allows for two useful
7362 // features:
7363 //
7364 // 1) A remote node can quickly check if the connection is
7365 // operational.
7366 // 2) Remote nodes can measure the latency of the network thread. If
7367 // this node is overloaded it won't respond to pings quickly and the
7368 // remote node can avoid sending us more work, like chain download
7369 // requests.
7370 //
7371 // The nonce stops the remote getting confused between different
7372 // pings: without it, if the remote node sends a ping once per
7373 // second and this node takes 5 seconds to respond to each, the 5th
7374 // ping the remote sends would appear to return very quickly.
7375 m_connman.PushMessage(&pfrom,
7376 msgMaker.Make(NetMsgType::PONG, nonce));
7377 }
7378 return;
7379 }
7380
7381 if (msg_type == NetMsgType::PONG) {
7382 const auto ping_end = time_received;
7383 uint64_t nonce = 0;
7384 size_t nAvail = vRecv.in_avail();
7385 bool bPingFinished = false;
7386 std::string sProblem;
7387
7388 if (nAvail >= sizeof(nonce)) {
7389 vRecv >> nonce;
7390
7391 // Only process pong message if there is an outstanding ping (old
7392 // ping without nonce should never pong)
7393 if (peer->m_ping_nonce_sent != 0) {
7394 if (nonce == peer->m_ping_nonce_sent) {
7395 // Matching pong received, this ping is no longer
7396 // outstanding
7397 bPingFinished = true;
7398 const auto ping_time = ping_end - peer->m_ping_start.load();
7399 if (ping_time.count() >= 0) {
7400 // Let connman know about this successful ping-pong
7401 pfrom.PongReceived(ping_time);
7402 } else {
7403 // This should never happen
7404 sProblem = "Timing mishap";
7405 }
7406 } else {
7407 // Nonce mismatches are normal when pings are overlapping
7408 sProblem = "Nonce mismatch";
7409 if (nonce == 0) {
7410 // This is most likely a bug in another implementation
7411 // somewhere; cancel this ping
7412 bPingFinished = true;
7413 sProblem = "Nonce zero";
7414 }
7415 }
7416 } else {
7417 sProblem = "Unsolicited pong without ping";
7418 }
7419 } else {
7420 // This is most likely a bug in another implementation somewhere;
7421 // cancel this ping
7422 bPingFinished = true;
7423 sProblem = "Short payload";
7424 }
7425
7426 if (!(sProblem.empty())) {
7428 "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
7429 pfrom.GetId(), sProblem, peer->m_ping_nonce_sent, nonce,
7430 nAvail);
7431 }
7432 if (bPingFinished) {
7433 peer->m_ping_nonce_sent = 0;
7434 }
7435 return;
7436 }
7437
7439 if (!(peer->m_our_services & NODE_BLOOM)) {
7441 "filterload received despite not offering bloom services "
7442 "from peer=%d; disconnecting\n",
7443 pfrom.GetId());
7444 pfrom.fDisconnect = true;
7445 return;
7446 }
7447 CBloomFilter filter;
7448 vRecv >> filter;
7449
7450 if (!filter.IsWithinSizeConstraints()) {
7451 // There is no excuse for sending a too-large filter
7452 Misbehaving(*peer, 100, "too-large bloom filter");
7453 } else if (auto tx_relay = peer->GetTxRelay()) {
7454 {
7455 LOCK(tx_relay->m_bloom_filter_mutex);
7456 tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
7457 tx_relay->m_relay_txs = true;
7458 }
7459 pfrom.m_bloom_filter_loaded = true;
7460 }
7461 return;
7462 }
7463
7465 if (!(peer->m_our_services & NODE_BLOOM)) {
7467 "filteradd received despite not offering bloom services "
7468 "from peer=%d; disconnecting\n",
7469 pfrom.GetId());
7470 pfrom.fDisconnect = true;
7471 return;
7472 }
7473 std::vector<uint8_t> vData;
7474 vRecv >> vData;
7475
7476 // Nodes must NEVER send a data item > 520 bytes (the max size for a
7477 // script data object, and thus, the maximum size any matched object can
7478 // have) in a filteradd message.
7479 bool bad = false;
7480 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
7481 bad = true;
7482 } else if (auto tx_relay = peer->GetTxRelay()) {
7483 LOCK(tx_relay->m_bloom_filter_mutex);
7484 if (tx_relay->m_bloom_filter) {
7485 tx_relay->m_bloom_filter->insert(vData);
7486 } else {
7487 bad = true;
7488 }
7489 }
7490 if (bad) {
7491 // The structure of this code doesn't really allow for a good error
7492 // code. We'll go generic.
7493 Misbehaving(*peer, 100, "bad filteradd message");
7494 }
7495 return;
7496 }
7497
7499 if (!(peer->m_our_services & NODE_BLOOM)) {
7501 "filterclear received despite not offering bloom services "
7502 "from peer=%d; disconnecting\n",
7503 pfrom.GetId());
7504 pfrom.fDisconnect = true;
7505 return;
7506 }
7507 auto tx_relay = peer->GetTxRelay();
7508 if (!tx_relay) {
7509 return;
7510 }
7511
7512 {
7513 LOCK(tx_relay->m_bloom_filter_mutex);
7514 tx_relay->m_bloom_filter = nullptr;
7515 tx_relay->m_relay_txs = true;
7516 }
7517 pfrom.m_bloom_filter_loaded = false;
7518 pfrom.m_relays_txs = true;
7519 return;
7520 }
7521
7524 vRecv >> newFeeFilter;
7525 if (MoneyRange(newFeeFilter)) {
7526 if (auto tx_relay = peer->GetTxRelay()) {
7527 tx_relay->m_fee_filter_received = newFeeFilter;
7528 }
7529 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n",
7530 CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
7531 }
7532 return;
7533 }
7534
7536 ProcessGetCFilters(pfrom, *peer, vRecv);
7537 return;
7538 }
7539
7541 ProcessGetCFHeaders(pfrom, *peer, vRecv);
7542 return;
7543 }
7544
7546 ProcessGetCFCheckPt(pfrom, *peer, vRecv);
7547 return;
7548 }
7549
7551 std::vector<CInv> vInv;
7552 vRecv >> vInv;
7553 // A peer might send up to 1 notfound per getdata request, but no more
7557 for (CInv &inv : vInv) {
7558 if (inv.IsMsgTx()) {
7559 // If we receive a NOTFOUND message for a tx we requested,
7560 // mark the announcement for it as completed in
7561 // InvRequestTracker.
7562 LOCK(::cs_main);
7563 m_txrequest.ReceivedResponse(pfrom.GetId(), TxId(inv.hash));
7564 continue;
7565 }
7566 if (inv.IsMsgProof()) {
7567 if (!m_avalanche) {
7568 continue;
7569 }
7570 LOCK(cs_proofrequest);
7571 m_proofrequest.ReceivedResponse(
7572 pfrom.GetId(), avalanche::ProofId(inv.hash));
7573 }
7574 }
7575 }
7576 return;
7577 }
7578
7579 // Ignore unknown commands for extensibility
7580 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n",
7581 SanitizeString(msg_type), pfrom.GetId());
7582 return;
7583}
7584
7585bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode &pnode, Peer &peer) {
7586 {
7587 LOCK(peer.m_misbehavior_mutex);
7588
7589 // There's nothing to do if the m_should_discourage flag isn't set
7590 if (!peer.m_should_discourage) {
7591 return false;
7592 }
7593
7594 peer.m_should_discourage = false;
7595 } // peer.m_misbehavior_mutex
7596
7597 if (pnode.HasPermission(NetPermissionFlags::NoBan)) {
7598 // We never disconnect or discourage peers for bad behavior if they have
7599 // NetPermissionFlags::NoBan permission
7600 LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id);
7601 return false;
7602 }
7603
7604 if (pnode.IsManualConn()) {
7605 // We never disconnect or discourage manual peers for bad behavior
7606 LogPrintf("Warning: not punishing manually connected peer %d!\n",
7607 peer.m_id);
7608 return false;
7609 }
7610
7611 if (pnode.addr.IsLocal()) {
7612 // We disconnect local peers for bad behavior but don't discourage
7613 // (since that would discourage all peers on the same local address)
7615 "Warning: disconnecting but not discouraging %s peer %d!\n",
7616 pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
7617 pnode.fDisconnect = true;
7618 return true;
7619 }
7620
7621 // Normal case: Disconnect the peer and discourage all nodes sharing the
7622 // address
7623 LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n",
7624 peer.m_id);
7625 if (m_banman) {
7626 m_banman->Discourage(pnode.addr);
7627 }
7628 m_connman.DisconnectNode(pnode.addr);
7629 return true;
7630}
7631
7632bool PeerManagerImpl::ProcessMessages(const Config &config, CNode *pfrom,
7633 std::atomic<bool> &interruptMsgProc) {
7634 AssertLockHeld(g_msgproc_mutex);
7635
7636 //
7637 // Message format
7638 // (4) message start
7639 // (12) command
7640 // (4) size
7641 // (4) checksum
7642 // (x) data
7643 //
7644 bool fMoreWork = false;
7645
7646 PeerRef peer = GetPeerRef(pfrom->GetId());
7647 if (peer == nullptr) {
7648 return false;
7649 }
7650
7651 {
7652 LOCK(peer->m_getdata_requests_mutex);
7653 if (!peer->m_getdata_requests.empty()) {
7654 ProcessGetData(config, *pfrom, *peer, interruptMsgProc);
7655 }
7656 }
7657
7658 const bool processed_orphan = ProcessOrphanTx(config, *peer);
7659
7660 if (pfrom->fDisconnect) {
7661 return false;
7662 }
7663
7664 if (processed_orphan) {
7665 return true;
7666 }
7667
7668 // this maintains the order of responses and prevents m_getdata_requests to
7669 // grow unbounded
7670 {
7671 LOCK(peer->m_getdata_requests_mutex);
7672 if (!peer->m_getdata_requests.empty()) {
7673 return true;
7674 }
7675 }
7676
7677 // Don't bother if send buffer is too full to respond anyway
7678 if (pfrom->fPauseSend) {
7679 return false;
7680 }
7681
7682 std::list<CNetMessage> msgs;
7683 {
7684 LOCK(pfrom->cs_vProcessMsg);
7685 if (pfrom->vProcessMsg.empty()) {
7686 return false;
7687 }
7688 // Just take one message
7689 msgs.splice(msgs.begin(), pfrom->vProcessMsg,
7690 pfrom->vProcessMsg.begin());
7691 pfrom->nProcessQueueSize -= msgs.front().m_raw_message_size;
7692 pfrom->fPauseRecv =
7693 pfrom->nProcessQueueSize > m_connman.GetReceiveFloodSize();
7694 fMoreWork = !pfrom->vProcessMsg.empty();
7695 }
7696 CNetMessage &msg(msgs.front());
7697
7698 TRACE6(net, inbound_message, pfrom->GetId(), pfrom->m_addr_name.c_str(),
7699 pfrom->ConnectionTypeAsString().c_str(), msg.m_type.c_str(),
7700 msg.m_recv.size(), msg.m_recv.data());
7701
7702 if (m_opts.capture_messages) {
7703 CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv),
7704 /*is_incoming=*/true);
7705 }
7706
7707 msg.SetVersion(pfrom->GetCommonVersion());
7708
7709 // Check network magic
7710 if (!msg.m_valid_netmagic) {
7712 "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n",
7713 SanitizeString(msg.m_type), pfrom->GetId());
7714
7715 // Make sure we discourage where that come from for some time.
7716 if (m_banman) {
7717 m_banman->Discourage(pfrom->addr);
7718 }
7719 m_connman.DisconnectNode(pfrom->addr);
7720
7721 pfrom->fDisconnect = true;
7722 return false;
7723 }
7724
7725 // Check header
7726 if (!msg.m_valid_header) {
7727 LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n",
7728 SanitizeString(msg.m_type), pfrom->GetId());
7729 return fMoreWork;
7730 }
7731
7732 // Checksum
7733 CDataStream &vRecv = msg.m_recv;
7734 if (!msg.m_valid_checksum) {
7735 LogPrint(BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR peer=%d\n",
7736 __func__, SanitizeString(msg.m_type), msg.m_message_size,
7737 pfrom->GetId());
7738 if (m_banman) {
7739 m_banman->Discourage(pfrom->addr);
7740 }
7741 m_connman.DisconnectNode(pfrom->addr);
7742 return fMoreWork;
7743 }
7744
7745 try {
7746 ProcessMessage(config, *pfrom, msg.m_type, vRecv, msg.m_time,
7748 if (interruptMsgProc) {
7749 return false;
7750 }
7751
7752 {
7753 LOCK(peer->m_getdata_requests_mutex);
7754 if (!peer->m_getdata_requests.empty()) {
7755 fMoreWork = true;
7756 }
7757 }
7758 // Does this peer has an orphan ready to reconsider?
7759 // (Note: we may have provided a parent for an orphan provided by
7760 // another peer that was already processed; in that case, the extra work
7761 // may not be noticed, possibly resulting in an unnecessary 100ms delay)
7762 if (m_mempool.withOrphanage([&peer](TxOrphanage &orphanage) {
7763 return orphanage.HaveTxToReconsider(peer->m_id);
7764 })) {
7765 fMoreWork = true;
7766 }
7767 } catch (const std::exception &e) {
7768 LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n",
7769 __func__, SanitizeString(msg.m_type), msg.m_message_size,
7770 e.what(), typeid(e).name());
7771 } catch (...) {
7772 LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n",
7773 __func__, SanitizeString(msg.m_type), msg.m_message_size);
7774 }
7775
7776 return fMoreWork;
7777}
7778
7779void PeerManagerImpl::ConsiderEviction(CNode &pto, Peer &peer,
7780 std::chrono::seconds time_in_seconds) {
7782
7783 CNodeState &state = *State(pto.GetId());
7784 const CNetMsgMaker msgMaker(pto.GetCommonVersion());
7785
7786 if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() &&
7787 state.fSyncStarted) {
7788 // This is an outbound peer subject to disconnection if they don't
7789 // announce a block with as much work as the current tip within
7790 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if their
7791 // chain has more work than ours, we should sync to it, unless it's
7792 // invalid, in which case we should find that out and disconnect from
7793 // them elsewhere).
7794 if (state.pindexBestKnownBlock != nullptr &&
7795 state.pindexBestKnownBlock->nChainWork >=
7796 m_chainman.ActiveChain().Tip()->nChainWork) {
7797 if (state.m_chain_sync.m_timeout != 0s) {
7798 state.m_chain_sync.m_timeout = 0s;
7799 state.m_chain_sync.m_work_header = nullptr;
7800 state.m_chain_sync.m_sent_getheaders = false;
7801 }
7802 } else if (state.m_chain_sync.m_timeout == 0s ||
7803 (state.m_chain_sync.m_work_header != nullptr &&
7804 state.pindexBestKnownBlock != nullptr &&
7805 state.pindexBestKnownBlock->nChainWork >=
7806 state.m_chain_sync.m_work_header->nChainWork)) {
7807 // Our best block known by this peer is behind our tip, and we're
7808 // either noticing that for the first time, OR this peer was able to
7809 // catch up to some earlier point where we checked against our tip.
7810 // Either way, set a new timeout based on current tip.
7811 state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
7812 state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
7813 state.m_chain_sync.m_sent_getheaders = false;
7814 } else if (state.m_chain_sync.m_timeout > 0s &&
7815 time_in_seconds > state.m_chain_sync.m_timeout) {
7816 // No evidence yet that our peer has synced to a chain with work
7817 // equal to that of our tip, when we first detected it was behind.
7818 // Send a single getheaders message to give the peer a chance to
7819 // update us.
7820 if (state.m_chain_sync.m_sent_getheaders) {
7821 // They've run out of time to catch up!
7822 LogPrintf(
7823 "Disconnecting outbound peer %d for old chain, best known "
7824 "block = %s\n",
7825 pto.GetId(),
7826 state.pindexBestKnownBlock != nullptr
7827 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7828 : "<none>");
7829 pto.fDisconnect = true;
7830 } else {
7831 assert(state.m_chain_sync.m_work_header);
7832 // Here, we assume that the getheaders message goes out,
7833 // because it'll either go out or be skipped because of a
7834 // getheaders in-flight already, in which case the peer should
7835 // still respond to us with a sufficiently high work chain tip.
7837 pto, GetLocator(state.m_chain_sync.m_work_header->pprev),
7838 peer);
7839 LogPrint(
7840 BCLog::NET,
7841 "sending getheaders to outbound peer=%d to verify chain "
7842 "work (current best known block:%s, benchmark blockhash: "
7843 "%s)\n",
7844 pto.GetId(),
7845 state.pindexBestKnownBlock != nullptr
7846 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7847 : "<none>",
7848 state.m_chain_sync.m_work_header->GetBlockHash()
7849 .ToString());
7850 state.m_chain_sync.m_sent_getheaders = true;
7851 // Bump the timeout to allow a response, which could clear the
7852 // timeout (if the response shows the peer has synced), reset
7853 // the timeout (if the peer syncs to the required work but not
7854 // to our tip), or result in disconnect (if we advance to the
7855 // timeout and pindexBestKnownBlock has not sufficiently
7856 // progressed)
7857 state.m_chain_sync.m_timeout =
7859 }
7860 }
7861 }
7862}
7863
7864void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) {
7865 // If we have any extra block-relay-only peers, disconnect the youngest
7866 // unless it's given us a block -- in which case, compare with the
7867 // second-youngest, and out of those two, disconnect the peer who least
7868 // recently gave us a block.
7869 // The youngest block-relay-only peer would be the extra peer we connected
7870 // to temporarily in order to sync our tip; see net.cpp.
7871 // Note that we use higher nodeid as a measure for most recent connection.
7872 if (m_connman.GetExtraBlockRelayCount() > 0) {
7873 std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0},
7874 next_youngest_peer{-1, 0};
7875
7876 m_connman.ForEachNode([&](CNode *pnode) {
7877 if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) {
7878 return;
7879 }
7880 if (pnode->GetId() > youngest_peer.first) {
7881 next_youngest_peer = youngest_peer;
7882 youngest_peer.first = pnode->GetId();
7883 youngest_peer.second = pnode->m_last_block_time;
7884 }
7885 });
7886
7888 if (youngest_peer.second > next_youngest_peer.second) {
7889 // Our newest block-relay-only peer gave us a block more recently;
7890 // disconnect our second youngest.
7892 }
7893
7894 m_connman.ForNode(
7898 // Make sure we're not getting a block right now, and that we've
7899 // been connected long enough for this eviction to happen at
7900 // all. Note that we only request blocks from a peer if we learn
7901 // of a valid headers chain with at least as much work as our
7902 // tip.
7903 CNodeState *node_state = State(pnode->GetId());
7904 if (node_state == nullptr ||
7905 (now - pnode->m_connected >= MINIMUM_CONNECT_TIME &&
7906 node_state->vBlocksInFlight.empty())) {
7907 pnode->fDisconnect = true;
7909 "disconnecting extra block-relay-only peer=%d "
7910 "(last block received at time %d)\n",
7911 pnode->GetId(),
7912 count_seconds(pnode->m_last_block_time));
7913 return true;
7914 } else {
7915 LogPrint(
7916 BCLog::NET,
7917 "keeping block-relay-only peer=%d chosen for eviction "
7918 "(connect time: %d, blocks_in_flight: %d)\n",
7919 pnode->GetId(), count_seconds(pnode->m_connected),
7920 node_state->vBlocksInFlight.size());
7921 }
7922 return false;
7923 });
7924 }
7925
7926 // Check whether we have too many OUTBOUND_FULL_RELAY peers
7927 if (m_connman.GetExtraFullOutboundCount() <= 0) {
7928 return;
7929 }
7930
7931 // If we have more OUTBOUND_FULL_RELAY peers than we target, disconnect one.
7932 // Pick the OUTBOUND_FULL_RELAY peer that least recently announced us a new
7933 // block, with ties broken by choosing the more recent connection (higher
7934 // node id)
7935 NodeId worst_peer = -1;
7936 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
7937
7939 ::cs_main) {
7941
7942 // Only consider OUTBOUND_FULL_RELAY peers that are not already marked
7943 // for disconnection
7944 if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) {
7945 return;
7946 }
7947 CNodeState *state = State(pnode->GetId());
7948 if (state == nullptr) {
7949 // shouldn't be possible, but just in case
7950 return;
7951 }
7952 // Don't evict our protected peers
7953 if (state->m_chain_sync.m_protect) {
7954 return;
7955 }
7956 if (state->m_last_block_announcement < oldest_block_announcement ||
7957 (state->m_last_block_announcement == oldest_block_announcement &&
7958 pnode->GetId() > worst_peer)) {
7959 worst_peer = pnode->GetId();
7960 oldest_block_announcement = state->m_last_block_announcement;
7961 }
7962 });
7963
7964 if (worst_peer == -1) {
7965 return;
7966 }
7967
7968 bool disconnected = m_connman.ForNode(
7971
7972 // Only disconnect a peer that has been connected to us for some
7973 // reasonable fraction of our check-frequency, to give it time for
7974 // new information to have arrived. Also don't disconnect any peer
7975 // we're trying to download a block from.
7976 CNodeState &state = *State(pnode->GetId());
7977 if (now - pnode->m_connected > MINIMUM_CONNECT_TIME &&
7978 state.vBlocksInFlight.empty()) {
7980 "disconnecting extra outbound peer=%d (last block "
7981 "announcement received at time %d)\n",
7983 pnode->fDisconnect = true;
7984 return true;
7985 } else {
7987 "keeping outbound peer=%d chosen for eviction "
7988 "(connect time: %d, blocks_in_flight: %d)\n",
7989 pnode->GetId(), count_seconds(pnode->m_connected),
7990 state.vBlocksInFlight.size());
7991 return false;
7992 }
7993 });
7994
7995 if (disconnected) {
7996 // If we disconnected an extra peer, that means we successfully
7997 // connected to at least one peer after the last time we detected a
7998 // stale tip. Don't try any more extra peers until we next detect a
7999 // stale tip, to limit the load we put on the network from these extra
8000 // connections.
8001 m_connman.SetTryNewOutboundPeer(false);
8002 }
8003}
8004
8005void PeerManagerImpl::CheckForStaleTipAndEvictPeers() {
8006 LOCK(cs_main);
8007
8009
8011
8012 if (now > m_stale_tip_check_time) {
8013 // Check whether our tip is stale, and if so, allow using an extra
8014 // outbound peer.
8015 if (!m_chainman.m_blockman.LoadingBlocks() &&
8016 m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() &&
8017 TipMayBeStale()) {
8018 LogPrintf("Potential stale tip detected, will try using extra "
8019 "outbound peer (last tip update: %d seconds ago)\n",
8020 count_seconds(now - m_last_tip_update.load()));
8021 m_connman.SetTryNewOutboundPeer(true);
8022 } else if (m_connman.GetTryNewOutboundPeer()) {
8023 m_connman.SetTryNewOutboundPeer(false);
8024 }
8025 m_stale_tip_check_time = now + STALE_CHECK_INTERVAL;
8026 }
8027
8028 if (!m_initial_sync_finished && CanDirectFetch()) {
8029 m_connman.StartExtraBlockRelayPeers();
8030 m_initial_sync_finished = true;
8031 }
8032}
8033
8034void PeerManagerImpl::MaybeSendPing(CNode &node_to, Peer &peer,
8035 std::chrono::microseconds now) {
8036 if (m_connman.ShouldRunInactivityChecks(
8037 node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
8038 peer.m_ping_nonce_sent &&
8039 now > peer.m_ping_start.load() + TIMEOUT_INTERVAL) {
8040 // The ping timeout is using mocktime. To disable the check during
8041 // testing, increase -peertimeout.
8042 LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n",
8043 0.000001 * count_microseconds(now - peer.m_ping_start.load()),
8044 peer.m_id);
8045 node_to.fDisconnect = true;
8046 return;
8047 }
8048
8049 const CNetMsgMaker msgMaker(node_to.GetCommonVersion());
8050 bool pingSend = false;
8051
8052 if (peer.m_ping_queued) {
8053 // RPC ping request by user
8054 pingSend = true;
8055 }
8056
8057 if (peer.m_ping_nonce_sent == 0 &&
8058 now > peer.m_ping_start.load() + PING_INTERVAL) {
8059 // Ping automatically sent as a latency probe & keepalive.
8060 pingSend = true;
8061 }
8062
8063 if (pingSend) {
8064 uint64_t nonce;
8065 do {
8066 nonce = GetRand<uint64_t>();
8067 } while (nonce == 0);
8068 peer.m_ping_queued = false;
8069 peer.m_ping_start = now;
8070 if (node_to.GetCommonVersion() > BIP0031_VERSION) {
8071 peer.m_ping_nonce_sent = nonce;
8072 m_connman.PushMessage(&node_to,
8073 msgMaker.Make(NetMsgType::PING, nonce));
8074 } else {
8075 // Peer is too old to support ping command with nonce, pong will
8076 // never arrive.
8077 peer.m_ping_nonce_sent = 0;
8078 m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING));
8079 }
8080 }
8081}
8082
8083void PeerManagerImpl::MaybeSendAddr(CNode &node, Peer &peer,
8084 std::chrono::microseconds current_time) {
8085 // Nothing to do for non-address-relay peers
8086 if (!peer.m_addr_relay_enabled) {
8087 return;
8088 }
8089
8090 LOCK(peer.m_addr_send_times_mutex);
8091 if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
8092 peer.m_next_local_addr_send < current_time) {
8093 // If we've sent before, clear the bloom filter for the peer, so
8094 // that our self-announcement will actually go out. This might
8095 // be unnecessary if the bloom filter has already rolled over
8096 // since our last self-announcement, but there is only a small
8097 // bandwidth cost that we can incur by doing this (which happens
8098 // once a day on average).
8099 if (peer.m_next_local_addr_send != 0us) {
8100 peer.m_addr_known->reset();
8101 }
8102 if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
8103 CAddress local_addr{*local_service, peer.m_our_services,
8105 PushAddress(peer, local_addr);
8106 }
8107 peer.m_next_local_addr_send = GetExponentialRand(
8109 }
8110
8111 // We sent an `addr` message to this peer recently. Nothing more to do.
8112 if (current_time <= peer.m_next_addr_send) {
8113 return;
8114 }
8115
8116 peer.m_next_addr_send =
8118
8119 const size_t max_addr_to_send = m_opts.max_addr_to_send;
8120 if (!Assume(peer.m_addrs_to_send.size() <= max_addr_to_send)) {
8121 // Should be impossible since we always check size before adding to
8122 // m_addrs_to_send. Recover by trimming the vector.
8123 peer.m_addrs_to_send.resize(max_addr_to_send);
8124 }
8125
8126 // Remove addr records that the peer already knows about, and add new
8127 // addrs to the m_addr_known filter on the same pass.
8128 auto addr_already_known =
8129 [&peer](const CAddress &addr)
8130 EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) {
8131 bool ret = peer.m_addr_known->contains(addr.GetKey());
8132 if (!ret) {
8133 peer.m_addr_known->insert(addr.GetKey());
8134 }
8135 return ret;
8136 };
8137 peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(),
8138 peer.m_addrs_to_send.end(),
8140 peer.m_addrs_to_send.end());
8141
8142 // No addr messages to send
8143 if (peer.m_addrs_to_send.empty()) {
8144 return;
8145 }
8146
8147 const char *msg_type;
8148 int make_flags;
8149 if (peer.m_wants_addrv2) {
8152 } else {
8154 make_flags = 0;
8155 }
8156 m_connman.PushMessage(
8157 &node, CNetMsgMaker(node.GetCommonVersion())
8158 .Make(make_flags, msg_type, peer.m_addrs_to_send));
8159 peer.m_addrs_to_send.clear();
8160
8161 // we only send the big addr message once
8162 if (peer.m_addrs_to_send.capacity() > 40) {
8163 peer.m_addrs_to_send.shrink_to_fit();
8164 }
8165}
8166
8167void PeerManagerImpl::MaybeSendSendHeaders(CNode &node, Peer &peer) {
8168 // Delay sending SENDHEADERS (BIP 130) until we're done with an
8169 // initial-headers-sync with this peer. Receiving headers announcements for
8170 // new blocks while trying to sync their headers chain is problematic,
8171 // because of the state tracking done.
8172 if (!peer.m_sent_sendheaders &&
8173 node.GetCommonVersion() >= SENDHEADERS_VERSION) {
8174 LOCK(cs_main);
8175 CNodeState &state = *State(node.GetId());
8176 if (state.pindexBestKnownBlock != nullptr &&
8177 state.pindexBestKnownBlock->nChainWork >
8178 m_chainman.MinimumChainWork()) {
8179 // Tell our peer we prefer to receive headers rather than inv's
8180 // We send this to non-NODE NETWORK peers as well, because even
8181 // non-NODE NETWORK peers can announce blocks (such as pruning
8182 // nodes)
8183 m_connman.PushMessage(&node, CNetMsgMaker(node.GetCommonVersion())
8185 peer.m_sent_sendheaders = true;
8186 }
8187 }
8188}
8189
8190void PeerManagerImpl::MaybeSendFeefilter(
8191 CNode &pto, Peer &peer, std::chrono::microseconds current_time) {
8192 if (m_opts.ignore_incoming_txs) {
8193 return;
8194 }
8195 if (pto.GetCommonVersion() < FEEFILTER_VERSION) {
8196 return;
8197 }
8198 // peers with the forcerelay permission should not filter txs to us
8199 if (pto.HasPermission(NetPermissionFlags::ForceRelay)) {
8200 return;
8201 }
8202 // Don't send feefilter messages to outbound block-relay-only peers since
8203 // they should never announce transactions to us, regardless of feefilter
8204 // state.
8205 if (pto.IsBlockOnlyConn()) {
8206 return;
8207 }
8208
8209 Amount currentFilter = m_mempool.GetMinFee().GetFeePerK();
8210
8211 if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
8212 // Received tx-inv messages are discarded when the active
8213 // chainstate is in IBD, so tell the peer to not send them.
8215 } else {
8216 static const Amount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)};
8217 if (peer.m_fee_filter_sent == MAX_FILTER) {
8218 // Send the current filter if we sent MAX_FILTER previously
8219 // and made it out of IBD.
8220 peer.m_next_send_feefilter = 0us;
8221 }
8222 }
8223 if (current_time > peer.m_next_send_feefilter) {
8225 // We always have a fee filter of at least the min relay fee
8226 filterToSend =
8227 std::max(filterToSend, m_mempool.m_min_relay_feerate.GetFeePerK());
8228 if (filterToSend != peer.m_fee_filter_sent) {
8229 m_connman.PushMessage(
8230 &pto, CNetMsgMaker(pto.GetCommonVersion())
8232 peer.m_fee_filter_sent = filterToSend;
8233 }
8234 peer.m_next_send_feefilter =
8236 }
8237 // If the fee filter has changed substantially and it's still more than
8238 // MAX_FEEFILTER_CHANGE_DELAY until scheduled broadcast, then move the
8239 // broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
8241 peer.m_next_send_feefilter &&
8242 (currentFilter < 3 * peer.m_fee_filter_sent / 4 ||
8243 currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
8244 peer.m_next_send_feefilter =
8247 }
8248}
8249
8250namespace {
8251class CompareInvMempoolOrder {
8252 CTxMemPool *mp;
8253
8254public:
8255 explicit CompareInvMempoolOrder(CTxMemPool *_mempool) : mp(_mempool) {}
8256
8257 bool operator()(std::set<TxId>::iterator a, std::set<TxId>::iterator b) {
8262 return mp->CompareTopologically(*b, *a);
8263 }
8264};
8265} // namespace
8266
8267bool PeerManagerImpl::RejectIncomingTxs(const CNode &peer) const {
8268 // block-relay-only peers may never send txs to us
8269 if (peer.IsBlockOnlyConn()) {
8270 return true;
8271 }
8272 if (peer.IsFeelerConn()) {
8273 return true;
8274 }
8275 // In -blocksonly mode, peers need the 'relay' permission to send txs to us
8276 if (m_opts.ignore_incoming_txs &&
8278 return true;
8279 }
8280 return false;
8281}
8282
8283bool PeerManagerImpl::SetupAddressRelay(const CNode &node, Peer &peer) {
8284 // We don't participate in addr relay with outbound block-relay-only
8285 // connections to prevent providing adversaries with the additional
8286 // information of addr traffic to infer the link.
8287 if (node.IsBlockOnlyConn()) {
8288 return false;
8289 }
8290
8291 if (!peer.m_addr_relay_enabled.exchange(true)) {
8292 // During version message processing (non-block-relay-only outbound
8293 // peers) or on first addr-related message we have received (inbound
8294 // peers), initialize m_addr_known.
8295 peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
8296 }
8297
8298 return true;
8299}
8300
8301bool PeerManagerImpl::SendMessages(const Config &config, CNode *pto) {
8302 AssertLockHeld(g_msgproc_mutex);
8303
8304 PeerRef peer = GetPeerRef(pto->GetId());
8305 if (!peer) {
8306 return false;
8307 }
8308 const Consensus::Params &consensusParams = m_chainparams.GetConsensus();
8309
8310 // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
8311 // disconnect misbehaving peers even before the version handshake is
8312 // complete.
8313 if (MaybeDiscourageAndDisconnect(*pto, *peer)) {
8314 return true;
8315 }
8316
8317 // Don't send anything until the version handshake is complete
8318 if (!pto->fSuccessfullyConnected || pto->fDisconnect) {
8319 return true;
8320 }
8321
8322 // If we get here, the outgoing message serialization version is set and
8323 // can't change.
8324 const CNetMsgMaker msgMaker(pto->GetCommonVersion());
8325
8327
8328 if (pto->IsAddrFetchConn() &&
8329 current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
8331 "addrfetch connection timeout; disconnecting peer=%d\n",
8332 pto->GetId());
8333 pto->fDisconnect = true;
8334 return true;
8335 }
8336
8337 MaybeSendPing(*pto, *peer, current_time);
8338
8339 // MaybeSendPing may have marked peer for disconnection
8340 if (pto->fDisconnect) {
8341 return true;
8342 }
8343
8345
8346 MaybeSendAddr(*pto, *peer, current_time);
8347
8348 MaybeSendSendHeaders(*pto, *peer);
8349
8350 {
8351 LOCK(cs_main);
8352
8353 CNodeState &state = *State(pto->GetId());
8354
8355 // Start block sync
8356 if (m_chainman.m_best_header == nullptr) {
8357 m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
8358 }
8359
8360 // Determine whether we might try initial headers sync or parallel
8361 // block download from this peer -- this mostly affects behavior while
8362 // in IBD (once out of IBD, we sync from all peers).
8363 if (state.fPreferredDownload) {
8365 } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) {
8366 // Typically this is an inbound peer. If we don't have any outbound
8367 // peers, or if we aren't downloading any blocks from such peers,
8368 // then allow block downloads from this peer, too.
8369 // We prefer downloading blocks from outbound peers to avoid
8370 // putting undue load on (say) some home user who is just making
8371 // outbound connections to the network, but if our only source of
8372 // the latest blocks is from an inbound peer, we have to be sure to
8373 // eventually download it (and not just wait indefinitely for an
8374 // outbound peer to have it).
8376 mapBlocksInFlight.empty()) {
8378 }
8379 }
8380
8381 if (!state.fSyncStarted && CanServeBlocks(*peer) &&
8382 !m_chainman.m_blockman.LoadingBlocks()) {
8383 // Only actively request headers from a single peer, unless we're
8384 // close to today.
8386 m_chainman.m_best_header->Time() > GetAdjustedTime() - 24h) {
8387 const CBlockIndex *pindexStart = m_chainman.m_best_header;
8396 if (pindexStart->pprev) {
8397 pindexStart = pindexStart->pprev;
8398 }
8400 LogPrint(
8401 BCLog::NET,
8402 "initial getheaders (%d) to peer=%d (startheight:%d)\n",
8403 pindexStart->nHeight, pto->GetId(),
8404 peer->m_starting_height);
8405
8406 state.fSyncStarted = true;
8407 peer->m_headers_sync_timeout =
8409 (
8410 // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to
8411 // microseconds before scaling to maintain precision
8412 std::chrono::microseconds{
8415 GetAdjustedTime() -
8416 m_chainman.m_best_header->Time()) /
8417 consensusParams.nPowTargetSpacing);
8418 nSyncStarted++;
8419 }
8420 }
8421 }
8422
8423 //
8424 // Try sending block announcements via headers
8425 //
8426 {
8427 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our list of block
8428 // hashes we're relaying, and our peer wants headers announcements,
8429 // then find the first header not yet known to our peer but would
8430 // connect, and send. If no header would connect, or if we have too
8431 // many blocks, or if the peer doesn't want headers, just add all to
8432 // the inv queue.
8433 LOCK(peer->m_block_inv_mutex);
8434 std::vector<CBlock> vHeaders;
8435 bool fRevertToInv =
8436 ((!peer->m_prefers_headers &&
8437 (!state.m_requested_hb_cmpctblocks ||
8438 peer->m_blocks_for_headers_relay.size() > 1)) ||
8439 peer->m_blocks_for_headers_relay.size() >
8441 // last header queued for delivery
8442 const CBlockIndex *pBestIndex = nullptr;
8443 // ensure pindexBestKnownBlock is up-to-date
8444 ProcessBlockAvailability(pto->GetId());
8445
8446 if (!fRevertToInv) {
8447 bool fFoundStartingHeader = false;
8448 // Try to find first header that our peer doesn't have, and then
8449 // send all headers past that one. If we come across an headers
8450 // that aren't on m_chainman.ActiveChain(), give up.
8451 for (const BlockHash &hash : peer->m_blocks_for_headers_relay) {
8452 const CBlockIndex *pindex =
8453 m_chainman.m_blockman.LookupBlockIndex(hash);
8454 assert(pindex);
8455 if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
8456 // Bail out if we reorged away from this block
8457 fRevertToInv = true;
8458 break;
8459 }
8460 if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
8461 // This means that the list of blocks to announce don't
8462 // connect to each other. This shouldn't really be
8463 // possible to hit during regular operation (because
8464 // reorgs should take us to a chain that has some block
8465 // not on the prior chain, which should be caught by the
8466 // prior check), but one way this could happen is by
8467 // using invalidateblock / reconsiderblock repeatedly on
8468 // the tip, causing it to be added multiple times to
8469 // m_blocks_for_headers_relay. Robustly deal with this
8470 // rare situation by reverting to an inv.
8471 fRevertToInv = true;
8472 break;
8473 }
8474 pBestIndex = pindex;
8476 // add this to the headers message
8477 vHeaders.push_back(pindex->GetBlockHeader());
8478 } else if (PeerHasHeader(&state, pindex)) {
8479 // Keep looking for the first new block.
8480 continue;
8481 } else if (pindex->pprev == nullptr ||
8482 PeerHasHeader(&state, pindex->pprev)) {
8483 // Peer doesn't have this header but they do have the
8484 // prior one. Start sending headers.
8485 fFoundStartingHeader = true;
8486 vHeaders.push_back(pindex->GetBlockHeader());
8487 } else {
8488 // Peer doesn't have this header or the prior one --
8489 // nothing will connect, so bail out.
8490 fRevertToInv = true;
8491 break;
8492 }
8493 }
8494 }
8495 if (!fRevertToInv && !vHeaders.empty()) {
8496 if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
8497 // We only send up to 1 block as header-and-ids, as
8498 // otherwise probably means we're doing an initial-ish-sync
8499 // or they're slow.
8501 "%s sending header-and-ids %s to peer=%d\n",
8502 __func__, vHeaders.front().GetHash().ToString(),
8503 pto->GetId());
8504
8505 std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
8506 {
8507 LOCK(m_most_recent_block_mutex);
8509 pBestIndex->GetBlockHash()) {
8513 }
8514 }
8515 if (cached_cmpctblock_msg.has_value()) {
8516 m_connman.PushMessage(
8517 pto, std::move(cached_cmpctblock_msg.value()));
8518 } else {
8519 CBlock block;
8520 const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(
8521 block, *pBestIndex)};
8522 assert(ret);
8524 m_connman.PushMessage(
8525 pto,
8527 }
8528 state.pindexBestHeaderSent = pBestIndex;
8529 } else if (peer->m_prefers_headers) {
8530 if (vHeaders.size() > 1) {
8532 "%s: %u headers, range (%s, %s), to peer=%d\n",
8533 __func__, vHeaders.size(),
8534 vHeaders.front().GetHash().ToString(),
8535 vHeaders.back().GetHash().ToString(),
8536 pto->GetId());
8537 } else {
8539 "%s: sending header %s to peer=%d\n", __func__,
8540 vHeaders.front().GetHash().ToString(),
8541 pto->GetId());
8542 }
8543 m_connman.PushMessage(
8545 state.pindexBestHeaderSent = pBestIndex;
8546 } else {
8547 fRevertToInv = true;
8548 }
8549 }
8550 if (fRevertToInv) {
8551 // If falling back to using an inv, just try to inv the tip. The
8552 // last entry in m_blocks_for_headers_relay was our tip at some
8553 // point in the past.
8554 if (!peer->m_blocks_for_headers_relay.empty()) {
8555 const BlockHash &hashToAnnounce =
8556 peer->m_blocks_for_headers_relay.back();
8557 const CBlockIndex *pindex =
8559 assert(pindex);
8560
8561 // Warn if we're announcing a block that is not on the main
8562 // chain. This should be very rare and could be optimized
8563 // out. Just log for now.
8564 if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
8565 LogPrint(
8566 BCLog::NET,
8567 "Announcing block %s not on main chain (tip=%s)\n",
8568 hashToAnnounce.ToString(),
8569 m_chainman.ActiveChain()
8570 .Tip()
8571 ->GetBlockHash()
8572 .ToString());
8573 }
8574
8575 // If the peer's chain has this block, don't inv it back.
8576 if (!PeerHasHeader(&state, pindex)) {
8577 peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
8579 "%s: sending inv peer=%d hash=%s\n", __func__,
8580 pto->GetId(), hashToAnnounce.ToString());
8581 }
8582 }
8583 }
8584 peer->m_blocks_for_headers_relay.clear();
8585 }
8586 } // release cs_main
8587
8588 //
8589 // Message: inventory
8590 //
8591 std::vector<CInv> vInv;
8592 auto addInvAndMaybeFlush = [&](uint32_t type, const uint256 &hash) {
8593 vInv.emplace_back(type, hash);
8594 if (vInv.size() == MAX_INV_SZ) {
8595 m_connman.PushMessage(
8596 pto, msgMaker.Make(NetMsgType::INV, std::move(vInv)));
8597 vInv.clear();
8598 }
8599 };
8600
8601 {
8602 LOCK(cs_main);
8603
8604 {
8605 LOCK(peer->m_block_inv_mutex);
8606
8607 vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(),
8609 config.GetMaxBlockSize() /
8610 1000000));
8611
8612 // Add blocks
8613 for (const BlockHash &hash : peer->m_blocks_for_inv_relay) {
8615 }
8616 peer->m_blocks_for_inv_relay.clear();
8617 }
8618
8620 [&](std::chrono::microseconds &next) -> bool {
8621 bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
8622
8623 if (next < current_time) {
8624 fSendTrickle = true;
8625 if (pto->IsInboundConn()) {
8626 next = NextInvToInbounds(
8628 } else {
8629 // Skip delay for outbound peers, as there is less privacy
8630 // concern for them.
8631 next = current_time;
8632 }
8633 }
8634
8635 return fSendTrickle;
8636 };
8637
8638 // Add proofs to inventory
8639 if (peer->m_proof_relay != nullptr) {
8640 LOCK(peer->m_proof_relay->m_proof_inventory_mutex);
8641
8643 peer->m_proof_relay->m_next_inv_send_time)) {
8644 auto it =
8645 peer->m_proof_relay->m_proof_inventory_to_send.begin();
8646 while (it !=
8647 peer->m_proof_relay->m_proof_inventory_to_send.end()) {
8648 const avalanche::ProofId proofid = *it;
8649
8650 it = peer->m_proof_relay->m_proof_inventory_to_send.erase(
8651 it);
8652
8653 if (peer->m_proof_relay->m_proof_inventory_known_filter
8654 .contains(proofid)) {
8655 continue;
8656 }
8657
8658 peer->m_proof_relay->m_proof_inventory_known_filter.insert(
8659 proofid);
8661 peer->m_proof_relay->m_recently_announced_proofs.insert(
8662 proofid);
8663 }
8664 }
8665 }
8666
8667 if (auto tx_relay = peer->GetTxRelay()) {
8668 LOCK(tx_relay->m_tx_inventory_mutex);
8669 // Check whether periodic sends should happen
8670 const bool fSendTrickle =
8671 computeNextInvSendTime(tx_relay->m_next_inv_send_time);
8672
8673 // Time to send but the peer has requested we not relay
8674 // transactions.
8675 if (fSendTrickle) {
8676 LOCK(tx_relay->m_bloom_filter_mutex);
8677 if (!tx_relay->m_relay_txs) {
8678 tx_relay->m_tx_inventory_to_send.clear();
8679 }
8680 }
8681
8682 // Respond to BIP35 mempool requests
8683 if (fSendTrickle && tx_relay->m_send_mempool) {
8684 auto vtxinfo = m_mempool.infoAll();
8685 tx_relay->m_send_mempool = false;
8686 const CFeeRate filterrate{
8687 tx_relay->m_fee_filter_received.load()};
8688
8689 LOCK(tx_relay->m_bloom_filter_mutex);
8690
8691 for (const auto &txinfo : vtxinfo) {
8692 const TxId &txid = txinfo.tx->GetId();
8693 tx_relay->m_tx_inventory_to_send.erase(txid);
8694 // Don't send transactions that peers will not put into
8695 // their mempool
8696 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8697 continue;
8698 }
8699 if (tx_relay->m_bloom_filter &&
8700 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8701 *txinfo.tx)) {
8702 continue;
8703 }
8704 tx_relay->m_tx_inventory_known_filter.insert(txid);
8705 // Responses to MEMPOOL requests bypass the
8706 // m_recently_announced_invs filter.
8708 }
8709 tx_relay->m_last_mempool_req =
8710 std::chrono::duration_cast<std::chrono::seconds>(
8711 current_time);
8712 }
8713
8714 // Determine transactions to relay
8715 if (fSendTrickle) {
8716 // Produce a vector with all candidates for sending
8717 std::vector<std::set<TxId>::iterator> vInvTx;
8718 vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
8719 for (std::set<TxId>::iterator it =
8720 tx_relay->m_tx_inventory_to_send.begin();
8721 it != tx_relay->m_tx_inventory_to_send.end(); it++) {
8722 vInvTx.push_back(it);
8723 }
8724 const CFeeRate filterrate{
8725 tx_relay->m_fee_filter_received.load()};
8726 // Send out the inventory in the order of admission to our
8727 // mempool, which is guaranteed to be a topological sort order.
8728 // A heap is used so that not all items need sorting if only a
8729 // few are being sent.
8730 CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool);
8731 std::make_heap(vInvTx.begin(), vInvTx.end(),
8733 // No reason to drain out at many times the network's
8734 // capacity, especially since we have many peers and some
8735 // will draw much shorter delays.
8736 unsigned int nRelayedTransactions = 0;
8737 LOCK(tx_relay->m_bloom_filter_mutex);
8738 while (!vInvTx.empty() &&
8740 config.GetMaxBlockSize() /
8741 1000000) {
8742 // Fetch the top element from the heap
8743 std::pop_heap(vInvTx.begin(), vInvTx.end(),
8745 std::set<TxId>::iterator it = vInvTx.back();
8746 vInvTx.pop_back();
8747 const TxId txid = *it;
8748 // Remove it from the to-be-sent set
8749 tx_relay->m_tx_inventory_to_send.erase(it);
8750 // Check if not in the filter already
8751 if (tx_relay->m_tx_inventory_known_filter.contains(txid)) {
8752 continue;
8753 }
8754 // Not in the mempool anymore? don't bother sending it.
8755 auto txinfo = m_mempool.info(txid);
8756 if (!txinfo.tx) {
8757 continue;
8758 }
8759 // Peer told you to not send transactions at that
8760 // feerate? Don't bother sending it.
8761 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8762 continue;
8763 }
8764 if (tx_relay->m_bloom_filter &&
8765 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8766 *txinfo.tx)) {
8767 continue;
8768 }
8769 // Send
8770 tx_relay->m_recently_announced_invs.insert(txid);
8773 {
8774 // Expire old relay messages
8775 while (!g_relay_expiration.empty() &&
8776 g_relay_expiration.front().first <
8777 current_time) {
8778 mapRelay.erase(g_relay_expiration.front().second);
8779 g_relay_expiration.pop_front();
8780 }
8781
8782 auto ret = mapRelay.insert(
8783 std::make_pair(txid, std::move(txinfo.tx)));
8784 if (ret.second) {
8785 g_relay_expiration.push_back(std::make_pair(
8787 }
8788 }
8789 tx_relay->m_tx_inventory_known_filter.insert(txid);
8790 }
8791 }
8792 }
8793 } // release cs_main
8794
8795 if (!vInv.empty()) {
8796 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
8797 }
8798
8799 {
8800 LOCK(cs_main);
8801
8802 CNodeState &state = *State(pto->GetId());
8803
8804 // Detect whether we're stalling
8805 auto stalling_timeout = m_block_stalling_timeout.load();
8806 if (state.m_stalling_since.count() &&
8807 state.m_stalling_since < current_time - stalling_timeout) {
8808 // Stalling only triggers when the block download window cannot
8809 // move. During normal steady state, the download window should be
8810 // much larger than the to-be-downloaded set of blocks, so
8811 // disconnection should only happen during initial block download.
8812 LogPrintf("Peer=%d is stalling block download, disconnecting\n",
8813 pto->GetId());
8814 pto->fDisconnect = true;
8815 // Increase timeout for the next peer so that we don't disconnect
8816 // multiple peers if our own bandwidth is insufficient.
8817 const auto new_timeout =
8820 m_block_stalling_timeout.compare_exchange_strong(
8822 LogPrint(
8823 BCLog::NET,
8824 "Increased stalling timeout temporarily to %d seconds\n",
8826 }
8827 return true;
8828 }
8829 // In case there is a block that has been in flight from this peer for
8830 // block_interval * (1 + 0.5 * N) (with N the number of peers from which
8831 // we're downloading validated blocks), disconnect due to timeout.
8832 // We compensate for other peers to prevent killing off peers due to our
8833 // own downstream link being saturated. We only count validated
8834 // in-flight blocks so peers can't advertise non-existing block hashes
8835 // to unreasonably increase our timeout.
8836 if (state.vBlocksInFlight.size() > 0) {
8837 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
8840 if (current_time >
8841 state.m_downloading_since +
8842 std::chrono::seconds{consensusParams.nPowTargetSpacing} *
8846 LogPrintf("Timeout downloading block %s from peer=%d, "
8847 "disconnecting\n",
8848 queuedBlock.pindex->GetBlockHash().ToString(),
8849 pto->GetId());
8850 pto->fDisconnect = true;
8851 return true;
8852 }
8853 }
8854
8855 // Check for headers sync timeouts
8856 if (state.fSyncStarted &&
8857 peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
8858 // Detect whether this is a stalling initial-headers-sync peer
8859 if (m_chainman.m_best_header->Time() <= GetAdjustedTime() - 24h) {
8860 if (current_time > peer->m_headers_sync_timeout &&
8861 nSyncStarted == 1 &&
8863 state.fPreferredDownload >=
8864 1)) {
8865 // Disconnect a peer (without NetPermissionFlags::NoBan
8866 // permission) if it is our only sync peer, and we have
8867 // others we could be using instead. Note: If all our peers
8868 // are inbound, then we won't disconnect our sync peer for
8869 // stalling; we have bigger problems if we can't get any
8870 // outbound peers.
8871 if (!pto->HasPermission(NetPermissionFlags::NoBan)) {
8872 LogPrintf("Timeout downloading headers from peer=%d, "
8873 "disconnecting\n",
8874 pto->GetId());
8875 pto->fDisconnect = true;
8876 return true;
8877 } else {
8878 LogPrintf("Timeout downloading headers from noban "
8879 "peer=%d, not disconnecting\n",
8880 pto->GetId());
8881 // Reset the headers sync state so that we have a chance
8882 // to try downloading from a different peer. Note: this
8883 // will also result in at least one more getheaders
8884 // message to be sent to this peer (eventually).
8885 state.fSyncStarted = false;
8886 nSyncStarted--;
8887 peer->m_headers_sync_timeout = 0us;
8888 }
8889 }
8890 } else {
8891 // After we've caught up once, reset the timeout so we can't
8892 // trigger disconnect later.
8893 peer->m_headers_sync_timeout = std::chrono::microseconds::max();
8894 }
8895 }
8896
8897 // Check that outbound peers have reasonable chains GetTime() is used by
8898 // this anti-DoS logic so we can test this using mocktime.
8900 } // release cs_main
8901
8902 std::vector<CInv> vGetData;
8903
8904 //
8905 // Message: getdata (blocks)
8906 //
8907 {
8908 LOCK(cs_main);
8909
8910 CNodeState &state = *State(pto->GetId());
8911
8912 if (CanServeBlocks(*peer) &&
8914 !m_chainman.ActiveChainstate().IsInitialBlockDownload()) &&
8915 state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
8916 std::vector<const CBlockIndex *> vToDownload;
8917 NodeId staller = -1;
8920 state.vBlocksInFlight.size(),
8922 for (const CBlockIndex *pindex : vToDownload) {
8923 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
8924 BlockRequested(config, pto->GetId(), *pindex);
8925 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n",
8926 pindex->GetBlockHash().ToString(), pindex->nHeight,
8927 pto->GetId());
8928 }
8929 if (state.vBlocksInFlight.empty() && staller != -1) {
8930 if (State(staller)->m_stalling_since == 0us) {
8931 State(staller)->m_stalling_since = current_time;
8932 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
8933 }
8934 }
8935 }
8936 } // release cs_main
8937
8938 auto addGetDataAndMaybeFlush = [&](uint32_t type, const uint256 &hash) {
8939 CInv inv(type, hash);
8940 LogPrint(BCLog::NET, "Requesting %s from peer=%d\n", inv.ToString(),
8941 pto->GetId());
8942 vGetData.push_back(std::move(inv));
8943 if (vGetData.size() >= MAX_GETDATA_SZ) {
8944 m_connman.PushMessage(
8945 pto, msgMaker.Make(NetMsgType::GETDATA, std::move(vGetData)));
8946 vGetData.clear();
8947 }
8948 };
8949
8950 //
8951 // Message: getdata (proof)
8952 //
8953 if (m_avalanche) {
8954 LOCK(cs_proofrequest);
8955 std::vector<std::pair<NodeId, avalanche::ProofId>> expired;
8956 auto requestable =
8957 m_proofrequest.GetRequestable(pto->GetId(), current_time, &expired);
8958 for (const auto &entry : expired) {
8960 "timeout of inflight proof %s from peer=%d\n",
8961 entry.second.ToString(), entry.first);
8962 }
8963 for (const auto &proofid : requestable) {
8964 if (!AlreadyHaveProof(proofid)) {
8966 m_proofrequest.RequestedData(
8967 pto->GetId(), proofid,
8969 } else {
8970 // We have already seen this proof, no need to download.
8971 // This is just a belt-and-suspenders, as this should
8972 // already be called whenever a proof becomes
8973 // AlreadyHaveProof().
8974 m_proofrequest.ForgetInvId(proofid);
8975 }
8976 }
8977 }
8978
8979 //
8980 // Message: getdata (transactions)
8981 //
8982 {
8983 LOCK(cs_main);
8984 std::vector<std::pair<NodeId, TxId>> expired;
8985 auto requestable =
8986 m_txrequest.GetRequestable(pto->GetId(), current_time, &expired);
8987 for (const auto &entry : expired) {
8988 LogPrint(BCLog::NET, "timeout of inflight tx %s from peer=%d\n",
8989 entry.second.ToString(), entry.first);
8990 }
8991 for (const TxId &txid : requestable) {
8992 // Exclude m_recent_rejects_package_reconsiderable: we may be
8993 // requesting a missing parent that was previously rejected for
8994 // being too low feerate.
8995 if (!AlreadyHaveTx(txid, /*include_reconsiderable=*/false)) {
8997 m_txrequest.RequestedData(
8998 pto->GetId(), txid,
9000 } else {
9001 // We have already seen this transaction, no need to download.
9002 // This is just a belt-and-suspenders, as this should already be
9003 // called whenever a transaction becomes AlreadyHaveTx().
9004 m_txrequest.ForgetInvId(txid);
9005 }
9006 }
9007
9008 if (!vGetData.empty()) {
9009 m_connman.PushMessage(pto,
9011 }
9012
9013 } // release cs_main
9015 return true;
9016}
9017
9018bool PeerManagerImpl::ReceivedAvalancheProof(CNode &node, Peer &peer,
9019 const avalanche::ProofRef &proof) {
9020 assert(proof != nullptr);
9021
9022 const avalanche::ProofId &proofid = proof->getId();
9023
9024 AddKnownProof(peer, proofid);
9025
9026 if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
9027 // We cannot reliably verify proofs during IBD, so bail out early and
9028 // keep the inventory as pending so it can be requested when the node
9029 // has synced.
9030 return true;
9031 }
9032
9033 const NodeId nodeid = node.GetId();
9034
9035 const bool isStaker = WITH_LOCK(node.cs_avalanche_pubkey,
9036 return node.m_avalanche_pubkey.has_value());
9037 auto saveProofIfStaker = [this, isStaker](const CNode &node,
9038 const avalanche::ProofId &proofid,
9039 const NodeId nodeid) -> bool {
9040 if (isStaker) {
9041 return m_avalanche->withPeerManager(
9043 return pm.saveRemoteProof(proofid, nodeid, true);
9044 });
9045 }
9046
9047 return false;
9048 };
9049
9050 {
9051 LOCK(cs_proofrequest);
9052 m_proofrequest.ReceivedResponse(nodeid, proofid);
9053
9054 if (AlreadyHaveProof(proofid)) {
9055 m_proofrequest.ForgetInvId(proofid);
9056 saveProofIfStaker(node, proofid, nodeid);
9057 return true;
9058 }
9059 }
9060
9061 // registerProof should not be called while cs_proofrequest because it
9062 // holds cs_main and that creates a potential deadlock during shutdown
9063
9065 if (m_avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
9066 return pm.registerProof(proof, state);
9067 })) {
9068 WITH_LOCK(cs_proofrequest, m_proofrequest.ForgetInvId(proofid));
9069 RelayProof(proofid);
9070
9071 node.m_last_proof_time = GetTime<std::chrono::seconds>();
9072
9073 LogPrint(BCLog::NET, "New avalanche proof: peer=%d, proofid %s\n",
9074 nodeid, proofid.ToString());
9075 }
9076
9078 m_avalanche->withPeerManager(
9079 [&](avalanche::PeerManager &pm) { pm.setInvalid(proofid); });
9080 Misbehaving(peer, 100, state.GetRejectReason());
9081 return false;
9082 }
9083
9085 // This is possible that a proof contains a utxo we don't know yet, so
9086 // don't ban for this.
9087 return false;
9088 }
9089
9090 // Unlike other reasons we can expect lots of peers to send a proof that we
9091 // have dangling. In this case we don't want to print a lot of useless debug
9092 // message, the proof will be polled as soon as it's considered again.
9093 if (!m_avalanche->reconcileOrFinalize(proof) &&
9096 "Not polling the avalanche proof (%s): peer=%d, proofid %s\n",
9097 state.IsValid() ? "not-worth-polling"
9098 : state.GetRejectReason(),
9099 nodeid, proofid.ToString());
9100 }
9101
9102 saveProofIfStaker(node, proofid, nodeid);
9103
9104 if (isStaker && m_opts.avalanche_staking_preconsensus) {
9105 WITH_LOCK(cs_main, m_avalanche->addStakeContender(proof));
9106 }
9107
9108 return true;
9109}
bool MoneyRange(const Amount nValue)
Definition amount.h:166
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition amount.h:165
@ READ_STATUS_OK
@ READ_STATUS_INVALID
@ READ_STATUS_FAILED
enum ReadStatus_t ReadStatus
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
BlockFilterType
Definition blockfilter.h:88
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
@ CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition chain.cpp:74
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition chain.cpp:41
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition chain.cpp:89
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition chain.cpp:112
#define Assert(val)
Identity function.
Definition check.h:84
#define Assume(val)
Assume is the identity function.
Definition check.h:97
Stochastic address manager.
Definition addrman.h:68
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
Definition addrman.cpp:1350
void Good(const CService &addr, bool test_before_evict=true, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as accessible, possibly moving it from "new" to "tried".
Definition addrman.cpp:1323
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
Definition addrman.cpp:1318
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Definition addrman.cpp:1354
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:3210
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition net.cpp:3379
bool GetNetworkActive() const
Definition net.h:948
bool GetTryNewOutboundPeer() const
Definition net.cpp:1933
void SetTryNewOutboundPeer(bool flag)
Definition net.cpp:1937
unsigned int GetReceiveFloodSize() const
Definition net.cpp:3257
int GetExtraBlockRelayCount() const
Definition net.cpp:1965
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:1763
void StartExtraBlockRelayPeers()
Definition net.h:1006
bool DisconnectNode(const std::string &node)
Definition net.cpp:3121
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition net.cpp:3391
int GetExtraFullOutboundCount() const
Definition net.cpp:1949
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition net.cpp:3002
bool CheckIncomingNonce(uint64_t nonce)
Definition net.cpp:396
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition net.cpp:1528
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition net.cpp:3333
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:170
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:100
HeadersSyncState:
Definition headerssync.h:98
@ FINAL
We're done syncing with this peer and can discard any remaining state.
@ PRESYNC
PRESYNC means the peer has not yet demonstrated their chain has sufficient work and we're only buildi...
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:18
bool error(const char *fmt, const Args &...args)
Definition logging.h:263
#define LogPrint(category,...)
Definition logging.h:238
#define LogPrintfCategory(category,...)
Definition logging.h:231
#define LogPrintf(...)
Definition logging.h:227
@ AVALANCHE
Definition logging.h:62
@ TXPACKAGES
Definition logging.h:70
@ NETDEBUG
Definition logging.h:69
@ MEMPOOLREJ
Definition logging.h:56
@ MEMPOOL
Definition logging.h:42
@ NET
Definition logging.h:40
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition protocol.cpp:36
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition protocol.cpp:48
const char * AVAPROOFSREQ
Request for missing avalanche proofs after an avaproofs message has been processed.
Definition protocol.cpp:58
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition protocol.cpp:46
const char * BLOCK
The block message transmits a single serialized block.
Definition protocol.cpp:30
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition protocol.cpp:38
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition protocol.cpp:29
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition protocol.cpp:21
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition protocol.cpp:39
const char * AVAPROOFS
The avaproofs message the proof short ids of all the valid proofs that we know.
Definition protocol.cpp:57
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition protocol.cpp:34
const char * GETAVAPROOFS
The getavaproofs message requests an avaproofs message that provides the proof short ids of all the v...
Definition protocol.cpp:56
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition protocol.cpp:41
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition protocol.cpp:31
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition protocol.cpp:49
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition protocol.cpp:35
const char * GETAVAADDR
The getavaaddr message requests an addr message from the receiving node, containing IP addresses of t...
Definition protocol.cpp:55
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition protocol.cpp:42
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition protocol.cpp:32
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition protocol.cpp:45
const char * TX
The tx message transmits a single transaction.
Definition protocol.cpp:28
const char * AVAHELLO
Contains a delegation and a signature.
Definition protocol.cpp:51
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition protocol.cpp:37
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition protocol.cpp:20
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition protocol.cpp:18
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition protocol.cpp:26
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition protocol.cpp:40
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition protocol.cpp:27
const char * AVARESPONSE
Contains an avalanche::Response.
Definition protocol.cpp:53
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition protocol.cpp:24
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition protocol.cpp:19
const char * BLOCKTXN
Contains a BlockTransactions.
Definition protocol.cpp:44
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition protocol.cpp:47
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition protocol.cpp:22
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition protocol.cpp:33
const char * AVAPOLL
Contains an avalanche::Poll.
Definition protocol.cpp:52
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition protocol.cpp:25
const char * AVAPROOF
Contains an avalanche::Proof.
Definition protocol.cpp:54
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition protocol.cpp:50
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition protocol.cpp:43
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition protocol.cpp:23
ShortIdProcessor< PrefilledProof, ShortIdProcessorPrefilledProofAdapter, ProofRefCompare > ProofShortIdProcessor
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:3482
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition net.cpp:599
std::string userAgent(const Config &config)
Definition net.cpp:3431
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