56#include <boost/multi_index/hashed_index.hpp>
57#include <boost/multi_index/member.hpp>
58#include <boost/multi_index/ordered_index.hpp>
59#include <boost/multi_index_container.hpp>
71#include <unordered_set>
120 "Max protocol message length must be greater than largest "
121 "possible INV message");
153 .max_peer_announcements = 5000,
154 .nonpref_peer_delay = 2s,
155 .overloaded_peer_delay = 2s,
156 .getdata_interval = 60s,
157 .bypass_request_limits_permissions =
189 "MAX_BLOCKTXN_DEPTH too high");
248 std::chrono::seconds{1},
249 "INVENTORY_RELAY_MAX too low");
300 std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
305 std::chrono::seconds timeAdded;
307 StalledTxId(
TxId txid_, std::chrono::seconds timeAdded_)
308 : txid(txid_), timeAdded(timeAdded_) {};
314using StalledTxIdSet = boost::multi_index_container<
316 boost::multi_index::indexed_by<
318 boost::multi_index::hashed_unique<
319 boost::multi_index::tag<by_txid>,
320 boost::multi_index::member<StalledTxId, TxId, &StalledTxId::txid>,
323 boost::multi_index::ordered_non_unique<
324 boost::multi_index::tag<by_time>,
325 boost::multi_index::member<StalledTxId, std::chrono::seconds,
326 &StalledTxId::timeAdded>>>>;
363 std::atomic<ServiceFlags> m_their_services{
NODE_NONE};
366 Mutex m_misbehavior_mutex;
371 bool m_should_discourage
GUARDED_BY(m_misbehavior_mutex){
false};
374 Mutex m_block_inv_mutex;
380 std::vector<BlockHash> m_blocks_for_inv_relay
GUARDED_BY(m_block_inv_mutex);
386 std::vector<BlockHash>
387 m_blocks_for_headers_relay
GUARDED_BY(m_block_inv_mutex);
398 std::atomic<int> m_starting_height{-1};
401 std::atomic<uint64_t> m_ping_nonce_sent{0};
403 std::atomic<std::chrono::microseconds> m_ping_start{0us};
405 std::atomic<bool> m_ping_queued{
false};
415 std::chrono::microseconds m_next_send_feefilter
428 bool m_relay_txs
GUARDED_BY(m_bloom_filter_mutex){
false};
433 std::unique_ptr<CBloomFilter>
449 GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
455 std::set<TxId> m_tx_inventory_to_send
GUARDED_BY(m_tx_inventory_mutex);
461 bool m_send_mempool
GUARDED_BY(m_tx_inventory_mutex){
false};
463 std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
468 std::chrono::microseconds
469 m_next_inv_send_time
GUARDED_BY(m_tx_inventory_mutex){0};
475 std::atomic<Amount> m_fee_filter_received{
Amount::zero()};
481 m_avalanche_stalled_txids
GUARDED_BY(m_tx_inventory_mutex);
489 LOCK(m_tx_relay_mutex);
491 m_tx_relay = std::make_unique<Peer::TxRelay>();
492 return m_tx_relay.get();
496 return WITH_LOCK(m_tx_relay_mutex,
return m_tx_relay.get());
498 const TxRelay *GetTxRelay() const
500 return WITH_LOCK(m_tx_relay_mutex,
return m_tx_relay.get());
505 std::set<avalanche::ProofId>
506 m_proof_inventory_to_send
GUARDED_BY(m_proof_inventory_mutex);
509 GUARDED_BY(m_proof_inventory_mutex){10000, 0.000001};
516 std::chrono::microseconds m_next_inv_send_time{0};
520 std::atomic<std::chrono::seconds> lastSharedProofsUpdate{0s};
521 std::atomic<bool> compactproofs_requested{
false};
528 const std::unique_ptr<ProofRelay> m_proof_relay;
547 std::vector<std::chrono::seconds> m_invalid_avaproof_times
553 std::vector<CAddress>
565 std::unique_ptr<CRollingBloomFilter>
583 std::atomic_bool m_addr_relay_enabled{
false};
587 mutable Mutex m_addr_send_times_mutex;
589 std::chrono::microseconds
590 m_next_addr_send
GUARDED_BY(m_addr_send_times_mutex){0};
592 std::chrono::microseconds
593 m_next_local_addr_send
GUARDED_BY(m_addr_send_times_mutex){0};
598 std::atomic_bool m_wants_addrv2{
false};
602 mutable Mutex m_addr_token_bucket_mutex;
607 double m_addr_token_bucket
GUARDED_BY(m_addr_token_bucket_mutex){1.0};
609 std::chrono::microseconds
611 GetTime<std::chrono::microseconds>()};
613 std::atomic<uint64_t> m_addr_rate_limited{0};
618 std::atomic<uint64_t> m_addr_processed{0};
624 bool m_inv_triggered_getheaders_before_sync
628 Mutex m_getdata_requests_mutex;
630 std::deque<CInv> m_getdata_requests
GUARDED_BY(m_getdata_requests_mutex);
637 Mutex m_headers_sync_mutex;
642 std::unique_ptr<HeadersSyncState>
647 std::atomic<bool> m_sent_sendheaders{
false};
650 std::chrono::microseconds m_headers_sync_timeout
661 : m_id(id), m_our_services{our_services},
662 m_proof_relay(fRelayProofs ?
std::make_unique<ProofRelay>()
668 mutable Mutex m_tx_relay_mutex;
671 std::unique_ptr<TxRelay> m_tx_relay
GUARDED_BY(m_tx_relay_mutex);
674using PeerRef = std::shared_ptr<Peer>;
692 bool fSyncStarted{
false};
695 std::chrono::microseconds m_stalling_since{0us};
696 std::list<QueuedBlock> vBlocksInFlight;
699 std::chrono::microseconds m_downloading_since{0us};
701 bool fPreferredDownload{
false};
706 bool m_requested_hb_cmpctblocks{
false};
708 bool m_provides_cmpctblocks{
false};
736 struct ChainSyncTimeoutState {
739 std::chrono::seconds m_timeout{0s};
743 bool m_sent_getheaders{
false};
746 bool m_protect{
false};
749 ChainSyncTimeoutState m_chain_sync;
752 int64_t m_last_block_announcement{0};
755 const bool m_is_inbound;
757 CNodeState(
bool is_inbound) : m_is_inbound(is_inbound) {}
770 const std::shared_ptr<const CBlock> &pblock,
778 bool fInitialDownload)
override
784 const std::shared_ptr<const CBlock> &pblock)
override
793 !m_headers_presync_mutex,
794 !m_tx_download_mutex);
796 std::atomic<bool> &interrupt)
override
799 !m_most_recent_block_mutex, !cs_proofrequest,
800 !m_headers_presync_mutex, g_msgproc_mutex,
801 !m_tx_download_mutex);
805 !m_most_recent_block_mutex, !cs_proofrequest,
806 g_msgproc_mutex, !m_tx_download_mutex);
811 std::optional<std::string>
818 bool IgnoresIncomingTxs()
override {
return m_opts.ignore_incoming_txs; }
820 void RelayTransaction(const
TxId &txid) override
822 void RelayProof(const
avalanche::ProofId &proofid) override
824 void SetBestHeight(
int height)
override { m_best_height = height; };
827 Misbehaving(*
Assert(GetPeerRef(peer_id)),
"");
830 const std::string &msg_type,
DataStream &vRecv,
831 const std::chrono::microseconds time_received,
832 const std::atomic<bool> &interruptMsgProc)
override
835 !m_most_recent_block_mutex, !cs_proofrequest,
836 !m_headers_presync_mutex, g_msgproc_mutex,
837 !m_tx_download_mutex);
839 int64_t time_in_seconds)
override;
846 void ConsiderEviction(
CNode &pto, Peer &peer,
847 std::chrono::seconds time_in_seconds)
854 void EvictExtraOutboundPeers(std::chrono::seconds now)
861 void ReattemptInitialBroadcast(
CScheduler &scheduler)
867 void UpdateAvalancheStatistics()
const;
872 void AvalanchePeriodicNetworking(
CScheduler &scheduler)
const;
890 void Misbehaving(Peer &peer,
const std::string &message);
902 void MaybePunishNodeForBlock(
NodeId nodeid,
904 bool via_compact_block,
905 const std::string &message =
"")
913 const
std::
string &message = "")
925 bool MaybeDiscourageAndDisconnect(
CNode &pnode, Peer &peer);
947 std::optional<
node::PackageToValidate>
951 m_tx_download_mutex);
960 m_tx_download_mutex);
968 ProcessPackageResult(const
node::PackageToValidate &package_to_validate,
971 m_tx_download_mutex);
988 bool ProcessOrphanTx(const
Config &config, Peer &peer)
990 !m_tx_download_mutex);
1002 void ProcessHeadersMessage(const
Config &config,
CNode &pfrom, Peer &peer,
1004 bool via_compact_block)
1024 void HandleUnconnectingHeaders(
CNode &pfrom, Peer &peer,
1029 CheckHeadersAreContinuous(const
std::vector<
CBlockHeader> &headers) const;
1049 bool IsContinuationOfLowWorkHeadersSync(Peer &peer,
CNode &pfrom,
1052 !m_headers_presync_mutex, g_msgproc_mutex);
1066 bool TryLowWorkHeadersSync(Peer &peer,
CNode &pfrom,
1070 !m_headers_presync_mutex, g_msgproc_mutex);
1076 bool IsAncestorOfBestHeaderOrTip(const
CBlockIndex *header)
1090 void HeadersDirectFetchBlocks(const
Config &config,
CNode &pfrom,
1093 void UpdatePeerStateForReceivedHeaders(
CNode &pfrom, Peer &peer,
1095 bool received_new_header,
1096 bool may_have_more_headers)
1099 void SendBlockTransactions(
CNode &pfrom, Peer &peer, const
CBlock &block,
1109 std::chrono::microseconds current_time,
bool preferred)
1114 m_connman.PushMessage(&
node, std::move(msg));
1116 template <
typename... Args>
1117 void MakeAndPushMessage(
CNode &
node, std::string msg_type,
1118 Args &&...args)
const {
1120 std::forward<Args>(args)...));
1124 void PushNodeVersion(
const Config &config,
CNode &pnode,
const Peer &peer);
1132 void MaybeSendPing(
CNode &node_to, Peer &peer,
1133 std::chrono::microseconds now);
1136 void MaybeSendAddr(
CNode &
node, Peer &peer,
1137 std::chrono::microseconds current_time)
1144 void MaybeSendSendHeaders(
CNode &
node, Peer &peer)
1148 void MaybeSendFeefilter(
CNode &
node, Peer &peer,
1149 std::chrono::microseconds current_time)
1161 void RelayAddress(
NodeId originator,
const CAddress &addr,
bool fReachable)
1196 Mutex cs_proofrequest;
1201 std::atomic<int> m_best_height{-1};
1204 std::chrono::seconds m_stale_tip_check_time
GUARDED_BY(cs_main){0s};
1206 const Options m_opts;
1208 bool RejectIncomingTxs(
const CNode &peer)
const;
1214 bool m_initial_sync_finished
GUARDED_BY(cs_main){
false};
1220 mutable Mutex m_peer_mutex;
1227 std::map<NodeId, PeerRef> m_peer_map
GUARDED_BY(m_peer_mutex);
1230 std::map<NodeId, CNodeState> m_node_states
GUARDED_BY(cs_main);
1236 const CNodeState *State(
NodeId pnode)
const
1241 std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us};
1248 m_last_block_inv_triggering_headers_sync
GUARDED_BY(g_msgproc_mutex){};
1256 std::map<BlockHash, std::pair<NodeId, bool>>
1260 int m_outbound_peers_with_protect_from_disconnect
GUARDED_BY(cs_main) = 0;
1263 int m_num_preferred_download_peers
GUARDED_BY(cs_main){0};
1266 std::atomic<std::chrono::seconds> m_block_stalling_timeout{
1276 std::chrono::microseconds
1277 NextInvToInbounds(std::chrono::microseconds now,
1278 std::chrono::seconds average_interval)
1283 mutable Mutex m_most_recent_block_mutex;
1284 std::shared_ptr<const CBlock>
1285 m_most_recent_block
GUARDED_BY(m_most_recent_block_mutex);
1286 std::shared_ptr<const CBlockHeaderAndShortTxIDs>
1287 m_most_recent_compact_block
GUARDED_BY(m_most_recent_block_mutex);
1289 std::unique_ptr<const std::map<TxId, CTransactionRef>>
1290 m_most_recent_block_txs
GUARDED_BY(m_most_recent_block_mutex);
1295 Mutex m_headers_presync_mutex;
1306 using HeadersPresyncStats =
1307 std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>;
1309 std::map<NodeId, HeadersPresyncStats>
1310 m_headers_presync_stats
GUARDED_BY(m_headers_presync_mutex){};
1314 std::atomic_bool m_headers_presync_should_signal{
false};
1319 int m_highest_fast_announce
GUARDED_BY(::cs_main){0};
1322 bool IsBlockRequested(
const BlockHash &hash)
1326 bool IsBlockRequestedFromOutbound(
const BlockHash &hash)
1337 void RemoveBlockRequest(
const BlockHash &hash,
1338 std::optional<NodeId> from_peer)
1347 bool BlockRequested(
const Config &config,
NodeId nodeid,
1349 std::list<QueuedBlock>::iterator **pit =
nullptr)
1358 void FindNextBlocksToDownload(const Peer &peer,
unsigned int count,
1364 void TryDownloadingHistoricalBlocks(
1365 const Peer &peer,
unsigned int count,
1399 const Peer &peer, CNodeState *state,
1401 int nWindowEnd, const
CChain *activeChain =
nullptr,
1402 NodeId *nodeStaller =
nullptr)
1409 BlockDownloadMap mapBlocksInFlight
GUARDED_BY(cs_main);
1412 std::atomic<
std::chrono::seconds> m_last_tip_update{0s};
1419 const std::chrono::seconds mempool_req,
1420 const std::chrono::seconds now)
1425 void ProcessGetData(
const Config &config,
CNode &pfrom, Peer &peer,
1426 const std::atomic<bool> &interruptMsgProc)
1428 peer.m_getdata_requests_mutex,
1434 const std::shared_ptr<const CBlock> &block,
1435 bool force_processing,
bool min_pow_checked);
1438 void ProcessCompactBlockTxns(
const Config &config,
CNode &pfrom, Peer &peer,
1448 void MaybeSetPeerAsAnnouncingHeaderAndIDs(
NodeId nodeid)
1452 std::list<NodeId> lNodesAnnouncingHeaderAndIDs
GUARDED_BY(cs_main);
1455 int m_peers_downloading_from
GUARDED_BY(cs_main) = 0;
1467 std::vector<CTransactionRef>
1468 vExtraTxnForCompact
GUARDED_BY(g_msgproc_mutex);
1470 size_t vExtraTxnForCompactIt
GUARDED_BY(g_msgproc_mutex) = 0;
1475 void ProcessBlockAvailability(
NodeId nodeid)
1490 bool BlockRequestAllowed(const
CBlockIndex *pindex)
1492 bool AlreadyHaveBlock(const
BlockHash &block_hash)
1494 bool AlreadyHaveProof(const
avalanche::ProofId &proofid);
1495 void ProcessGetBlockData(const
Config &config,
CNode &pfrom, Peer &peer,
1518 bool PrepareBlockFilterRequest(
CNode &
node, Peer &peer,
1520 uint32_t start_height,
1522 uint32_t max_height_diff,
1564 uint32_t GetAvalancheVoteForBlock(const
BlockHash &hash) const
1585 bool SetupAddressRelay(const
CNode &
node, Peer &peer)
1588 void AddAddressKnown(Peer &peer, const
CAddress &addr)
1590 void PushAddress(Peer &peer, const
CAddress &addr)
1598 bool ReceivedAvalancheProof(
CNode &
node, Peer &peer,
1603 avalanche::ProofRef FindProofForGetData(const Peer &peer,
1605 const
std::chrono::seconds now)
1608 bool isPreferredDownloadPeer(const
CNode &pfrom);
1611const CNodeState *PeerManagerImpl::State(
NodeId pnode) const
1613 std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
1614 if (it == m_node_states.end()) {
1621CNodeState *PeerManagerImpl::State(
NodeId pnode)
1623 return const_cast<CNodeState *
>(std::as_const(*this).State(pnode));
1631static bool IsAddrCompatible(
const Peer &peer,
const CAddress &addr) {
1635void PeerManagerImpl::AddAddressKnown(Peer &peer,
const CAddress &addr) {
1636 assert(peer.m_addr_known);
1637 peer.m_addr_known->insert(addr.
GetKey());
1640void PeerManagerImpl::PushAddress(Peer &peer,
const CAddress &addr) {
1644 assert(peer.m_addr_known);
1645 if (addr.
IsValid() && !peer.m_addr_known->contains(addr.
GetKey()) &&
1646 IsAddrCompatible(peer, addr)) {
1647 if (peer.m_addrs_to_send.size() >= m_opts.max_addr_to_send) {
1648 peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] =
1651 peer.m_addrs_to_send.push_back(addr);
1656static void AddKnownTx(Peer &peer,
const TxId &txid) {
1657 auto tx_relay = peer.GetTxRelay();
1662 LOCK(tx_relay->m_tx_inventory_mutex);
1663 tx_relay->m_tx_inventory_known_filter.insert(txid);
1667 if (peer.m_proof_relay !=
nullptr) {
1668 LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
1669 peer.m_proof_relay->m_proof_inventory_known_filter.insert(proofid);
1673bool PeerManagerImpl::isPreferredDownloadPeer(
const CNode &pfrom) {
1675 const CNodeState *state = State(pfrom.
GetId());
1676 return state && state->fPreferredDownload;
1679static bool CanServeBlocks(
const Peer &peer) {
1687static bool IsLimitedPeer(
const Peer &peer) {
1692std::chrono::microseconds
1693PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
1694 std::chrono::seconds average_interval) {
1695 if (m_next_inv_to_inbounds.load() < now) {
1700 m_next_inv_to_inbounds =
1701 now + m_rng.rand_exp_duration(average_interval);
1703 return m_next_inv_to_inbounds;
1706bool PeerManagerImpl::IsBlockRequested(
const BlockHash &hash) {
1707 return mapBlocksInFlight.count(hash);
1710bool PeerManagerImpl::IsBlockRequestedFromOutbound(
const BlockHash &hash) {
1711 for (
auto range = mapBlocksInFlight.equal_range(hash);
1712 range.first != range.second; range.first++) {
1713 auto [nodeid, block_it] = range.first->second;
1714 CNodeState &nodestate = *
Assert(State(nodeid));
1715 if (!nodestate.m_is_inbound) {
1723void PeerManagerImpl::RemoveBlockRequest(
const BlockHash &hash,
1724 std::optional<NodeId> from_peer) {
1725 auto range = mapBlocksInFlight.equal_range(hash);
1726 if (range.first == range.second) {
1734 while (range.first != range.second) {
1735 auto [node_id, list_it] = range.first->second;
1737 if (from_peer && *from_peer != node_id) {
1742 CNodeState &state = *
Assert(State(node_id));
1744 if (state.vBlocksInFlight.begin() == list_it) {
1747 state.m_downloading_since =
1748 std::max(state.m_downloading_since,
1749 GetTime<std::chrono::microseconds>());
1751 state.vBlocksInFlight.erase(list_it);
1753 if (state.vBlocksInFlight.empty()) {
1755 m_peers_downloading_from--;
1757 state.m_stalling_since = 0us;
1759 range.first = mapBlocksInFlight.erase(range.first);
1763bool PeerManagerImpl::BlockRequested(
const Config &config,
NodeId nodeid,
1765 std::list<QueuedBlock>::iterator **pit) {
1768 CNodeState *state = State(nodeid);
1769 assert(state !=
nullptr);
1774 for (
auto range = mapBlocksInFlight.equal_range(hash);
1775 range.first != range.second; range.first++) {
1776 if (range.first->second.first == nodeid) {
1778 *pit = &range.first->second.second;
1785 RemoveBlockRequest(hash, nodeid);
1787 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(
1788 state->vBlocksInFlight.end(),
1789 {&block, std::unique_ptr<PartiallyDownloadedBlock>(
1790 pit ? new PartiallyDownloadedBlock(config, &m_mempool)
1792 if (state->vBlocksInFlight.size() == 1) {
1794 state->m_downloading_since = GetTime<std::chrono::microseconds>();
1795 m_peers_downloading_from++;
1798 auto itInFlight = mapBlocksInFlight.insert(
1799 std::make_pair(hash, std::make_pair(nodeid, it)));
1802 *pit = &itInFlight->second.second;
1808void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(
NodeId nodeid) {
1814 if (m_opts.ignore_incoming_txs) {
1818 CNodeState *nodestate = State(nodeid);
1823 if (!nodestate->m_provides_cmpctblocks) {
1826 int num_outbound_hb_peers = 0;
1827 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin();
1828 it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
1829 if (*it == nodeid) {
1830 lNodesAnnouncingHeaderAndIDs.erase(it);
1831 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
1834 CNodeState *state = State(*it);
1835 if (state !=
nullptr && !state->m_is_inbound) {
1836 ++num_outbound_hb_peers;
1839 if (nodestate->m_is_inbound) {
1842 if (lNodesAnnouncingHeaderAndIDs.size() >= 3 &&
1843 num_outbound_hb_peers == 1) {
1844 CNodeState *remove_node =
1845 State(lNodesAnnouncingHeaderAndIDs.front());
1846 if (remove_node !=
nullptr && !remove_node->m_is_inbound) {
1849 std::swap(lNodesAnnouncingHeaderAndIDs.front(),
1850 *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
1857 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
1861 lNodesAnnouncingHeaderAndIDs.front(), [
this](
CNode *pnodeStop) {
1862 MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT,
1864 CMPCTBLOCKS_VERSION);
1867 pnodeStop->m_bip152_highbandwidth_to = false;
1870 lNodesAnnouncingHeaderAndIDs.pop_front();
1877 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->
GetId());
1882bool PeerManagerImpl::TipMayBeStale() {
1885 if (m_last_tip_update.load() == 0s) {
1886 m_last_tip_update = GetTime<std::chrono::seconds>();
1888 return m_last_tip_update.load() <
1889 GetTime<std::chrono::seconds>() -
1892 mapBlocksInFlight.empty();
1895bool PeerManagerImpl::CanDirectFetch() {
1901static bool PeerHasHeader(CNodeState *state,
const CBlockIndex *pindex)
1903 if (state->pindexBestKnownBlock &&
1904 pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) {
1907 if (state->pindexBestHeaderSent &&
1908 pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) {
1914void PeerManagerImpl::ProcessBlockAvailability(
NodeId nodeid) {
1915 CNodeState *state = State(nodeid);
1916 assert(state !=
nullptr);
1918 if (!state->hashLastUnknownBlock.IsNull()) {
1922 if (state->pindexBestKnownBlock ==
nullptr ||
1923 pindex->
nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1924 state->pindexBestKnownBlock = pindex;
1926 state->hashLastUnknownBlock.SetNull();
1931void PeerManagerImpl::UpdateBlockAvailability(
NodeId nodeid,
1933 CNodeState *state = State(nodeid);
1934 assert(state !=
nullptr);
1936 ProcessBlockAvailability(nodeid);
1941 if (state->pindexBestKnownBlock ==
nullptr ||
1942 pindex->
nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1943 state->pindexBestKnownBlock = pindex;
1948 state->hashLastUnknownBlock = hash;
1954void PeerManagerImpl::FindNextBlocksToDownload(
1955 const Peer &peer,
unsigned int count,
1956 std::vector<const CBlockIndex *> &vBlocks,
NodeId &nodeStaller) {
1961 vBlocks.reserve(vBlocks.size() +
count);
1962 CNodeState *state = State(peer.m_id);
1963 assert(state !=
nullptr);
1966 ProcessBlockAvailability(peer.m_id);
1968 if (state->pindexBestKnownBlock ==
nullptr ||
1969 state->pindexBestKnownBlock->nChainWork <
1971 state->pindexBestKnownBlock->nChainWork <
1981 const CBlockIndex *snap_base{m_chainman.GetSnapshotBaseBlock()};
1982 if (snap_base && state->pindexBestKnownBlock->GetAncestor(
1983 snap_base->nHeight) != snap_base) {
1985 "Not downloading blocks from peer=%d, which doesn't have the "
1986 "snapshot block in its best chain.\n",
1995 if (state->pindexLastCommonBlock ==
nullptr ||
1997 state->pindexLastCommonBlock->nHeight < snap_base->nHeight)) {
1998 state->pindexLastCommonBlock =
2000 .
ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight,
2007 state->pindexLastCommonBlock, state->pindexBestKnownBlock);
2008 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) {
2012 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
2020 FindNextBlocks(vBlocks, peer, state, pindexWalk,
count, nWindowEnd,
2024void PeerManagerImpl::TryDownloadingHistoricalBlocks(
2025 const Peer &peer,
unsigned int count,
2026 std::vector<const CBlockIndex *> &vBlocks,
const CBlockIndex *from_tip,
2031 if (vBlocks.size() >=
count) {
2035 vBlocks.reserve(
count);
2036 CNodeState *state =
Assert(State(peer.m_id));
2038 if (state->pindexBestKnownBlock ==
nullptr ||
2039 state->pindexBestKnownBlock->GetAncestor(target_block->
nHeight) !=
2054 FindNextBlocks(vBlocks, peer, state, from_tip,
count,
2059void PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex *> &vBlocks,
2060 const Peer &peer, CNodeState *state,
2062 unsigned int count,
int nWindowEnd,
2063 const CChain *activeChain,
2065 std::vector<const CBlockIndex *> vToFetch;
2067 std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
2069 while (pindexWalk->
nHeight < nMaxHeight) {
2074 int nToFetch = std::min(nMaxHeight - pindexWalk->
nHeight,
2075 std::max<int>(
count - vBlocks.size(), 128));
2076 vToFetch.resize(nToFetch);
2077 pindexWalk = state->pindexBestKnownBlock->GetAncestor(
2078 pindexWalk->
nHeight + nToFetch);
2079 vToFetch[nToFetch - 1] = pindexWalk;
2080 for (
unsigned int i = nToFetch - 1; i > 0; i--) {
2081 vToFetch[i - 1] = vToFetch[i]->
pprev;
2094 if (pindex->nStatus.hasData() ||
2095 (activeChain && activeChain->
Contains(pindex))) {
2097 state->pindexLastCommonBlock = pindex;
2099 }
else if (!IsBlockRequested(pindex->
GetBlockHash())) {
2101 if (pindex->
nHeight > nWindowEnd) {
2103 if (vBlocks.size() == 0 && waitingfor != peer.m_id) {
2107 *nodeStaller = waitingfor;
2112 vBlocks.push_back(pindex);
2113 if (vBlocks.size() ==
count) {
2116 }
else if (waitingfor == -1) {
2128void PeerManagerImpl::PushNodeVersion(
const Config &config,
CNode &pnode,
2130 uint64_t my_services{peer.m_our_services};
2131 const int64_t nTime{
count_seconds(GetTime<std::chrono::seconds>())};
2133 const int nNodeStartingHeight{m_best_height};
2144 const bool tx_relay{!RejectIncomingTxs(pnode)};
2153 nNodeStartingHeight, tx_relay, extraEntropy);
2157 "send version message: version %d, blocks=%d, them=%s, "
2158 "txrelay=%d, peer=%d\n",
2163 "send version message: version %d, blocks=%d, "
2164 "txrelay=%d, peer=%d\n",
2169void PeerManagerImpl::AddProofAnnouncement(
2171 std::chrono::microseconds current_time,
bool preferred) {
2175 const bool bypass_limits =
node.HasPermission(
2184 current_time, preferred, bypass_limits);
2186 m_proofrequest.ReceivedInv(
node.GetId(), proofid, preferred, reqtime);
2189void PeerManagerImpl::UpdateLastBlockAnnounceTime(
NodeId node,
2190 int64_t time_in_seconds) {
2192 CNodeState *state = State(
node);
2194 state->m_last_block_announcement = time_in_seconds;
2198void PeerManagerImpl::InitializeNode(
const Config &config,
CNode &
node,
2203 m_node_states.emplace_hint(m_node_states.end(),
2204 std::piecewise_construct,
2205 std::forward_as_tuple(nodeid),
2206 std::forward_as_tuple(
node.IsInboundConn()));
2208 WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty(nodeid));
2215 PeerRef peer = std::make_shared<Peer>(nodeid, our_services, !!m_avalanche);
2218 m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
2220 if (!
node.IsInboundConn()) {
2221 PushNodeVersion(config,
node, *peer);
2225void PeerManagerImpl::ReattemptInitialBroadcast(
CScheduler &scheduler) {
2228 for (
const TxId &txid : unbroadcast_txids) {
2230 if (m_mempool.
exists(txid)) {
2231 RelayTransaction(txid);
2242 auto unbroadcasted_proofids =
2246 auto it = unbroadcasted_proofids.begin();
2247 while (it != unbroadcasted_proofids.end()) {
2250 if (!pm.isBoundToPeer(*it)) {
2251 pm.removeUnbroadcastProof(*it);
2252 it = unbroadcasted_proofids.erase(it);
2259 return unbroadcasted_proofids;
2263 for (
const auto &proofid : unbroadcasted_proofids) {
2264 RelayProof(proofid);
2271 const auto reattemptBroadcastInterval =
2273 scheduler.
scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2274 reattemptBroadcastInterval);
2277void PeerManagerImpl::UpdateAvalancheStatistics()
const {
2283void PeerManagerImpl::AvalanchePeriodicNetworking(
CScheduler &scheduler)
const {
2284 const auto now = GetTime<std::chrono::seconds>();
2285 std::vector<NodeId> avanode_ids;
2286 bool fQuorumEstablished;
2287 bool fShouldRequestMoreNodes;
2297 fShouldRequestMoreNodes =
2305 avanode_ids.push_back(pnode->GetId());
2308 PeerRef peer = GetPeerRef(pnode->
GetId());
2309 if (peer ==
nullptr) {
2313 if (peer->m_proof_relay &&
2314 now > (peer->m_proof_relay->lastSharedProofsUpdate.load() +
2316 peer->m_proof_relay->sharedProofs = {};
2320 if (avanode_ids.empty()) {
2328 for (
NodeId avanodeId : avanode_ids) {
2329 const bool sentGetavaaddr =
2332 MakeAndPushMessage(*pavanode, NetMsgType::GETAVAADDR);
2333 PeerRef peer = GetPeerRef(avanodeId);
2334 WITH_LOCK(peer->m_addr_token_bucket_mutex,
2335 peer->m_addr_token_bucket +=
2336 m_opts.max_addr_to_send);
2344 if (sentGetavaaddr && fQuorumEstablished && !fShouldRequestMoreNodes) {
2359 avanode_ids.resize(std::min<size_t>(avanode_ids.size(), 3));
2362 for (
NodeId nodeid : avanode_ids) {
2365 PeerRef peer = GetPeerRef(nodeid);
2366 if (peer->m_proof_relay) {
2368 peer->m_proof_relay->compactproofs_requested =
true;
2378 const auto avalanchePeriodicNetworkingInterval =
2380 scheduler.
scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2381 avalanchePeriodicNetworkingInterval);
2384void PeerManagerImpl::FinalizeNode(
const Config &config,
const CNode &
node) {
2394 PeerRef peer = RemovePeer(nodeid);
2397 m_peer_map.erase(nodeid);
2399 CNodeState *state = State(nodeid);
2400 assert(state !=
nullptr);
2402 if (state->fSyncStarted) {
2406 for (
const QueuedBlock &entry : state->vBlocksInFlight) {
2408 mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash());
2409 while (range.first != range.second) {
2410 auto [node_id, list_it] = range.first->second;
2411 if (node_id != nodeid) {
2414 range.first = mapBlocksInFlight.erase(range.first);
2419 LOCK(m_tx_download_mutex);
2420 m_txdownloadman.DisconnectedPeer(nodeid);
2422 m_num_preferred_download_peers -= state->fPreferredDownload;
2423 m_peers_downloading_from -= (!state->vBlocksInFlight.empty());
2424 assert(m_peers_downloading_from >= 0);
2425 m_outbound_peers_with_protect_from_disconnect -=
2426 state->m_chain_sync.m_protect;
2427 assert(m_outbound_peers_with_protect_from_disconnect >= 0);
2429 m_node_states.erase(nodeid);
2431 if (m_node_states.empty()) {
2433 assert(mapBlocksInFlight.empty());
2434 assert(m_num_preferred_download_peers == 0);
2435 assert(m_peers_downloading_from == 0);
2436 assert(m_outbound_peers_with_protect_from_disconnect == 0);
2437 WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty());
2441 if (
node.fSuccessfullyConnected && !
node.IsBlockOnlyConn() &&
2442 !
node.IsInboundConn()) {
2449 LOCK(m_headers_presync_mutex);
2450 m_headers_presync_stats.erase(nodeid);
2453 WITH_LOCK(cs_proofrequest, m_proofrequest.DisconnectedPeer(nodeid));
2458PeerRef PeerManagerImpl::GetPeerRef(
NodeId id)
const {
2460 auto it = m_peer_map.find(
id);
2461 return it != m_peer_map.end() ? it->second :
nullptr;
2464PeerRef PeerManagerImpl::RemovePeer(
NodeId id) {
2467 auto it = m_peer_map.find(
id);
2468 if (it != m_peer_map.end()) {
2469 ret = std::move(it->second);
2470 m_peer_map.erase(it);
2475bool PeerManagerImpl::GetNodeStateStats(
NodeId nodeid,
2479 const CNodeState *state = State(nodeid);
2480 if (state ==
nullptr) {
2484 ? state->pindexBestKnownBlock->nHeight
2487 ? state->pindexLastCommonBlock->nHeight
2489 for (
const QueuedBlock &queue : state->vBlocksInFlight) {
2496 PeerRef peer = GetPeerRef(nodeid);
2497 if (peer ==
nullptr) {
2509 auto ping_wait{0us};
2510 if ((0 != peer->m_ping_nonce_sent) &&
2511 (0 != peer->m_ping_start.load().count())) {
2513 GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
2516 if (
auto tx_relay = peer->GetTxRelay()) {
2518 return tx_relay->m_relay_txs);
2530 LOCK(peer->m_headers_sync_mutex);
2531 if (peer->m_headers_sync) {
2539std::vector<TxOrphanage::PoolTx> PeerManagerImpl::GetOrphanTransactions() {
2540 LOCK(m_tx_download_mutex);
2541 return m_txdownloadman.GetOrphanTransactions();
2544void PeerManagerImpl::AddToCompactExtraTransactions(
const CTransactionRef &tx) {
2545 if (m_opts.max_extra_txs <= 0) {
2549 if (!vExtraTxnForCompact.size()) {
2550 vExtraTxnForCompact.resize(m_opts.max_extra_txs);
2553 vExtraTxnForCompact[vExtraTxnForCompactIt] = tx;
2554 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs;
2557void PeerManagerImpl::Misbehaving(Peer &peer,
const std::string &message) {
2558 LOCK(peer.m_misbehavior_mutex);
2560 const std::string message_prefixed =
2561 message.empty() ?
"" : (
": " + message);
2562 peer.m_should_discourage =
true;
2567void PeerManagerImpl::MaybePunishNodeForBlock(
NodeId nodeid,
2569 bool via_compact_block,
2570 const std::string &message) {
2571 PeerRef peer{GetPeerRef(nodeid)};
2582 if (!via_compact_block) {
2584 Misbehaving(*peer, message);
2591 CNodeState *node_state = State(nodeid);
2592 if (node_state ==
nullptr) {
2599 if (!via_compact_block && !node_state->m_is_inbound) {
2601 Misbehaving(*peer, message);
2611 Misbehaving(*peer, message);
2617 Misbehaving(*peer, message);
2623 if (message !=
"") {
2628void PeerManagerImpl::MaybePunishNodeForTx(
NodeId nodeid,
2630 const std::string &message) {
2631 PeerRef peer{GetPeerRef(nodeid)};
2638 Misbehaving(*peer, message);
2656 if (message !=
"") {
2661bool PeerManagerImpl::BlockRequestAllowed(
const CBlockIndex *pindex) {
2667 (m_chainman.m_best_header !=
nullptr) &&
2668 (m_chainman.m_best_header->GetBlockTime() - pindex->
GetBlockTime() <
2671 *m_chainman.m_best_header, *pindex, *m_chainman.m_best_header,
2675std::optional<std::string>
2676PeerManagerImpl::FetchBlock(
const Config &config,
NodeId peer_id,
2679 return "Loading blocks ...";
2685 CNodeState *state = State(peer_id);
2686 if (state ==
nullptr) {
2687 return "Peer does not exist";
2691 RemoveBlockRequest(block_index.
GetBlockHash(), std::nullopt);
2696 if (!BlockRequested(config, peer_id, block_index)) {
2697 return "Already requested from this peer";
2706 this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs);
2709 return "Node not fully connected";
2714 return std::nullopt;
2717std::unique_ptr<PeerManager>
2721 return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman,
2730 : m_rng{opts.deterministic_rng},
2732 m_chainparams(chainman.GetParams()), m_connman(connman),
2733 m_addrman(addrman), m_banman(banman), m_chainman(chainman),
2734 m_mempool(pool), m_avalanche(
avalanche),
2735 m_txdownloadman(
node::TxDownloadOptions{pool, opts.max_orphan_txs,
2736 opts.deterministic_rng}),
2739void PeerManagerImpl::StartScheduledTasks(
CScheduler &scheduler) {
2746 "peer eviction timer should be less than stale tip check timer");
2749 this->CheckForStaleTipAndEvictPeers();
2755 const auto reattemptBroadcastInterval =
2757 scheduler.
scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2758 reattemptBroadcastInterval);
2763 UpdateAvalancheStatistics();
2769 const auto avalanchePeriodicNetworkingInterval =
2771 scheduler.
scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2772 avalanchePeriodicNetworkingInterval);
2775void PeerManagerImpl::ActiveTipChange(
const CBlockIndex &new_tip,
bool is_ibd) {
2782 LOCK(m_tx_download_mutex);
2786 m_txdownloadman.ActiveTipChange();
2796void PeerManagerImpl::BlockConnected(
2797 ChainstateRole role,
const std::shared_ptr<const CBlock> &pblock,
2801 m_last_tip_update = GetTime<std::chrono::seconds>();
2805 auto stalling_timeout = m_block_stalling_timeout.load();
2808 const auto new_timeout =
2809 std::max(std::chrono::duration_cast<std::chrono::seconds>(
2810 stalling_timeout * 0.85),
2812 if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout,
2824 LOCK(m_tx_download_mutex);
2825 m_txdownloadman.BlockConnected(pblock);
2828void PeerManagerImpl::BlockDisconnected(
2829 const std::shared_ptr<const CBlock> &block,
const CBlockIndex *pindex) {
2830 LOCK(m_tx_download_mutex);
2831 m_txdownloadman.BlockDisconnected();
2838void PeerManagerImpl::NewPoWValidBlock(
2839 const CBlockIndex *pindex,
const std::shared_ptr<const CBlock> &pblock) {
2840 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock =
2841 std::make_shared<const CBlockHeaderAndShortTxIDs>(
2846 if (pindex->
nHeight <= m_highest_fast_announce) {
2849 m_highest_fast_announce = pindex->
nHeight;
2852 const std::shared_future<CSerializedNetMsg> lazy_ser{
2853 std::async(std::launch::deferred, [&] {
2858 auto most_recent_block_txs =
2859 std::make_unique<std::map<TxId, CTransactionRef>>();
2860 for (
const auto &tx : pblock->vtx) {
2861 most_recent_block_txs->emplace(tx->GetId(), tx);
2864 LOCK(m_most_recent_block_mutex);
2865 m_most_recent_block_hash = hashBlock;
2866 m_most_recent_block = pblock;
2867 m_most_recent_compact_block = pcmpctblock;
2868 m_most_recent_block_txs = std::move(most_recent_block_txs);
2872 [
this, pindex, &lazy_ser, &hashBlock](
CNode *pnode)
2879 ProcessBlockAvailability(pnode->
GetId());
2880 CNodeState &state = *State(pnode->
GetId());
2884 if (state.m_requested_hb_cmpctblocks &&
2885 !PeerHasHeader(&state, pindex) &&
2886 PeerHasHeader(&state, pindex->
pprev)) {
2888 "%s sending header-and-ids %s to peer=%d\n",
2889 "PeerManager::NewPoWValidBlock",
2890 hashBlock.ToString(), pnode->
GetId());
2893 PushMessage(*pnode, ser_cmpctblock.Copy());
2894 state.pindexBestHeaderSent = pindex;
2903void PeerManagerImpl::UpdatedBlockTip(
const CBlockIndex *pindexNew,
2905 bool fInitialDownload) {
2906 SetBestHeight(pindexNew->
nHeight);
2910 if (fInitialDownload) {
2915 std::vector<BlockHash> vHashes;
2917 while (pindexToAnnounce != pindexFork) {
2919 pindexToAnnounce = pindexToAnnounce->
pprev;
2929 for (
auto &it : m_peer_map) {
2930 Peer &peer = *it.second;
2931 LOCK(peer.m_block_inv_mutex);
2933 peer.m_blocks_for_headers_relay.push_back(hash);
2945void PeerManagerImpl::BlockChecked(
const CBlock &block,
2950 std::map<BlockHash, std::pair<NodeId, bool>>::iterator it =
2951 mapBlockSource.find(hash);
2955 if (state.
IsInvalid() && it != mapBlockSource.end() &&
2956 State(it->second.first)) {
2957 MaybePunishNodeForBlock(it->second.first, state,
2958 !it->second.second);
2967 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
2968 if (it != mapBlockSource.end()) {
2969 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
2973 if (it != mapBlockSource.end()) {
2974 mapBlockSource.erase(it);
2983bool PeerManagerImpl::AlreadyHaveBlock(
const BlockHash &block_hash) {
2988 if (!
Assume(m_avalanche)) {
2993 if (localProof && localProof->getId() == proofid) {
3002void PeerManagerImpl::SendPings() {
3004 for (
auto &it : m_peer_map) {
3005 it.second->m_ping_queued =
true;
3009void PeerManagerImpl::RelayTransaction(
const TxId &txid) {
3011 for (
auto &it : m_peer_map) {
3012 Peer &peer = *it.second;
3013 auto tx_relay = peer.GetTxRelay();
3017 LOCK(tx_relay->m_tx_inventory_mutex);
3023 if (tx_relay->m_next_inv_send_time == 0s) {
3027 if (!tx_relay->m_tx_inventory_known_filter.contains(txid) ||
3028 tx_relay->m_avalanche_stalled_txids.count(txid) > 0) {
3029 tx_relay->m_tx_inventory_to_send.insert(txid);
3036 for (
auto &it : m_peer_map) {
3037 Peer &peer = *it.second;
3039 if (!peer.m_proof_relay) {
3042 LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
3043 if (!peer.m_proof_relay->m_proof_inventory_known_filter.contains(
3045 peer.m_proof_relay->m_proof_inventory_to_send.insert(proofid);
3050void PeerManagerImpl::RelayAddress(
NodeId originator,
const CAddress &addr,
3066 const auto current_time{GetTime<std::chrono::seconds>()};
3069 const uint64_t time_addr{
3070 (
static_cast<uint64_t
>(
count_seconds(current_time)) + hash_addr) /
3080 unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
3081 std::array<std::pair<uint64_t, Peer *>, 2> best{
3082 {{0,
nullptr}, {0,
nullptr}}};
3083 assert(nRelayNodes <= best.size());
3087 for (
auto &[
id, peer] : m_peer_map) {
3088 if (peer->m_addr_relay_enabled &&
id != originator &&
3089 IsAddrCompatible(*peer, addr)) {
3091 for (
unsigned int i = 0; i < nRelayNodes; i++) {
3092 if (hashKey > best[i].first) {
3093 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1,
3094 best.begin() + i + 1);
3095 best[i] = std::make_pair(hashKey, peer.get());
3102 for (
unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
3103 PushAddress(*best[i].second, addr);
3107void PeerManagerImpl::ProcessGetBlockData(
const Config &config,
CNode &pfrom,
3108 Peer &peer,
const CInv &inv) {
3111 std::shared_ptr<const CBlock> a_recent_block;
3112 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
3114 LOCK(m_most_recent_block_mutex);
3115 a_recent_block = m_most_recent_block;
3116 a_recent_compact_block = m_most_recent_compact_block;
3119 bool need_activate_chain =
false;
3133 need_activate_chain =
true;
3137 if (need_activate_chain) {
3140 state, a_recent_block, m_avalanche)) {
3148 bool can_direct_fetch{
false};
3156 if (!BlockRequestAllowed(pindex)) {
3158 "%s: ignoring request from peer=%i for old "
3159 "block that isn't in the main chain\n",
3160 __func__, pfrom.
GetId());
3166 (((m_chainman.m_best_header !=
nullptr) &&
3167 (m_chainman.m_best_header->GetBlockTime() -
3175 "historical block serving limit reached, disconnect peer=%d\n",
3188 (tip->nHeight - pindex->
nHeight >
3191 "Ignore block request below NODE_NETWORK_LIMITED "
3192 "threshold, disconnect peer=%d\n",
3202 if (!pindex->nStatus.hasData()) {
3205 can_direct_fetch = CanDirectFetch();
3209 std::shared_ptr<const CBlock> pblock;
3210 auto handle_block_read_error = [&]() {
3212 return m_chainman.
m_blockman.IsBlockPruned(*pindex))) {
3214 "Block was pruned before it could be read, disconnect "
3218 LogError(
"Cannot load block from disk, disconnect peer=%d\n",
3224 if (a_recent_block && a_recent_block->GetHash() == pindex->
GetBlockHash()) {
3225 pblock = a_recent_block;
3230 std::vector<uint8_t> block_data;
3232 handle_block_read_error();
3239 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
3241 handle_block_read_error();
3244 pblock = pblockRead;
3250 bool sendMerkleBlock =
false;
3252 if (
auto tx_relay = peer.GetTxRelay()) {
3253 LOCK(tx_relay->m_bloom_filter_mutex);
3254 if (tx_relay->m_bloom_filter) {
3255 sendMerkleBlock =
true;
3260 if (sendMerkleBlock) {
3271 typedef std::pair<size_t, uint256> PairType;
3272 for (PairType &pair : merkleBlock.vMatchedTxn) {
3274 *pblock->vtx[pair.first]);
3284 if (can_direct_fetch &&
3286 if (a_recent_compact_block &&
3287 a_recent_compact_block->header.GetHash() ==
3290 *a_recent_compact_block);
3304 LOCK(peer.m_block_inv_mutex);
3307 if (hash == peer.m_continuation_block) {
3311 std::vector<CInv> vInv;
3314 peer.m_continuation_block =
BlockHash();
3320PeerManagerImpl::FindTxForGetData(
const Peer &peer,
const TxId &txid,
3321 const std::chrono::seconds mempool_req,
3322 const std::chrono::seconds now) {
3323 auto txinfo = m_mempool.
info(txid);
3328 if ((mempool_req.count() && txinfo.m_time <= mempool_req) ||
3330 return std::move(txinfo.tx);
3339 Assume(peer.GetTxRelay())->m_recently_announced_invs.contains(txid);
3340 if (recent && txinfo.tx) {
3341 return std::move(txinfo.tx);
3346 LOCK(m_most_recent_block_mutex);
3347 if (m_most_recent_block_txs !=
nullptr) {
3348 auto it = m_most_recent_block_txs->find(txid);
3349 if (it != m_most_recent_block_txs->end()) {
3362PeerManagerImpl::FindProofForGetData(
const Peer &peer,
3364 const std::chrono::seconds now) {
3367 bool send_unconditionally =
3393 if (send_unconditionally) {
3398 if (peer.m_proof_relay->m_recently_announced_proofs.contains(proofid)) {
3405void PeerManagerImpl::ProcessGetData(
3407 const std::atomic<bool> &interruptMsgProc) {
3410 auto tx_relay = peer.GetTxRelay();
3412 std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
3413 std::vector<CInv> vNotFound;
3415 const auto now{GetTime<std::chrono::seconds>()};
3417 const auto mempool_req = tx_relay !=
nullptr
3418 ? tx_relay->m_last_mempool_req.load()
3419 : std::chrono::seconds::min();
3424 while (it != peer.m_getdata_requests.end() &&
3425 (it->IsMsgProof() || it->IsMsgTx())) {
3426 if (interruptMsgProc) {
3435 const CInv &inv = *it++;
3439 vNotFound.push_back(inv);
3443 auto proof = FindProofForGetData(peer, proofid, now);
3450 vNotFound.push_back(inv);
3457 if (tx_relay ==
nullptr) {
3471 std::vector<TxId> parent_ids_to_add;
3474 auto tx_iter = m_mempool.
GetIter(tx->GetId());
3476 auto &pentry = *tx_iter;
3478 (*pentry)->GetMemPoolParentsConst();
3479 parent_ids_to_add.reserve(parents.size());
3480 for (
const auto &parent : parents) {
3481 if (parent.get()->GetTime() >
3483 parent_ids_to_add.push_back(
3484 parent.get()->GetTx().GetId());
3489 for (
const TxId &parent_txid : parent_ids_to_add) {
3492 if (
WITH_LOCK(tx_relay->m_tx_inventory_mutex,
3493 return !tx_relay->m_tx_inventory_known_filter
3494 .contains(parent_txid))) {
3495 tx_relay->m_recently_announced_invs.insert(parent_txid);
3499 vNotFound.push_back(inv);
3511 if (it != peer.m_getdata_requests.end() && !pfrom.
fPauseSend) {
3512 const CInv &inv = *it++;
3514 ProcessGetBlockData(config, pfrom, peer, inv);
3520 peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
3522 if (!vNotFound.empty()) {
3539void PeerManagerImpl::SendBlockTransactions(
3543 for (
size_t i = 0; i < req.
indices.size(); i++) {
3545 Misbehaving(peer,
"getblocktxn with out-of-bounds tx indices");
3554bool PeerManagerImpl::CheckHeadersPoW(
const std::vector<CBlockHeader> &headers,
3559 Misbehaving(peer,
"header with invalid proof of work");
3564 if (!CheckHeadersAreContinuous(headers)) {
3565 Misbehaving(peer,
"non-continuous headers sequence");
3578 near_chaintip_work =
3591void PeerManagerImpl::HandleUnconnectingHeaders(
3592 CNode &pfrom, Peer &peer,
const std::vector<CBlockHeader> &headers) {
3596 if (MaybeSendGetHeaders(pfrom,
GetLocator(best_header), peer)) {
3599 "received header %s: missing prev block %s, sending getheaders "
3600 "(%d) to end (peer=%d)\n",
3602 headers[0].hashPrevBlock.ToString(), best_header->nHeight,
3610 UpdateBlockAvailability(pfrom.
GetId(), headers.back().GetHash()));
3613bool PeerManagerImpl::CheckHeadersAreContinuous(
3614 const std::vector<CBlockHeader> &headers)
const {
3617 if (!hashLastBlock.
IsNull() && header.hashPrevBlock != hashLastBlock) {
3620 hashLastBlock = header.GetHash();
3625bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(
3626 Peer &peer,
CNode &pfrom, std::vector<CBlockHeader> &headers) {
3627 if (peer.m_headers_sync) {
3628 auto result = peer.m_headers_sync->ProcessNextHeaders(
3632 if (result.success) {
3633 peer.m_last_getheaders_timestamp = {};
3635 if (result.request_more) {
3636 auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
3639 Assume(!locator.vHave.empty());
3643 if (!locator.vHave.empty()) {
3646 bool sent_getheaders =
3647 MaybeSendGetHeaders(pfrom, locator, peer);
3650 locator.vHave.front().ToString(), pfrom.
GetId());
3655 peer.m_headers_sync.reset(
nullptr);
3660 LOCK(m_headers_presync_mutex);
3661 m_headers_presync_stats.erase(pfrom.
GetId());
3664 HeadersPresyncStats stats;
3665 stats.first = peer.m_headers_sync->GetPresyncWork();
3666 if (peer.m_headers_sync->GetState() ==
3668 stats.second = {peer.m_headers_sync->GetPresyncHeight(),
3669 peer.m_headers_sync->GetPresyncTime()};
3673 LOCK(m_headers_presync_mutex);
3674 m_headers_presync_stats[pfrom.
GetId()] = stats;
3676 m_headers_presync_stats.find(m_headers_presync_bestpeer);
3677 bool best_updated =
false;
3678 if (best_it == m_headers_presync_stats.end()) {
3683 const HeadersPresyncStats *stat_best{
nullptr};
3684 for (
const auto &[_peer, _stat] : m_headers_presync_stats) {
3685 if (!stat_best || _stat > *stat_best) {
3690 m_headers_presync_bestpeer = peer_best;
3691 best_updated = (peer_best == pfrom.
GetId());
3692 }
else if (best_it->first == pfrom.
GetId() ||
3693 stats > best_it->second) {
3696 m_headers_presync_bestpeer = pfrom.
GetId();
3697 best_updated =
true;
3699 if (best_updated && stats.second.has_value()) {
3702 m_headers_presync_should_signal =
true;
3706 if (result.success) {
3709 headers.swap(result.pow_validated_headers);
3712 return result.success;
3720bool PeerManagerImpl::TryLowWorkHeadersSync(
3722 std::vector<CBlockHeader> &headers) {
3729 arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
3733 if (total_work < minimum_chain_work) {
3747 LOCK(peer.m_headers_sync_mutex);
3748 peer.m_headers_sync.reset(
3750 chain_start_header, minimum_chain_work));
3755 (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3758 "Ignoring low-work chain (height=%u) from peer=%d\n",
3759 chain_start_header->
nHeight + headers.size(),
3771bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(
const CBlockIndex *header) {
3772 return header !=
nullptr &&
3773 ((m_chainman.m_best_header !=
nullptr &&
3775 m_chainman.m_best_header->GetAncestor(header->
nHeight)) ||
3779bool PeerManagerImpl::MaybeSendGetHeaders(
CNode &pfrom,
3786 if (current_time - peer.m_last_getheaders_timestamp >
3789 peer.m_last_getheaders_timestamp = current_time;
3801void PeerManagerImpl::HeadersDirectFetchBlocks(
const Config &config,
3805 CNodeState *nodestate = State(pfrom.
GetId());
3809 std::vector<const CBlockIndex *> vToFetch;
3815 if (!pindexWalk->nStatus.hasData() &&
3818 vToFetch.push_back(pindexWalk);
3820 pindexWalk = pindexWalk->
pprev;
3831 std::vector<CInv> vGetData;
3834 if (nodestate->vBlocksInFlight.size() >=
3840 BlockRequested(config, pfrom.
GetId(), *pindex);
3844 if (vGetData.size() > 1) {
3846 "Downloading blocks toward %s (%d) via headers "
3851 if (vGetData.size() > 0) {
3852 if (!m_opts.ignore_incoming_txs &&
3853 nodestate->m_provides_cmpctblocks && vGetData.size() == 1 &&
3854 mapBlocksInFlight.size() == 1 &&
3871void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(
3873 bool received_new_header,
bool may_have_more_headers) {
3876 CNodeState *nodestate = State(pfrom.
GetId());
3884 if (received_new_header &&
3886 nodestate->m_last_block_announcement =
GetTime();
3894 if (nodestate->pindexBestKnownBlock &&
3895 nodestate->pindexBestKnownBlock->nChainWork <
3906 LogPrintf(
"Disconnecting outbound peer %d -- headers "
3907 "chain has insufficient work\n",
3921 nodestate->pindexBestKnownBlock !=
nullptr) {
3922 if (m_outbound_peers_with_protect_from_disconnect <
3924 nodestate->pindexBestKnownBlock->nChainWork >=
3926 !nodestate->m_chain_sync.m_protect) {
3929 nodestate->m_chain_sync.m_protect =
true;
3930 ++m_outbound_peers_with_protect_from_disconnect;
3935void PeerManagerImpl::ProcessHeadersMessage(
const Config &config,
CNode &pfrom,
3937 std::vector<CBlockHeader> &&headers,
3938 bool via_compact_block) {
3939 size_t nCount = headers.size();
3947 LOCK(peer.m_headers_sync_mutex);
3948 if (peer.m_headers_sync) {
3949 peer.m_headers_sync.reset(
nullptr);
3950 LOCK(m_headers_presync_mutex);
3951 m_headers_presync_stats.erase(pfrom.
GetId());
3956 peer.m_last_getheaders_timestamp = {};
3964 if (!CheckHeadersPoW(headers, m_chainparams.
GetConsensus(), peer)) {
3979 bool already_validated_work =
false;
3982 bool have_headers_sync =
false;
3984 LOCK(peer.m_headers_sync_mutex);
3986 already_validated_work =
3987 IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3999 if (headers.empty()) {
4003 have_headers_sync = !!peer.m_headers_sync;
4009 headers[0].hashPrevBlock))};
4010 bool headers_connect_blockindex{chain_start_header !=
nullptr};
4012 if (!headers_connect_blockindex) {
4016 HandleUnconnectingHeaders(pfrom, peer, headers);
4024 peer.m_last_getheaders_timestamp = {};
4033 last_received_header =
4035 if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
4036 already_validated_work =
true;
4044 already_validated_work =
true;
4050 if (!already_validated_work &&
4051 TryLowWorkHeadersSync(peer, pfrom, chain_start_header, headers)) {
4063 bool received_new_header{last_received_header ==
nullptr};
4068 state, &pindexLast)) {
4070 MaybePunishNodeForBlock(pfrom.
GetId(), state, via_compact_block,
4071 "invalid header received");
4077 LogError(
"headers message processed but no pindexLast\n");
4086 if (MaybeSendGetHeaders(pfrom,
GetLocator(pindexLast), peer)) {
4089 "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
4090 pindexLast->
nHeight, pfrom.
GetId(), peer.m_starting_height);
4094 UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast,
4095 received_new_header,
4099 HeadersDirectFetchBlocks(config, pfrom, *pindexLast);
4102std::optional<node::PackageToValidate>
4105 bool first_time_failure) {
4111 PeerRef peer{GetPeerRef(nodeid)};
4113 const TxId &txid = ptx->GetId();
4121 return std::nullopt;
4124 const auto &[add_extra_compact_tx, unique_parents, package_to_validate] =
4125 m_txdownloadman.MempoolRejectedTx(ptx, state, nodeid,
4126 first_time_failure);
4129 AddToCompactExtraTransactions(ptx);
4133 for (
const TxId &parent_txid : unique_parents) {
4135 AddKnownTx(*peer, parent_txid);
4139 MaybePunishNodeForTx(nodeid, state);
4141 return package_to_validate;
4149 m_txdownloadman.MempoolAcceptedTx(tx);
4153 "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4154 nodeid, tx->GetId().ToString(), m_mempool.
size(),
4157 RelayTransaction(tx->GetId());
4160void PeerManagerImpl::ProcessPackageResult(
4167 const auto &
package = package_to_validate.m_txns;
4168 const auto &senders = package_to_validate.
m_senders;
4171 m_txdownloadman.MempoolRejectedPackage(package);
4175 if (!
Assume(package.size() == 2)) {
4181 auto package_iter = package.rbegin();
4182 auto senders_iter = senders.rbegin();
4183 while (package_iter != package.rend()) {
4184 const auto &tx = *package_iter;
4185 const NodeId nodeid = *senders_iter;
4186 const auto it_result{package_result.
m_tx_results.find(tx->GetId())};
4190 const auto &tx_result = it_result->second;
4191 switch (tx_result.m_result_type) {
4193 ProcessValidTx(nodeid, tx);
4203 ProcessInvalidTx(nodeid, tx, tx_result.m_state,
4220bool PeerManagerImpl::ProcessOrphanTx(
const Config &config, Peer &peer) {
4225 m_txdownloadman.GetTxToReconsider(peer.m_id)) {
4229 const TxId &orphanTxId = porphanTx->GetId();
4234 ProcessValidTx(peer.m_id, porphanTx);
4240 " invalid orphan tx %s from peer=%d. %s\n",
4247 ProcessInvalidTx(peer.m_id, porphanTx, state,
4258bool PeerManagerImpl::PrepareBlockFilterRequest(
4260 const BlockHash &stop_hash, uint32_t max_height_diff,
4262 const bool supported_filter_type =
4265 if (!supported_filter_type) {
4267 "peer %d requested unsupported block filter type: %d\n",
4268 node.GetId(),
static_cast<uint8_t
>(filter_type));
4269 node.fDisconnect =
true;
4279 if (!stop_index || !BlockRequestAllowed(stop_index)) {
4282 node.fDisconnect =
true;
4287 uint32_t stop_height = stop_index->
nHeight;
4288 if (start_height > stop_height) {
4291 "peer %d sent invalid getcfilters/getcfheaders with "
4293 "start height %d and stop height %d\n",
4294 node.GetId(), start_height, stop_height);
4295 node.fDisconnect =
true;
4298 if (stop_height - start_height >= max_height_diff) {
4300 "peer %d requested too many cfilters/cfheaders: %d / %d\n",
4301 node.GetId(), stop_height - start_height + 1, max_height_diff);
4302 node.fDisconnect =
true;
4307 if (!filter_index) {
4316void PeerManagerImpl::ProcessGetCFilters(
CNode &
node, Peer &peer,
4318 uint8_t filter_type_ser;
4319 uint32_t start_height;
4322 vRecv >> filter_type_ser >> start_height >> stop_hash;
4329 if (!PrepareBlockFilterRequest(
node, peer, filter_type, start_height,
4335 std::vector<BlockFilter> filters;
4338 "Failed to find block filter in index: filter_type=%s, "
4339 "start_height=%d, stop_hash=%s\n",
4345 for (
const auto &filter : filters) {
4350void PeerManagerImpl::ProcessGetCFHeaders(
CNode &
node, Peer &peer,
4352 uint8_t filter_type_ser;
4353 uint32_t start_height;
4356 vRecv >> filter_type_ser >> start_height >> stop_hash;
4363 if (!PrepareBlockFilterRequest(
node, peer, filter_type, start_height,
4370 if (start_height > 0) {
4372 stop_index->
GetAncestor(
static_cast<int>(start_height - 1));
4375 "Failed to find block filter header in index: "
4376 "filter_type=%s, block_hash=%s\n",
4383 std::vector<uint256> filter_hashes;
4387 "Failed to find block filter hashes in index: filter_type=%s, "
4388 "start_height=%d, stop_hash=%s\n",
4395 stop_index->
GetBlockHash(), prev_header, filter_hashes);
4398void PeerManagerImpl::ProcessGetCFCheckPt(
CNode &
node, Peer &peer,
4400 uint8_t filter_type_ser;
4403 vRecv >> filter_type_ser >> stop_hash;
4410 if (!PrepareBlockFilterRequest(
4411 node, peer, filter_type, 0, stop_hash,
4412 std::numeric_limits<uint32_t>::max(),
4413 stop_index, filter_index)) {
4421 for (
int i = headers.size() - 1; i >= 0; i--) {
4427 "Failed to find block filter header in index: "
4428 "filter_type=%s, block_hash=%s\n",
4451PeerManagerImpl::GetAvalancheVoteForBlock(
const BlockHash &hash)
const {
4462 if (pindex->nStatus.isInvalid()) {
4467 if (pindex->nStatus.isOnParkedChain()) {
4475 if (pindex == pindexFork) {
4480 if (pindexFork != pindexTip) {
4485 if (!pindex->nStatus.hasData()) {
4500 if (m_txdownloadman.RecentConfirmedTransactionsFilter().contains(
id)) {
4507 if (m_txdownloadman.RecentRejectsFilter().contains(
id)) {
4519 if (
auto iter = m_mempool.
GetIter(
id)) {
4520 mempool_tx = (**iter)->GetSharedTx();
4525 return conflicting.HaveTx(id);
4532 return orphanage.HaveTx(id);
4598 const std::shared_ptr<const CBlock> &block,
4599 bool force_processing,
4600 bool min_pow_checked) {
4601 bool new_block{
false};
4603 &new_block, m_avalanche);
4605 node.m_last_block_time = GetTime<std::chrono::seconds>();
4610 RemoveBlockRequest(block->GetHash(), std::nullopt);
4613 mapBlockSource.erase(block->GetHash());
4617void PeerManagerImpl::ProcessCompactBlockTxns(
4620 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4621 bool fBlockRead{
false};
4626 mapBlocksInFlight.equal_range(block_transactions.
blockhash);
4627 size_t already_in_flight =
4628 std::distance(range_flight.first, range_flight.second);
4629 bool requested_block_from_this_peer{
false};
4633 bool first_in_flight =
4634 already_in_flight == 0 ||
4635 (range_flight.first->second.first == pfrom.
GetId());
4637 while (range_flight.first != range_flight.second) {
4638 auto [node_id, block_it] = range_flight.first->second;
4639 if (node_id == pfrom.
GetId() && block_it->partialBlock) {
4640 requested_block_from_this_peer =
true;
4643 range_flight.first++;
4646 if (!requested_block_from_this_peer) {
4648 "Peer %d sent us block transactions for block we weren't "
4655 *range_flight.first->second.second->partialBlock;
4660 "previous compact block reconstruction attempt failed");
4662 "Peer %d sent compact block transactions multiple times\n",
4668 partialBlock.
FillBlock(*pblock, block_transactions.
txn);
4674 peer,
"invalid compact block/non-matching block transactions");
4677 if (first_in_flight) {
4683 std::vector<CInv> invs;
4689 "Peer %d sent us a compact block but it failed to "
4690 "reconstruct, waiting on first download to complete\n",
4706 mapBlockSource.emplace(block_transactions.
blockhash,
4707 std::make_pair(pfrom.
GetId(),
false));
4718 ProcessBlock(config, pfrom, pblock,
true,
4724void PeerManagerImpl::ProcessMessage(
4725 const Config &config,
CNode &pfrom,
const std::string &msg_type,
4726 DataStream &vRecv,
const std::chrono::microseconds time_received,
4727 const std::atomic<bool> &interruptMsgProc) {
4733 PeerRef peer = GetPeerRef(pfrom.
GetId());
4734 if (peer ==
nullptr) {
4740 "Avalanche is not initialized, ignoring %s message\n",
4755 uint64_t nNonce = 1;
4758 std::string cleanSubVer;
4759 int starting_height = -1;
4761 uint64_t nExtraEntropy = 1;
4763 vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
4776 "peer=%d does not offer the expected services "
4777 "(%08x offered, %08x expected); disconnecting\n",
4778 pfrom.
GetId(), nServices,
4788 "peer=%d does not offer the avalanche service; disconnecting\n",
4797 "peer=%d using obsolete version %i; disconnecting\n",
4798 pfrom.
GetId(), nVersion);
4803 if (!vRecv.
empty()) {
4812 if (!vRecv.
empty()) {
4813 std::string strSubVer;
4817 if (!vRecv.
empty()) {
4818 vRecv >> starting_height;
4820 if (!vRecv.
empty()) {
4823 if (!vRecv.
empty()) {
4824 vRecv >> nExtraEntropy;
4828 LogPrintf(
"connected to self at %s, disconnecting\n",
4841 PushNodeVersion(config, pfrom, *peer);
4845 const int greatest_common_version =
4857 peer->m_their_services = nServices;
4861 pfrom.cleanSubVer = cleanSubVer;
4863 peer->m_starting_height = starting_height;
4871 (fRelay || (peer->m_our_services &
NODE_BLOOM))) {
4872 auto *
const tx_relay = peer->SetTxRelay();
4874 LOCK(tx_relay->m_bloom_filter_mutex);
4876 tx_relay->m_relay_txs = fRelay;
4889 CNodeState *state = State(pfrom.
GetId());
4890 state->fPreferredDownload =
4894 m_num_preferred_download_peers += state->fPreferredDownload;
4900 bool send_getaddr{
false};
4902 send_getaddr = SetupAddressRelay(pfrom, *peer);
4913 peer->m_getaddr_sent =
true;
4917 WITH_LOCK(peer->m_addr_token_bucket_mutex,
4918 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
4939 std::string remoteAddr;
4945 "receive version message: [%s] %s: version %d, blocks=%d, "
4946 "us=%s, txrelay=%d, peer=%d%s\n",
4949 pfrom.
GetId(), remoteAddr);
4951 int64_t currentTime =
GetTime();
4952 int64_t nTimeOffset = nTime - currentTime;
4957 Misbehaving(*peer,
"Ignoring invalid timestamp in version message");
4967 "feeler connection completed peer=%d; disconnecting\n",
4976 Misbehaving(*peer,
"non-version message before version handshake");
4983 "ignoring redundant verack message from peer=%d\n",
4989 LogPrintf(
"New outbound peer connected: version: %d, blocks=%d, "
4991 pfrom.
nVersion.load(), peer->m_starting_height,
5012 AddKnownProof(*peer, localProof->getId());
5016 peer->m_proof_relay->m_recently_announced_proofs.insert(
5017 localProof->getId());
5022 if (
auto tx_relay = peer->GetTxRelay()) {
5031 return tx_relay->m_tx_inventory_to_send.empty() &&
5032 tx_relay->m_next_inv_send_time == 0s));
5037 const CNodeState *state = State(pfrom.
GetId());
5038 m_txdownloadman.ConnectedPeer(
5040 .m_preferred = state->fPreferredDownload,
5041 .m_relay_permissions = pfrom.HasPermission(
5042 NetPermissionFlags::Relay),
5052 Misbehaving(*peer,
"non-verack message before version handshake");
5057 const auto ser_params{
5066 std::vector<CAddress> vAddr;
5070 if (!SetupAddressRelay(pfrom, *peer)) {
5076 if (vAddr.size() > m_opts.max_addr_to_send) {
5077 Misbehaving(*peer,
strprintf(
"%s message size = %u", msg_type,
5083 std::vector<CAddress> vAddrOk;
5084 const auto current_a_time{Now<NodeSeconds>()};
5087 const auto current_time = GetTime<std::chrono::microseconds>();
5089 LOCK(peer->m_addr_token_bucket_mutex);
5092 const auto time_diff =
5093 std::max(current_time - peer->m_addr_token_timestamp, 0us);
5094 const double increment =
5096 peer->m_addr_token_bucket =
5097 std::min<double>(peer->m_addr_token_bucket + increment,
5101 peer->m_addr_token_timestamp = current_time;
5103 const bool rate_limited =
5105 uint64_t num_proc = 0;
5106 uint64_t num_rate_limit = 0;
5107 Shuffle(vAddr.begin(), vAddr.end(), m_rng);
5109 if (interruptMsgProc) {
5114 LOCK(peer->m_addr_token_bucket_mutex);
5116 if (peer->m_addr_token_bucket < 1.0) {
5122 peer->m_addr_token_bucket -= 1.0;
5135 addr.
nTime > current_a_time + 10min) {
5136 addr.
nTime = current_a_time - 5 * 24h;
5138 AddAddressKnown(*peer, addr);
5147 if (addr.
nTime > current_a_time - 10min && !peer->m_getaddr_sent &&
5150 RelayAddress(pfrom.
GetId(), addr, fReachable);
5154 vAddrOk.push_back(addr);
5157 peer->m_addr_processed += num_proc;
5158 peer->m_addr_rate_limited += num_rate_limit;
5160 "Received addr: %u addresses (%u processed, %u rate-limited) "
5162 vAddr.size(), num_proc, num_rate_limit, pfrom.
GetId());
5164 m_addrman.
Add(vAddrOk, pfrom.
addr, 2h);
5165 if (vAddr.size() < 1000) {
5166 peer->m_getaddr_sent =
false;
5173 "addrfetch connection completed peer=%d; disconnecting\n",
5181 peer->m_wants_addrv2 =
true;
5186 peer->m_prefers_headers =
true;
5191 bool sendcmpct_hb{
false};
5192 uint64_t sendcmpct_version{0};
5193 vRecv >> sendcmpct_hb >> sendcmpct_version;
5200 CNodeState *nodestate = State(pfrom.
GetId());
5201 nodestate->m_provides_cmpctblocks =
true;
5202 nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
5211 std::vector<CInv> vInv;
5214 Misbehaving(*peer,
strprintf(
"inv message size = %u", vInv.size()));
5218 const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
5220 const auto current_time{GetTime<std::chrono::microseconds>()};
5221 std::optional<BlockHash> best_block;
5223 auto logInv = [&](
const CInv &inv,
bool fAlreadyHave) {
5225 fAlreadyHave ?
"have" :
"new", pfrom.GetId());
5228 for (
CInv &inv : vInv) {
5229 if (interruptMsgProc) {
5241 const bool fAlreadyHave = AlreadyHaveBlock(
BlockHash(inv.
hash));
5242 logInv(inv, fAlreadyHave);
5245 UpdateBlockAvailability(pfrom.
GetId(), hash);
5247 !IsBlockRequested(hash)) {
5254 best_block = std::move(hash);
5265 const bool fAlreadyHave = AlreadyHaveProof(proofid);
5266 logInv(inv, fAlreadyHave);
5267 AddKnownProof(*peer, proofid);
5269 if (!fAlreadyHave && m_avalanche &&
5271 const bool preferred = isPreferredDownloadPeer(pfrom);
5273 LOCK(cs_proofrequest);
5274 AddProofAnnouncement(pfrom, proofid, current_time,
5283 AddKnownTx(*peer, txid);
5284 if (reject_tx_invs) {
5286 "transaction (%s) inv sent in violation of "
5287 "protocol, disconnecting peer=%d\n",
5294 const bool fAlreadyHave{m_txdownloadman.AddTxAnnouncement(
5295 pfrom.
GetId(), txid, current_time,
5297 logInv(inv, fAlreadyHave);
5304 "Unknown inv type \"%s\" received from peer=%d\n",
5321 if (state.fSyncStarted ||
5322 (!peer->m_inv_triggered_getheaders_before_sync &&
5323 *best_block != m_last_block_inv_triggering_headers_sync)) {
5324 if (MaybeSendGetHeaders(
5325 pfrom,
GetLocator(m_chainman.m_best_header), *peer)) {
5327 m_chainman.m_best_header->nHeight,
5328 best_block->ToString(), pfrom.
GetId());
5330 if (!state.fSyncStarted) {
5331 peer->m_inv_triggered_getheaders_before_sync =
true;
5335 m_last_block_inv_triggering_headers_sync = *best_block;
5344 std::vector<CInv> vInv;
5348 strprintf(
"getdata message size = %u", vInv.size()));
5353 vInv.size(), pfrom.
GetId());
5355 if (vInv.size() > 0) {
5361 LOCK(peer->m_getdata_requests_mutex);
5362 peer->m_getdata_requests.insert(peer->m_getdata_requests.end(),
5363 vInv.begin(), vInv.end());
5364 ProcessGetData(config, pfrom, *peer, interruptMsgProc);
5373 vRecv >> locator >> hashStop;
5377 "getblocks locator size %lld > %d, disconnect peer=%d\n",
5391 std::shared_ptr<const CBlock> a_recent_block;
5393 LOCK(m_most_recent_block_mutex);
5394 a_recent_block = m_most_recent_block;
5398 state, a_recent_block, m_avalanche)) {
5416 (pindex ? pindex->
nHeight : -1),
5417 hashStop.IsNull() ?
"end" : hashStop.
ToString(), nLimit,
5419 for (; pindex; pindex = m_chainman.
ActiveChain().Next(pindex)) {
5428 const int nPrunedBlocksLikelyToHave =
5432 (!pindex->nStatus.hasData() ||
5434 nPrunedBlocksLikelyToHave)) {
5437 " getblocks stopping, pruned or too old block at %d %s\n",
5442 peer->m_block_inv_mutex,
5443 peer->m_blocks_for_inv_relay.push_back(pindex->
GetBlockHash()));
5444 if (--nLimit <= 0) {
5450 peer->m_continuation_block = pindex->GetBlockHash();
5462 std::shared_ptr<const CBlock> recent_block;
5464 LOCK(m_most_recent_block_mutex);
5465 if (m_most_recent_block_hash == req.
blockhash) {
5466 recent_block = m_most_recent_block;
5471 SendBlockTransactions(pfrom, *peer, *recent_block, req);
5481 if (!pindex || !pindex->nStatus.hasData()) {
5484 "Peer %d sent us a getblocktxn for a block we don't have\n",
5495 if (!block_pos.IsNull()) {
5502 LogError(
"getblocktxn: block read failed for block %s\n",
5508 SendBlockTransactions(pfrom, *peer, block, req);
5520 "Peer %d sent us a getblocktxn for a block > %i deep\n",
5525 WITH_LOCK(peer->m_getdata_requests_mutex,
5526 peer->m_getdata_requests.push_back(inv));
5535 vRecv >> locator >> hashStop;
5539 "getheaders locator size %lld > %d, disconnect peer=%d\n",
5548 "Ignoring getheaders from peer=%d while importing/reindexing\n",
5562 if (m_chainman.
ActiveTip() ==
nullptr ||
5567 "Ignoring getheaders from peer=%d because active chain "
5568 "has too little work; sending empty response\n",
5573 std::vector<CBlock>());
5577 CNodeState *nodestate = State(pfrom.
GetId());
5586 if (!BlockRequestAllowed(pindex)) {
5588 "%s: ignoring request from peer=%i for old block "
5589 "header that isn't in the main chain\n",
5590 __func__, pfrom.
GetId());
5604 std::vector<CBlock> vHeaders;
5607 (pindex ? pindex->
nHeight : -1),
5608 hashStop.IsNull() ?
"end" : hashStop.
ToString(),
5610 for (; pindex; pindex = m_chainman.
ActiveChain().Next(pindex)) {
5612 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) {
5629 nodestate->pindexBestHeaderSent =
5636 if (RejectIncomingTxs(pfrom)) {
5638 "transaction sent in violation of protocol peer=%d\n",
5656 AddKnownTx(*peer, txid);
5661 const auto &[should_validate, reconsiderable_package] =
5662 m_txdownloadman.ReceivedTx(pfrom.
GetId(), ptx);
5663 if (!should_validate) {
5671 "Not relaying non-mempool transaction %s from "
5672 "forcerelay peer=%d\n",
5675 LogPrintf(
"Force relaying tx %s from peer=%d\n",
5677 RelayTransaction(tx.
GetId());
5681 if (reconsiderable_package) {
5684 reconsiderable_package->m_txns,
5687 "package evaluation for %s: %s (%s)\n",
5688 reconsiderable_package->ToString(),
5690 ?
"package accepted"
5691 :
"package rejected",
5692 package_result.m_state.
ToString());
5693 ProcessPackageResult(reconsiderable_package.value(),
5701 Assume(!reconsiderable_package.has_value());
5709 ProcessValidTx(pfrom.
GetId(), ptx);
5713 if (
auto package_to_validate{
5714 ProcessInvalidTx(pfrom.
GetId(), ptx, state,
5718 package_to_validate->
m_txns,
false)};
5720 "package evaluation for %s: %s (%s)\n",
5723 ?
"package accepted"
5724 :
"package rejected",
5725 package_result.m_state.
ToString());
5726 ProcessPackageResult(package_to_validate.value(),
5735 m_txdownloadman.GetTxRequestRef().ForgetInvId(tx.
GetId());
5737 unsigned int nEvicted{0};
5744 m_opts.max_conflicting_txs, m_rng);
5749 "conflicting pool overflow, removed %u tx\n",
5762 "Unexpected cmpctblock message received from peer %d\n",
5769 vRecv >> cmpctblock;
5770 }
catch (std::ios_base::failure &e) {
5772 Misbehaving(*peer,
"cmpctblock-bad-indexes");
5776 bool received_new_header =
false;
5789 MaybeSendGetHeaders(
5790 pfrom,
GetLocator(m_chainman.m_best_header), *peer);
5796 GetAntiDoSWorkThreshold()) {
5800 "Ignoring low-work compact block from peer %d\n",
5806 received_new_header =
true;
5816 MaybePunishNodeForBlock(pfrom.
GetId(), state,
5818 "invalid header via cmpctblock");
5823 if (received_new_header) {
5824 LogInfo(
"Saw new cmpctblock header hash=%s peer=%d\n",
5825 blockhash.ToString(), pfrom.
GetId());
5828 bool fProcessBLOCKTXN =
false;
5833 bool fRevertToHeaderProcessing =
false;
5837 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
5838 bool fBlockReconstructed =
false;
5846 "cmpctblock: header accepted but no pindex for block %s\n",
5847 blockhash.ToString());
5854 CNodeState *nodestate = State(pfrom.
GetId());
5858 if (received_new_header &&
5861 nodestate->m_last_block_announcement =
GetTime();
5864 if (pindex->nStatus.hasData()) {
5871 size_t already_in_flight =
5872 std::distance(range_flight.first, range_flight.second);
5873 bool requested_block_from_this_peer{
false};
5877 bool first_in_flight =
5878 already_in_flight == 0 ||
5879 (range_flight.first->second.first == pfrom.
GetId());
5881 while (range_flight.first != range_flight.second) {
5882 if (range_flight.first->second.first == pfrom.
GetId()) {
5883 requested_block_from_this_peer =
true;
5886 range_flight.first++;
5895 if (requested_block_from_this_peer) {
5899 std::vector<CInv> vInv(1);
5908 if (!already_in_flight && !CanDirectFetch()) {
5916 nodestate->vBlocksInFlight.size() <
5918 requested_block_from_this_peer) {
5919 std::list<QueuedBlock>::iterator *queuedBlockIt =
nullptr;
5920 if (!BlockRequested(config, pfrom.
GetId(), *pindex,
5922 if (!(*queuedBlockIt)->partialBlock) {
5924 ->partialBlock.reset(
5931 "we were already syncing!\n");
5937 *(*queuedBlockIt)->partialBlock;
5939 partialBlock.
InitData(cmpctblock, vExtraTxnForCompact);
5945 Misbehaving(*peer,
"invalid compact block");
5948 if (first_in_flight) {
5951 std::vector<CInv> vInv(1);
5964 for (
size_t i = 0; i < cmpctblock.
BlockTxCount(); i++) {
5970 fProcessBLOCKTXN =
true;
5971 }
else if (first_in_flight) {
5978 IsBlockRequestedFromOutbound(blockhash) ||
6001 tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
6006 std::vector<CTransactionRef> dummy;
6007 status = tempBlock.FillBlock(*pblock, dummy);
6009 fBlockReconstructed =
true;
6013 if (requested_block_from_this_peer) {
6017 std::vector<CInv> vInv(1);
6024 fRevertToHeaderProcessing =
true;
6029 if (fProcessBLOCKTXN) {
6032 return ProcessCompactBlockTxns(config, pfrom, *peer, txn);
6035 if (fRevertToHeaderProcessing) {
6041 return ProcessHeadersMessage(config, pfrom, *peer,
6046 if (fBlockReconstructed) {
6051 mapBlockSource.emplace(pblock->GetHash(),
6052 std::make_pair(pfrom.
GetId(),
false));
6063 ProcessBlock(config, pfrom, pblock,
true,
6072 RemoveBlockRequest(pblock->GetHash(), std::nullopt);
6082 "Unexpected blocktxn message received from peer %d\n",
6090 return ProcessCompactBlockTxns(config, pfrom, *peer, resp);
6097 "Unexpected headers message received from peer %d\n",
6102 std::vector<CBlockHeader> headers;
6109 strprintf(
"too-many-headers: headers message size = %u",
6113 headers.resize(nCount);
6114 for (
unsigned int n = 0; n < nCount; n++) {
6115 vRecv >> headers[n];
6120 ProcessHeadersMessage(config, pfrom, *peer, std::move(headers),
6126 if (m_headers_presync_should_signal.exchange(
false)) {
6127 HeadersPresyncStats stats;
6129 LOCK(m_headers_presync_mutex);
6131 m_headers_presync_stats.find(m_headers_presync_bestpeer);
6132 if (it != m_headers_presync_stats.end()) {
6138 stats.first, stats.second->first, stats.second->second);
6149 "Unexpected block message received from peer %d\n",
6154 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6158 pblock->GetHash().ToString(), pfrom.
GetId());
6163 pblock->hashPrevBlock))};
6167 "Received mutated block from peer=%d\n", peer->m_id);
6168 Misbehaving(*peer,
"mutated block");
6170 RemoveBlockRequest(pblock->GetHash(), peer->m_id));
6180 const BlockHash hash = pblock->GetHash();
6181 bool min_pow_checked =
false;
6186 forceProcessing = IsBlockRequested(hash);
6187 RemoveBlockRequest(hash, pfrom.
GetId());
6191 mapBlockSource.emplace(hash, std::make_pair(pfrom.
GetId(),
true));
6196 {pblock->GetBlockHeader()}) >=
6197 GetAntiDoSWorkThreshold()) {
6198 min_pow_checked =
true;
6201 ProcessBlock(config, pfrom, pblock, forceProcessing, min_pow_checked);
6211 if (pfrom.m_avalanche_pubkey.has_value()) {
6214 "Ignoring avahello from peer %d: already in our node set\n",
6220 vRecv >> delegation;
6227 if (!delegation.
verify(state, pubkey)) {
6228 Misbehaving(*peer,
"invalid-delegation");
6231 pfrom.m_avalanche_pubkey = std::move(pubkey);
6234 sighasher << delegation.
getId();
6242 if (!(*pfrom.m_avalanche_pubkey)
6243 .VerifySchnorr(sighasher.GetHash(),
sig)) {
6244 Misbehaving(*peer,
"invalid-avahello-signature");
6251 if (!AlreadyHaveProof(proofid)) {
6252 const bool preferred = isPreferredDownloadPeer(pfrom);
6253 LOCK(cs_proofrequest);
6254 AddProofAnnouncement(pfrom, proofid,
6255 GetTime<std::chrono::microseconds>(),
6263 vRecv >> max_elements;
6267 Misbehaving(*peer,
"avahello-max-elements-too-low");
6272 max_elements = std::min(
6278 return pm.
addNode(pfrom.
GetId(), proofid, max_elements);
6289 WITH_LOCK(peer->m_addr_token_bucket_mutex,
6290 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
6294 peer->m_proof_relay->compactproofs_requested =
true;
6305 const auto now = Now<SteadyMilliseconds>();
6311 last_poll + std::chrono::milliseconds(m_opts.avalanche_cooldown)) {
6313 "Ignoring repeated avapoll from peer %d: cooldown not "
6328 strprintf(
"too-many-ava-poll: poll message size = %u", nCount));
6332 std::vector<avalanche::Vote> votes;
6333 votes.reserve(nCount);
6335 bool fPreconsensus{
false};
6336 bool fStakingPreconsensus{
false};
6341 fStakingPreconsensus =
6345 for (
unsigned int n = 0; n < nCount; n++) {
6353 if (!quorum_established) {
6354 votes.emplace_back(vote, inv.
hash);
6361 if (fPreconsensus) {
6363 return GetAvalancheVoteForTx(
6376 if (fStakingPreconsensus) {
6383 "poll inv type %d unknown from peer=%d\n",
6388 votes.emplace_back(vote, inv.
hash);
6414 if (!pfrom.m_avalanche_pubkey.has_value() ||
6415 !(*pfrom.m_avalanche_pubkey)
6416 .VerifySchnorr(verifier.GetHash(),
sig)) {
6417 Misbehaving(*peer,
"invalid-ava-response-signature");
6422 auto now = GetTime<std::chrono::seconds>();
6424 std::vector<avalanche::VoteItemUpdate> updates;
6425 bool disconnect{
false};
6428 disconnect, error)) {
6430 Misbehaving(*peer, error);
6448 "Repeated failure to register votes from peer %d: %s\n",
6449 pfrom.
GetId(), error);
6452 Misbehaving(*peer, error);
6465 auto logVoteUpdate = [](
const auto &voteUpdate,
6466 const std::string &voteItemTypeStr,
6467 const auto &voteItemId) {
6468 std::string voteOutcome;
6469 bool alwaysPrint =
false;
6470 switch (voteUpdate.getStatus()) {
6472 voteOutcome =
"invalidated";
6476 voteOutcome =
"rejected";
6479 voteOutcome =
"accepted";
6482 voteOutcome =
"finalized";
6485 alwaysPrint = voteItemTypeStr !=
"tx";
6488 voteOutcome =
"stalled";
6497 alwaysPrint &= (voteItemTypeStr !=
"contender");
6500 LogPrintf(
"Avalanche %s %s %s\n", voteOutcome, voteItemTypeStr,
6501 voteItemId.ToString());
6505 voteItemTypeStr, voteItemId.ToString());
6509 bool shouldActivateBestChain =
false;
6511 bool fPreconsensus{
false};
6512 bool fStakingPreconsensus{
false};
6517 fStakingPreconsensus =
6521 for (
const auto &u : updates) {
6526 if (
auto pitem = std::get_if<const avalanche::ProofRef>(&item)) {
6530 logVoteUpdate(u,
"proof", proofid);
6532 auto rejectionMode =
6534 auto nextCooldownTimePoint = GetTime<std::chrono::seconds>();
6535 switch (u.getStatus()) {
6551 return pm.rejectProof(proofid,
6555 "ERROR: Failed to reject proof: %s\n",
6561 nextCooldownTimePoint += std::chrono::seconds(
6562 m_opts.avalanche_peer_replacement_cooldown);
6568 avalanche::PeerManager::
6569 RegistrationMode::FORCE_ACCEPT);
6572 [&](const avalanche::Peer &peer) {
6573 pm.updateNextPossibleConflictTime(
6575 nextCooldownTimePoint);
6576 if (u.getStatus() ==
6577 avalanche::VoteStatus::
6579 pm.setFinalized(peer.peerid);
6587 "ERROR: Failed to accept proof: %s\n",
6594 auto getBlockFromIndex = [
this](
const CBlockIndex *pindex)
6595 -> std::shared_ptr<const CBlock> {
6598 std::shared_ptr<const CBlock> pblock =
WITH_LOCK(
6599 m_most_recent_block_mutex,
return m_most_recent_block);
6601 if (!pblock || pblock->GetHash() != pindex->
GetBlockHash()) {
6602 std::shared_ptr<CBlock> pblockRead =
6603 std::make_shared<CBlock>();
6606 LogError(
"getBlockFromIndex: cannot load block from "
6611 pblock = pblockRead;
6616 if (
auto pitem = std::get_if<const CBlockIndex *>(&item)) {
6619 shouldActivateBestChain =
true;
6623 switch (u.getStatus()) {
6628 LogPrintf(
"ERROR: Database error: %s\n",
6637 LogPrintf(
"ERROR: Database error: %s\n",
6642 auto pblock = getBlockFromIndex(pindex);
6644 LogError(
"avaresponse: failed to get invalidated "
6645 "block from index\n");
6664 std::unique_ptr<node::CBlockTemplate> blockTemplate;
6668 chainstate.UnparkBlock(pindex);
6670 const bool newlyFinalized =
6671 !chainstate.IsBlockAvalancheFinalized(pindex) &&
6672 chainstate.AvalancheFinalizeBlock(pindex,
6677 if (fPreconsensus && newlyFinalized) {
6687 std::unordered_set<TxId, SaltedTxIdHasher>
6688 confirmedTxIdsInNonFinalizedBlocks;
6689 bool missing_block =
false;
6691 block !=
nullptr && block != pindex;
6692 block = block->pprev) {
6694 getBlockFromIndex(block);
6695 if (!currentBlock) {
6697 "avaresponse: failed to get "
6698 "finalized block descendant from "
6701 missing_block =
true;
6704 for (
const auto &tx : currentBlock->vtx) {
6705 confirmedTxIdsInNonFinalizedBlocks
6706 .insert(tx->
GetId());
6710 if (missing_block) {
6722 confirmedTxIdsInNonFinalizedBlocks);
6734 config, chainstate, &m_mempool,
6736 blockAssembler.pblocktemplate.reset(
6739 if (blockAssembler.pblocktemplate) {
6740 blockAssembler.addTxs(m_mempool);
6741 blockTemplate = std::move(
6742 blockAssembler.pblocktemplate);
6747 if (blockTemplate) {
6752 for (
const auto &templateEntry :
6766 if (fStakingPreconsensus) {
6768 std::get_if<const avalanche::StakeContenderId>(&item)) {
6770 logVoteUpdate(u,
"contender", contenderId);
6772 switch (u.getStatus()) {
6793 if (!fPreconsensus) {
6797 if (
auto pitem = std::get_if<const CTransactionRef>(&item)) {
6801 const TxId &txid = tx->GetId();
6802 const auto status{u.getStatus()};
6807 logVoteUpdate(u,
"tx", txid);
6820 std::shared_ptr<const std::vector<Coin>> spentCoins;
6832 _spentCoins.has_value()
6833 ? std::make_shared<const std::vector<Coin>>(
6834 std::move(*_spentCoins))
6838 if (m_mempool.
exists(txid)) {
6842 std::vector<CTransactionRef> conflictingTxs =
6848 if (conflictingTxs.size() > 0) {
6856 "Attempting to pull a now invalid "
6857 "conflicting tx %s to mempool\n",
6858 conflictingTxs[0]->GetId().
ToString());
6865 for (
const auto &conflictingTx :
6868 conflictingTx->GetId());
6887 m_txdownloadman.RecentRejectsFilter().insert(txid);
6889 AddToCompactExtraTransactions(tx);
6907 return conflicting.HaveTx(txid);
6910 std::vector<CTransactionRef>
6911 mempool_conflicting_txs;
6912 for (
const auto &txin : tx->vin) {
6917 mempool_conflicting_txs.push_back(
6918 std::move(conflict));
6925 LogError(
"accepted tx %s failed mempool "
6933 [&txid, &mempool_conflicting_txs](
6938 if (mempool_conflicting_txs.size() >
6941 mempool_conflicting_txs[0],
6951 auto it = m_mempool.
GetIter(txid);
6952 if (!it.has_value()) {
6955 "Error: finalized tx (%s) is not in the "
6961 std::vector<TxId> finalizedTxIds;
6962 m_mempool.setAvalancheFinalized(
6967 for (
const auto &finalized_txid : finalizedTxIds) {
6972 logVoteUpdate(u,
"tx", finalized_txid);
6981 std::vector<CTransactionRef>
6984 for (
const auto &conflictingTx :
6987 .RecentRejectsFilter()
6988 .insert(conflictingTx->GetId());
6990 conflictingTx->GetId());
6998 LOCK(m_tx_download_mutex);
7016 m_txdownloadman.GetTxRequestRef().ForgetInvId(txid);
7022 for (
auto &it : m_peer_map) {
7023 auto tx_relay = (*it.second).GetTxRelay();
7028 LOCK(tx_relay->m_tx_inventory_mutex);
7035 auto &stalled_by_time =
7036 tx_relay->m_avalanche_stalled_txids
7038 if (stalled_by_time.size() >=
7040 stalled_by_time.erase(
7041 stalled_by_time.begin()->timeAdded);
7044 tx_relay->m_avalanche_stalled_txids.insert(
7049 AddToCompactExtraTransactions(tx);
7057 if (shouldActivateBestChain) {
7060 state,
nullptr, m_avalanche)) {
7075 ReceivedAvalancheProof(pfrom, *peer, proof);
7084 if (peer->m_proof_relay ==
nullptr) {
7088 auto now = GetTime<std::chrono::seconds>();
7089 if (now < peer->m_next_getavaproofs) {
7098 peer->m_proof_relay->lastSharedProofsUpdate = now;
7100 peer->m_proof_relay->sharedProofs =
7106 peer->m_proof_relay->sharedProofs);
7116 if (peer->m_proof_relay ==
nullptr) {
7121 if (!peer->m_proof_relay->compactproofs_requested) {
7125 peer->m_proof_relay->compactproofs_requested =
false;
7129 vRecv >> compactProofs;
7130 }
catch (std::ios_base::failure &e) {
7132 Misbehaving(*peer,
"avaproofs-bad-indexes");
7137 for (
const auto &prefilledProof : compactProofs.getPrefilledProofs()) {
7138 if (!ReceivedAvalancheProof(pfrom, *peer, prefilledProof.proof)) {
7168 auto shortIdProcessor =
7172 if (shortIdProcessor.hasOutOfBoundIndex()) {
7175 Misbehaving(*peer,
"avaproofs-bad-indexes");
7178 if (!shortIdProcessor.isEvenlyDistributed()) {
7183 std::vector<std::pair<avalanche::ProofId, bool>> remoteProofsStatus;
7187 uint64_t shortid = compactProofs.
getShortID(proofid);
7189 int added = shortIdProcessor.matchKnownItem(shortid, proof);
7201 remoteProofsStatus.emplace_back(proofid, added > 0);
7206 matchKnownProof(peer.
proof);
7215 matchKnownProof(proof);
7220 for (
size_t i = 0; i < compactProofs.
size(); i++) {
7221 if (shortIdProcessor.getItem(i) ==
nullptr) {
7237 return pfrom.m_avalanche_pubkey.has_value())) {
7242 for (
const auto &[proofid, present] : remoteProofsStatus) {
7252 if (peer->m_proof_relay ==
nullptr) {
7259 auto requestedIndiceIt = proofreq.
indices.begin();
7260 uint32_t treeIndice = 0;
7261 peer->m_proof_relay->sharedProofs.forEachLeaf([&](
const auto &proof) {
7262 if (requestedIndiceIt == proofreq.
indices.end()) {
7267 if (treeIndice++ == *requestedIndiceIt) {
7269 requestedIndiceIt++;
7275 peer->m_proof_relay->sharedProofs = {};
7288 "Ignoring \"getaddr\" from %s connection. peer=%d\n",
7295 Assume(SetupAddressRelay(pfrom, *peer));
7299 if (peer->m_getaddr_recvd) {
7304 peer->m_getaddr_recvd =
true;
7306 peer->m_addrs_to_send.clear();
7307 std::vector<CAddress> vAddr;
7308 const size_t maxAddrToSend = m_opts.max_addr_to_send;
7316 for (
const CAddress &addr : vAddr) {
7317 PushAddress(*peer, addr);
7323 auto now = GetTime<std::chrono::seconds>();
7324 if (now < peer->m_next_getavaaddr) {
7333 if (!SetupAddressRelay(pfrom, *peer)) {
7335 "Ignoring getavaaddr message from %s peer=%d\n",
7340 using AvaNodeInfo = std::tuple<CAddress, NodeId, double>;
7341 auto availabilityScoreComparator = [](
const AvaNodeInfo &lhs,
7342 const AvaNodeInfo &rhs) {
7343 double scoreLhs = std::get<double>(lhs);
7344 double scoreRhs = std::get<double>(rhs);
7346 if (scoreLhs != scoreRhs) {
7347 return scoreLhs > scoreRhs;
7350 return std::get<NodeId>(lhs) < std::get<NodeId>(rhs);
7356 std::set<AvaNodeInfo,
decltype(availabilityScoreComparator)> avaNodes(
7357 availabilityScoreComparator);
7364 avaNodes.insert(AvaNodeInfo{pnode->
addr, pnode->
GetId(), score});
7365 if (avaNodes.size() > m_opts.max_addr_to_send) {
7366 avaNodes.erase(std::prev(avaNodes.end()));
7370 peer->m_addrs_to_send.clear();
7371 for (
const auto &nodeInfo : avaNodes) {
7372 PushAddress(*peer, std::get<CAddress>(nodeInfo));
7383 "mempool request with bloom filters disabled, "
7384 "disconnect peer=%d\n",
7395 "mempool request with bandwidth limit reached, "
7396 "disconnect peer=%d\n",
7403 if (
auto tx_relay = peer->GetTxRelay()) {
7404 LOCK(tx_relay->m_tx_inventory_mutex);
7405 tx_relay->m_send_mempool =
true;
7431 const auto ping_end = time_received;
7434 bool bPingFinished =
false;
7435 std::string sProblem;
7437 if (nAvail >=
sizeof(nonce)) {
7442 if (peer->m_ping_nonce_sent != 0) {
7443 if (nonce == peer->m_ping_nonce_sent) {
7446 bPingFinished =
true;
7447 const auto ping_time = ping_end - peer->m_ping_start.load();
7448 if (ping_time.count() >= 0) {
7453 sProblem =
"Timing mishap";
7457 sProblem =
"Nonce mismatch";
7461 bPingFinished =
true;
7462 sProblem =
"Nonce zero";
7466 sProblem =
"Unsolicited pong without ping";
7471 bPingFinished =
true;
7472 sProblem =
"Short payload";
7475 if (!(sProblem.empty())) {
7477 "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
7478 pfrom.
GetId(), sProblem, peer->m_ping_nonce_sent, nonce,
7481 if (bPingFinished) {
7482 peer->m_ping_nonce_sent = 0;
7490 "filterload received despite not offering bloom services "
7491 "from peer=%d; disconnecting\n",
7501 Misbehaving(*peer,
"too-large bloom filter");
7502 }
else if (
auto tx_relay = peer->GetTxRelay()) {
7504 LOCK(tx_relay->m_bloom_filter_mutex);
7505 tx_relay->m_bloom_filter.reset(
new CBloomFilter(filter));
7506 tx_relay->m_relay_txs =
true;
7516 "filteradd received despite not offering bloom services "
7517 "from peer=%d; disconnecting\n",
7522 std::vector<uint8_t> vData;
7531 }
else if (
auto tx_relay = peer->GetTxRelay()) {
7532 LOCK(tx_relay->m_bloom_filter_mutex);
7533 if (tx_relay->m_bloom_filter) {
7534 tx_relay->m_bloom_filter->insert(vData);
7542 Misbehaving(*peer,
"bad filteradd message");
7550 "filterclear received despite not offering bloom services "
7551 "from peer=%d; disconnecting\n",
7556 auto tx_relay = peer->GetTxRelay();
7562 LOCK(tx_relay->m_bloom_filter_mutex);
7563 tx_relay->m_bloom_filter =
nullptr;
7564 tx_relay->m_relay_txs =
true;
7573 vRecv >> newFeeFilter;
7575 if (
auto tx_relay = peer->GetTxRelay()) {
7576 tx_relay->m_fee_filter_received = newFeeFilter;
7585 ProcessGetCFilters(pfrom, *peer, vRecv);
7590 ProcessGetCFHeaders(pfrom, *peer, vRecv);
7595 ProcessGetCFCheckPt(pfrom, *peer, vRecv);
7600 std::vector<CInv> vInv;
7602 std::vector<TxId> tx_invs;
7607 for (
CInv &inv : vInv) {
7609 tx_invs.emplace_back(inv.
hash);
7616 LOCK(cs_proofrequest);
7617 m_proofrequest.ReceivedResponse(
7622 LOCK(m_tx_download_mutex);
7623 m_txdownloadman.ReceivedNotFound(pfrom.
GetId(), tx_invs);
7633bool PeerManagerImpl::MaybeDiscourageAndDisconnect(
CNode &pnode, Peer &peer) {
7635 LOCK(peer.m_misbehavior_mutex);
7638 if (!peer.m_should_discourage) {
7642 peer.m_should_discourage =
false;
7648 LogPrintf(
"Warning: not punishing noban peer %d!\n", peer.m_id);
7654 LogPrintf(
"Warning: not punishing manually connected peer %d!\n",
7663 "Warning: disconnecting but not discouraging %s peer %d!\n",
7680bool PeerManagerImpl::ProcessMessages(
const Config &config,
CNode *pfrom,
7681 std::atomic<bool> &interruptMsgProc) {
7685 PeerRef peer = GetPeerRef(pfrom->
GetId());
7686 if (peer ==
nullptr) {
7691 LOCK(peer->m_getdata_requests_mutex);
7692 if (!peer->m_getdata_requests.empty()) {
7693 ProcessGetData(config, *pfrom, *peer, interruptMsgProc);
7697 const bool processed_orphan = ProcessOrphanTx(config, *peer);
7703 if (processed_orphan) {
7710 LOCK(peer->m_getdata_requests_mutex);
7711 if (!peer->m_getdata_requests.empty()) {
7728 bool fMoreWork = poll_result->second;
7732 msg.m_recv.size(),
msg.m_recv.data());
7734 if (m_opts.capture_messages) {
7740 ProcessMessage(config, *pfrom,
msg.m_type,
msg.m_recv,
msg.m_time,
7742 if (interruptMsgProc) {
7747 LOCK(peer->m_getdata_requests_mutex);
7748 if (!peer->m_getdata_requests.empty()) {
7756 LOCK(m_tx_download_mutex);
7757 if (m_txdownloadman.HaveMoreWork(peer->m_id)) {
7760 }
catch (
const std::exception &e) {
7763 e.what(),
typeid(e).name());
7772void PeerManagerImpl::ConsiderEviction(
CNode &pto, Peer &peer,
7773 std::chrono::seconds time_in_seconds) {
7776 CNodeState &state = *State(pto.
GetId());
7779 state.fSyncStarted) {
7786 if (state.pindexBestKnownBlock !=
nullptr &&
7787 state.pindexBestKnownBlock->nChainWork >=
7789 if (state.m_chain_sync.m_timeout != 0s) {
7790 state.m_chain_sync.m_timeout = 0s;
7791 state.m_chain_sync.m_work_header =
nullptr;
7792 state.m_chain_sync.m_sent_getheaders =
false;
7794 }
else if (state.m_chain_sync.m_timeout == 0s ||
7795 (state.m_chain_sync.m_work_header !=
nullptr &&
7796 state.pindexBestKnownBlock !=
nullptr &&
7797 state.pindexBestKnownBlock->nChainWork >=
7798 state.m_chain_sync.m_work_header->nChainWork)) {
7804 state.m_chain_sync.m_work_header = m_chainman.
ActiveChain().
Tip();
7805 state.m_chain_sync.m_sent_getheaders =
false;
7806 }
else if (state.m_chain_sync.m_timeout > 0s &&
7807 time_in_seconds > state.m_chain_sync.m_timeout) {
7812 if (state.m_chain_sync.m_sent_getheaders) {
7815 "Disconnecting outbound peer %d for old chain, best known "
7818 state.pindexBestKnownBlock !=
nullptr
7819 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7823 assert(state.m_chain_sync.m_work_header);
7828 MaybeSendGetHeaders(
7829 pto,
GetLocator(state.m_chain_sync.m_work_header->pprev),
7833 "sending getheaders to outbound peer=%d to verify chain "
7834 "work (current best known block:%s, benchmark blockhash: "
7837 state.pindexBestKnownBlock !=
nullptr
7838 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7840 state.m_chain_sync.m_work_header->GetBlockHash()
7842 state.m_chain_sync.m_sent_getheaders =
true;
7849 state.m_chain_sync.m_timeout =
7856void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) {
7865 std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0},
7866 next_youngest_peer{-1, 0};
7872 if (pnode->
GetId() > youngest_peer.first) {
7873 next_youngest_peer = youngest_peer;
7874 youngest_peer.first = pnode->GetId();
7875 youngest_peer.second = pnode->m_last_block_time;
7879 NodeId to_disconnect = youngest_peer.first;
7880 if (youngest_peer.second > next_youngest_peer.second) {
7883 to_disconnect = next_youngest_peer.first;
7895 CNodeState *node_state = State(pnode->
GetId());
7896 if (node_state ==
nullptr ||
7898 node_state->vBlocksInFlight.empty())) {
7901 "disconnecting extra block-relay-only peer=%d "
7902 "(last block received at time %d)\n",
7909 "keeping block-relay-only peer=%d chosen for eviction "
7910 "(connect time: %d, blocks_in_flight: %d)\n",
7912 node_state->vBlocksInFlight.size());
7928 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
7939 CNodeState *state = State(pnode->
GetId());
7940 if (state ==
nullptr) {
7945 if (state->m_chain_sync.m_protect) {
7948 if (state->m_last_block_announcement < oldest_block_announcement ||
7949 (state->m_last_block_announcement == oldest_block_announcement &&
7950 pnode->
GetId() > worst_peer)) {
7951 worst_peer = pnode->
GetId();
7952 oldest_block_announcement = state->m_last_block_announcement;
7956 if (worst_peer == -1) {
7960 bool disconnected = m_connman.
ForNode(
7968 CNodeState &state = *State(pnode->
GetId());
7970 state.vBlocksInFlight.empty()) {
7972 "disconnecting extra outbound peer=%d (last block "
7973 "announcement received at time %d)\n",
7974 pnode->
GetId(), oldest_block_announcement);
7979 "keeping outbound peer=%d chosen for eviction "
7980 "(connect time: %d, blocks_in_flight: %d)\n",
7982 state.vBlocksInFlight.size());
7997void PeerManagerImpl::CheckForStaleTipAndEvictPeers() {
8000 auto now{GetTime<std::chrono::seconds>()};
8002 EvictExtraOutboundPeers(now);
8004 if (now > m_stale_tip_check_time) {
8010 LogPrintf(
"Potential stale tip detected, will try using extra "
8011 "outbound peer (last tip update: %d seconds ago)\n",
8020 if (!m_initial_sync_finished && CanDirectFetch()) {
8022 m_initial_sync_finished =
true;
8026void PeerManagerImpl::MaybeSendPing(
CNode &node_to, Peer &peer,
8027 std::chrono::microseconds now) {
8029 node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
8030 peer.m_ping_nonce_sent &&
8041 bool pingSend =
false;
8043 if (peer.m_ping_queued) {
8048 if (peer.m_ping_nonce_sent == 0 &&
8058 }
while (nonce == 0);
8059 peer.m_ping_queued =
false;
8060 peer.m_ping_start = now;
8061 peer.m_ping_nonce_sent = nonce;
8066void PeerManagerImpl::MaybeSendAddr(
CNode &
node, Peer &peer,
8067 std::chrono::microseconds current_time) {
8069 if (!peer.m_addr_relay_enabled) {
8073 LOCK(peer.m_addr_send_times_mutex);
8075 peer.m_next_local_addr_send < current_time) {
8082 if (peer.m_next_local_addr_send != 0us) {
8083 peer.m_addr_known->reset();
8086 CAddress local_addr{*local_service, peer.m_our_services,
8087 Now<NodeSeconds>()};
8088 PushAddress(peer, local_addr);
8090 peer.m_next_local_addr_send =
8096 if (current_time <= peer.m_next_addr_send) {
8100 peer.m_next_addr_send =
8103 const size_t max_addr_to_send = m_opts.max_addr_to_send;
8104 if (!
Assume(peer.m_addrs_to_send.size() <= max_addr_to_send)) {
8107 peer.m_addrs_to_send.resize(max_addr_to_send);
8112 auto addr_already_known =
8115 bool ret = peer.m_addr_known->contains(addr.
GetKey());
8117 peer.m_addr_known->insert(addr.
GetKey());
8121 peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(),
8122 peer.m_addrs_to_send.end(),
8123 addr_already_known),
8124 peer.m_addrs_to_send.end());
8127 if (peer.m_addrs_to_send.empty()) {
8131 const char *msg_type;
8133 if (peer.m_wants_addrv2) {
8143 peer.m_addrs_to_send));
8144 peer.m_addrs_to_send.clear();
8147 if (peer.m_addrs_to_send.capacity() > 40) {
8148 peer.m_addrs_to_send.shrink_to_fit();
8152void PeerManagerImpl::MaybeSendSendHeaders(
CNode &
node, Peer &peer) {
8157 if (!peer.m_sent_sendheaders) {
8159 CNodeState &state = *State(
node.GetId());
8160 if (state.pindexBestKnownBlock !=
nullptr &&
8161 state.pindexBestKnownBlock->nChainWork >
8168 peer.m_sent_sendheaders =
true;
8173void PeerManagerImpl::MaybeSendFeefilter(
8174 CNode &pto, Peer &peer, std::chrono::microseconds current_time) {
8175 if (m_opts.ignore_incoming_txs) {
8196 static const Amount MAX_FILTER{m_fee_filter_rounder.round(
MAX_MONEY)};
8197 if (peer.m_fee_filter_sent == MAX_FILTER) {
8200 peer.m_next_send_feefilter = 0us;
8203 if (current_time > peer.m_next_send_feefilter) {
8204 Amount filterToSend = m_fee_filter_rounder.round(currentFilter);
8206 filterToSend = std::max(
8208 if (filterToSend != peer.m_fee_filter_sent) {
8210 peer.m_fee_filter_sent = filterToSend;
8212 peer.m_next_send_feefilter =
8220 peer.m_next_send_feefilter &&
8221 (currentFilter < 3 * peer.m_fee_filter_sent / 4 ||
8222 currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
8223 peer.m_next_send_feefilter =
8231class CompareInvMempoolOrder {
8235 explicit CompareInvMempoolOrder(
CTxMemPool *_mempool) : mp(_mempool) {}
8237 bool operator()(std::set<TxId>::iterator a, std::set<TxId>::iterator b) {
8247bool PeerManagerImpl::RejectIncomingTxs(
const CNode &peer)
const {
8256 if (m_opts.ignore_incoming_txs &&
8263bool PeerManagerImpl::SetupAddressRelay(
const CNode &
node, Peer &peer) {
8267 if (
node.IsBlockOnlyConn()) {
8271 if (!peer.m_addr_relay_enabled.exchange(
true)) {
8275 peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
8281bool PeerManagerImpl::SendMessages(
const Config &config,
CNode *pto) {
8285 PeerRef peer = GetPeerRef(pto->
GetId());
8294 if (MaybeDiscourageAndDisconnect(*pto, *peer)) {
8303 const auto current_time{GetTime<std::chrono::microseconds>()};
8308 "addrfetch connection timeout; disconnecting peer=%d\n",
8314 MaybeSendPing(*pto, *peer, current_time);
8321 bool sync_blocks_and_headers_from_peer =
false;
8323 MaybeSendAddr(*pto, *peer, current_time);
8325 MaybeSendSendHeaders(*pto, *peer);
8330 CNodeState &state = *State(pto->
GetId());
8333 if (m_chainman.m_best_header ==
nullptr) {
8340 if (state.fPreferredDownload) {
8341 sync_blocks_and_headers_from_peer =
true;
8352 if (m_num_preferred_download_peers == 0 ||
8353 mapBlocksInFlight.empty()) {
8354 sync_blocks_and_headers_from_peer =
true;
8358 if (!state.fSyncStarted && CanServeBlocks(*peer) &&
8362 if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) ||
8364 const CBlockIndex *pindexStart = m_chainman.m_best_header;
8373 if (pindexStart->
pprev) {
8374 pindexStart = pindexStart->
pprev;
8376 if (MaybeSendGetHeaders(*pto,
GetLocator(pindexStart), *peer)) {
8379 "initial getheaders (%d) to peer=%d (startheight:%d)\n",
8381 peer->m_starting_height);
8383 state.fSyncStarted =
true;
8384 peer->m_headers_sync_timeout =
8389 std::chrono::microseconds{
8391 Ticks<std::chrono::seconds>(
8393 m_chainman.m_best_header->Time()) /
8410 LOCK(peer->m_block_inv_mutex);
8411 std::vector<CBlock> vHeaders;
8413 ((!peer->m_prefers_headers &&
8414 (!state.m_requested_hb_cmpctblocks ||
8415 peer->m_blocks_for_headers_relay.size() > 1)) ||
8416 peer->m_blocks_for_headers_relay.size() >
8421 ProcessBlockAvailability(pto->
GetId());
8423 if (!fRevertToInv) {
8424 bool fFoundStartingHeader =
false;
8428 for (
const BlockHash &hash : peer->m_blocks_for_headers_relay) {
8434 fRevertToInv =
true;
8437 if (pBestIndex !=
nullptr && pindex->
pprev != pBestIndex) {
8448 fRevertToInv =
true;
8451 pBestIndex = pindex;
8452 if (fFoundStartingHeader) {
8455 }
else if (PeerHasHeader(&state, pindex)) {
8458 }
else if (pindex->
pprev ==
nullptr ||
8459 PeerHasHeader(&state, pindex->
pprev)) {
8462 fFoundStartingHeader =
true;
8467 fRevertToInv =
true;
8472 if (!fRevertToInv && !vHeaders.empty()) {
8473 if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
8478 "%s sending header-and-ids %s to peer=%d\n",
8479 __func__, vHeaders.front().GetHash().ToString(),
8482 std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
8484 LOCK(m_most_recent_block_mutex);
8485 if (m_most_recent_block_hash ==
8487 cached_cmpctblock_msg =
8489 *m_most_recent_compact_block);
8492 if (cached_cmpctblock_msg.has_value()) {
8494 std::move(cached_cmpctblock_msg.value()));
8498 block, *pBestIndex)};
8505 state.pindexBestHeaderSent = pBestIndex;
8506 }
else if (peer->m_prefers_headers) {
8507 if (vHeaders.size() > 1) {
8509 "%s: %u headers, range (%s, %s), to peer=%d\n",
8510 __func__, vHeaders.size(),
8511 vHeaders.front().GetHash().ToString(),
8512 vHeaders.back().GetHash().ToString(),
8516 "%s: sending header %s to peer=%d\n", __func__,
8517 vHeaders.front().GetHash().ToString(),
8521 state.pindexBestHeaderSent = pBestIndex;
8523 fRevertToInv =
true;
8530 if (!peer->m_blocks_for_headers_relay.empty()) {
8532 peer->m_blocks_for_headers_relay.back();
8543 "Announcing block %s not on main chain (tip=%s)\n",
8552 if (!PeerHasHeader(&state, pindex)) {
8553 peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
8555 "%s: sending inv peer=%d hash=%s\n", __func__,
8560 peer->m_blocks_for_headers_relay.clear();
8567 std::vector<CInv> vInv;
8568 auto addInvAndMaybeFlush = [&](uint32_t type,
const uint256 &hash) {
8569 vInv.emplace_back(type, hash);
8580 LOCK(peer->m_block_inv_mutex);
8582 vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(),
8588 for (
const BlockHash &hash : peer->m_blocks_for_inv_relay) {
8591 peer->m_blocks_for_inv_relay.clear();
8594 auto computeNextInvSendTime =
8595 [&](std::chrono::microseconds &next)
8599 if (next < current_time) {
8600 fSendTrickle =
true;
8602 next = NextInvToInbounds(
8607 next = current_time;
8611 return fSendTrickle;
8615 if (peer->m_proof_relay !=
nullptr) {
8616 LOCK(peer->m_proof_relay->m_proof_inventory_mutex);
8618 if (computeNextInvSendTime(
8619 peer->m_proof_relay->m_next_inv_send_time)) {
8621 peer->m_proof_relay->m_proof_inventory_to_send.begin();
8623 peer->m_proof_relay->m_proof_inventory_to_send.end()) {
8626 it = peer->m_proof_relay->m_proof_inventory_to_send.erase(
8629 if (peer->m_proof_relay->m_proof_inventory_known_filter
8630 .contains(proofid)) {
8634 peer->m_proof_relay->m_proof_inventory_known_filter.insert(
8637 peer->m_proof_relay->m_recently_announced_proofs.insert(
8643 if (
auto tx_relay = peer->GetTxRelay()) {
8644 LOCK(tx_relay->m_tx_inventory_mutex);
8646 const bool fSendTrickle =
8647 computeNextInvSendTime(tx_relay->m_next_inv_send_time);
8652 LOCK(tx_relay->m_bloom_filter_mutex);
8653 if (!tx_relay->m_relay_txs) {
8654 tx_relay->m_tx_inventory_to_send.clear();
8659 if (fSendTrickle && tx_relay->m_send_mempool) {
8660 auto vtxinfo = m_mempool.
infoAll();
8661 tx_relay->m_send_mempool =
false;
8663 tx_relay->m_fee_filter_received.load()};
8665 LOCK(tx_relay->m_bloom_filter_mutex);
8667 for (
const auto &txinfo : vtxinfo) {
8668 const TxId &txid = txinfo.tx->GetId();
8669 tx_relay->m_tx_inventory_to_send.erase(txid);
8672 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8675 if (tx_relay->m_bloom_filter &&
8676 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8680 tx_relay->m_tx_inventory_known_filter.insert(txid);
8683 addInvAndMaybeFlush(
MSG_TX, txid);
8685 tx_relay->m_last_mempool_req =
8686 std::chrono::duration_cast<std::chrono::seconds>(
8693 std::vector<std::set<TxId>::iterator> vInvTx;
8694 vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
8695 for (std::set<TxId>::iterator it =
8696 tx_relay->m_tx_inventory_to_send.begin();
8697 it != tx_relay->m_tx_inventory_to_send.end(); it++) {
8698 vInvTx.push_back(it);
8701 tx_relay->m_fee_filter_received.load()};
8706 CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool);
8707 std::make_heap(vInvTx.begin(), vInvTx.end(),
8708 compareInvMempoolOrder);
8712 unsigned int nRelayedTransactions = 0;
8713 LOCK(tx_relay->m_bloom_filter_mutex);
8714 while (!vInvTx.empty() &&
8719 std::pop_heap(vInvTx.begin(), vInvTx.end(),
8720 compareInvMempoolOrder);
8721 std::set<TxId>::iterator it = vInvTx.back();
8723 const TxId txid = *it;
8725 tx_relay->m_tx_inventory_to_send.erase(it);
8727 if (tx_relay->m_tx_inventory_known_filter.contains(txid) &&
8728 tx_relay->m_avalanche_stalled_txids.count(txid) == 0) {
8732 auto txinfo = m_mempool.
info(txid);
8738 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8741 if (tx_relay->m_bloom_filter &&
8742 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8747 tx_relay->m_recently_announced_invs.insert(txid);
8748 addInvAndMaybeFlush(
MSG_TX, txid);
8749 nRelayedTransactions++;
8750 tx_relay->m_tx_inventory_known_filter.insert(txid);
8751 tx_relay->m_avalanche_stalled_txids.erase(txid);
8757 if (!vInv.empty()) {
8764 CNodeState &state = *State(pto->
GetId());
8767 auto stalling_timeout = m_block_stalling_timeout.load();
8768 if (state.m_stalling_since.count() &&
8769 state.m_stalling_since < current_time - stalling_timeout) {
8774 LogPrintf(
"Peer=%d is stalling block download, disconnecting\n",
8779 const auto new_timeout =
8781 if (stalling_timeout != new_timeout &&
8782 m_block_stalling_timeout.compare_exchange_strong(
8783 stalling_timeout, new_timeout)) {
8786 "Increased stalling timeout temporarily to %d seconds\n",
8798 if (state.vBlocksInFlight.size() > 0) {
8799 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
8800 int nOtherPeersWithValidatedDownloads =
8801 m_peers_downloading_from - 1;
8803 state.m_downloading_since +
8804 std::chrono::seconds{consensusParams.nPowTargetSpacing} *
8807 nOtherPeersWithValidatedDownloads)) {
8808 LogPrintf(
"Timeout downloading block %s from peer=%d, "
8810 queuedBlock.pindex->GetBlockHash().ToString(),
8818 if (state.fSyncStarted &&
8819 peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
8822 if (current_time > peer->m_headers_sync_timeout &&
8823 nSyncStarted == 1 &&
8824 (m_num_preferred_download_peers -
8825 state.fPreferredDownload >=
8834 LogPrintf(
"Timeout downloading headers from peer=%d, "
8840 LogPrintf(
"Timeout downloading headers from noban "
8841 "peer=%d, not disconnecting\n",
8847 state.fSyncStarted =
false;
8849 peer->m_headers_sync_timeout = 0us;
8855 peer->m_headers_sync_timeout = std::chrono::microseconds::max();
8861 ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
8864 std::vector<CInv> vGetData;
8872 CNodeState &state = *State(pto->
GetId());
8874 if (CanServeBlocks(*peer) &&
8875 ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) ||
8878 std::vector<const CBlockIndex *> vToDownload;
8880 auto get_inflight_budget = [&state]() {
8883 static_cast<int>(state.vBlocksInFlight.size()));
8889 FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload,
8892 !IsLimitedPeer(*peer)) {
8898 m_chainman.GetSnapshotBaseBlock());
8900 TryDownloadingHistoricalBlocks(
8901 *peer, get_inflight_budget(), vToDownload, from_tip,
8902 Assert(m_chainman.GetSnapshotBaseBlock()));
8906 BlockRequested(config, pto->
GetId(), *pindex);
8911 if (state.vBlocksInFlight.empty() && staller != -1) {
8912 if (State(staller)->m_stalling_since == 0us) {
8913 State(staller)->m_stalling_since = current_time;
8920 auto addGetDataAndMaybeFlush = [&](uint32_t type,
const uint256 &hash) {
8921 CInv inv(type, hash);
8924 vGetData.push_back(std::move(inv));
8935 LOCK(cs_proofrequest);
8936 std::vector<std::pair<NodeId, avalanche::ProofId>> expired;
8938 m_proofrequest.GetRequestable(pto->
GetId(), current_time, &expired);
8939 for (
const auto &entry : expired) {
8941 "timeout of inflight proof %s from peer=%d\n",
8942 entry.second.ToString(), entry.first);
8944 for (
const auto &proofid : requestable) {
8945 if (!AlreadyHaveProof(proofid)) {
8947 m_proofrequest.RequestedData(
8948 pto->
GetId(), proofid,
8955 m_proofrequest.ForgetInvId(proofid);
8966 LOCK(m_tx_download_mutex);
8967 for (
const TxId &txid : m_txdownloadman.GetRequestsToSend(
8968 pto->GetId(), current_time)) {
8969 addGetDataAndMaybeFlush(
MSG_TX, txid);
8972 if (!vGetData.empty()) {
8977 MaybeSendFeefilter(*pto, *peer, current_time);
8981bool PeerManagerImpl::ReceivedAvalancheProof(
CNode &
node, Peer &peer,
8986 LogError(
"ReceivedAvalancheProof: proof is null\n");
8992 AddKnownProof(peer, proofid);
9004 return node.m_avalanche_pubkey.has_value());
9005 auto saveProofIfStaker = [
this, isStaker](
const CNode &
node,
9007 const NodeId nodeid) ->
bool {
9019 LOCK(cs_proofrequest);
9020 m_proofrequest.ReceivedResponse(nodeid, proofid);
9022 if (AlreadyHaveProof(proofid)) {
9023 m_proofrequest.ForgetInvId(proofid);
9024 saveProofIfStaker(
node, proofid, nodeid);
9032 const auto now{GetTime<std::chrono::seconds>()};
9036 return pm.registerProof(proof, state);
9038 WITH_LOCK(cs_proofrequest, m_proofrequest.ForgetInvId(proofid));
9039 RelayProof(proofid);
9041 node.m_last_proof_time = now;
9044 nodeid, proofid.ToString());
9064 auto × = peer.m_invalid_avaproof_times;
9068 std::find_if(times.begin(), times.end(), [now](
const auto &t) {
9069 return t > now - AVALANCHE_INVALID_AVAPROOFS_INTERVAL;
9071 times.push_back(now);
9073 Misbehaving(peer,
"too-many-invalid-avaproofs");
9084 "Not polling the avalanche proof (%s): peer=%d, proofid %s\n",
9085 state.
IsValid() ?
"not-worth-polling"
9086 : state.GetRejectReason(),
9090 saveProofIfStaker(
node, proofid, nodeid);
bool MoneyRange(const Amount nValue)
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
enum ReadStatus_t ReadStatus
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
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)
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params ¶ms)
Return the time it would take to redo the work difference between from and to, assuming the current h...
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the identity function.
Stochastic address manager.
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
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".
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.
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
void Discourage(const CNetAddr &net_addr)
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
bool LookupFilterHashRange(int start_height, const CBlockIndex *stop_index, std::vector< uint256 > &hashes_out) const
Get a range of filter hashes between two heights on a chain.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
std::vector< CTransactionRef > txn
std::vector< uint32_t > indices
A CService with information about it as peer.
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
static constexpr SerParams V1_NETWORK
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
static constexpr SerParams V2_NETWORK
size_t BlockTxCount() const
std::string ToString() const
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
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.
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockHeader GetBlockHeader() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
int64_t GetBlockTime() const
unsigned int nTx
Number of transactions in this block.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
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...
int Height() const
Return the maximal height in the chain.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
const Consensus::Params & GetConsensus() const
CCoinsView that adds a memory cache for transactions to another CCoinsView.
CCoinsView that brings transactions from a mempool into view.
void ForEachNode(const NodeFn &func)
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
bool GetNetworkActive() const
bool GetTryNewOutboundPeer() const
void SetTryNewOutboundPeer(bool flag)
int GetExtraBlockRelayCount() const
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
void StartExtraBlockRelayPeers()
bool DisconnectNode(const std::string &node)
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
int GetExtraFullOutboundCount() const
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.
bool CheckIncomingNonce(uint64_t nonce)
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
bool GetUseAddrmanOutgoing() const
Fee rate in satoshis per virtualbyte: Amount / vB the feerate is represented internally as FeeFrac.
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Inv(ventory) message data.
bool IsMsgCmpctBlk() const
std::string ToString() const
bool IsMsgStakeContender() const
bool IsMsgFilteredBlk() const
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.
static constexpr SerParams V1
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Transport protocol agnostic message container.
Information about a peer.
Mutex cs_avalanche_pubkey
bool IsFeelerConn() const
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
bool ExpectServicesFromConn() const
std::atomic< int > nVersion
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
bool IsInboundConn() const
bool HasPermission(NetPermissionFlags permission) const
bool IsOutboundOrBlockRelayConn() const
bool IsManualConn() const
std::atomic< int64_t > nTimeOffset
const std::string m_addr_name
std::string ConnectionTypeAsString() const
void SetCommonVersion(int greatest_common_version)
std::atomic< bool > m_bip152_highbandwidth_to
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
std::atomic< bool > m_bip152_highbandwidth_from
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
std::atomic_bool fSuccessfullyConnected
bool IsAddrFetchConn() const
uint64_t GetLocalNonce() const
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
bool IsBlockOnlyConn() const
int GetCommonVersion() const
bool IsFullOutboundConn() const
uint64_t nRemoteHostNonce
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
std::atomic_bool fPauseSend
uint64_t nRemoteExtraEntropy
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
uint64_t GetLocalExtraEntropy() const
SteadyMilliseconds m_last_poll
double getAvailabilityScore() const
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
std::atomic< std::chrono::seconds > m_avalanche_last_message_fault
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
std::atomic< int > m_avalanche_message_fault_counter
How much faulty messages did this node accumulate.
std::atomic< bool > m_avalanche_enabled
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
std::atomic_bool fDisconnect
std::atomic< int > m_avalanche_message_fault_score
This score is incremented for every new faulty message received when m_avalanche_message_fault_counte...
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
void invsVoted(uint32_t count)
The node voted for count invs.
bool IsAvalancheOutboundConnection() const
An encapsulated public key.
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Simple class for background tasks that should be run periodically or once "after a while".
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.
A combination of a network address (CNetAddr) and a (TCP) port.
std::vector< uint8_t > GetKey() const
std::string ToStringAddrPort() const
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
The basic transaction that is broadcasted on the network and contained in blocks.
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 ...
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...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
bool setAvalancheFinalized(const CTxMemPoolEntryRef &tx, const Consensus::Params ¶ms, const CBlockIndex &active_chain_tip, Chainstate &active_chainstate, std::vector< TxId > &finalizedTxIds) EXCLUSIVE_LOCKS_REQUIRED(bool isAvalancheFinalizedPreConsensus(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool CompareTopologically(const TxId &txida, const TxId &txidb) const
TxMempoolInfo info(const TxId &txid) const
size_t DynamicMemoryUsage() const
std::vector< TxMempoolInfo > infoAll() const
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
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
auto withOrphanage(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_orphanage)
auto withConflicting(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_conflicting)
void removeForFinalizedBlock(const std::unordered_set< TxId, SaltedTxIdHasher > &confirmedTxIdsInNonFinalizedBlocks) EXCLUSIVE_LOCKS_REQUIRED(cs)
unsigned long size() const
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 BlockConnected(ChainstateRole role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void ActiveTipChange(const CBlockIndex &new_tip, bool is_ibd)
Notifies listeners any time the block chain tip changes, synchronously.
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...
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
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
Double ended buffer combining vector and stream-like interfaces.
void ignore(size_t num_ignore)
uint64_t rand64() noexcept
Generate a random 64-bit integer.
Reads data from an underlying stream, while hashing the read data.
A writer stream (for serialization) that computes a 256-bit hash.
Interface for message handling.
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
virtual bool ProcessMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool SendMessages(const Config &config, CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void InitializeNode(const Config &config, CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
virtual void FinalizeNode(const Config &config, const CNode &node)=0
Handle removal of a peer (clear state)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< CTransactionRef > &extra_txn)
bool IsTxAvailable(size_t index) const
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
virtual std::optional< std::string > FetchBlock(const Config &config, NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
virtual std::vector< TxOrphanage::PoolTx > GetOrphanTransactions()=0
virtual void SendPings()=0
Send ping message to all peers.
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, avalanche::Processor *const avalanche, Options opts)
virtual void StartScheduledTasks(CScheduler &scheduler)=0
Begin running background tasks, should only be called once.
virtual void ProcessMessage(const Config &config, CNode &pfrom, const std::string &msg_type, DataStream &vRecv, const std::chrono::microseconds time_received, const std::atomic< bool > &interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process a single message from a peer.
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
virtual void UnitTestMisbehaving(const NodeId peer_id)=0
Public for unit testing.
virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)=0
This function is used for testing the stale tip eviction logic, see denialofservice_tests....
virtual void CheckForStaleTipAndEvictPeers()=0
Evict extra outbound peers.
static RCUPtr make(Args &&...args)
Construct a new object that is owned by the pointer.
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
A Span is an object that can refer to a contiguous sequence of objects.
bool AddTx(const CTransactionRef &tx, NodeId peer)
Add a new transaction to the pool.
std::vector< CTransactionRef > GetConflictTxs(const CTransactionRef &tx) const
unsigned int LimitTxs(unsigned int max_txs, FastRandomContext &rng)
Limit the txs to the given maximum.
int EraseTx(const TxId &txid)
Erase a tx by txid.
void BlockInvalidated(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
void TransactionInvalidated(const CTransactionRef &tx, std::shared_ptr< const std::vector< Coin > > spent_coins)
std::string GetRejectReason() const
std::string ToString() const
256-bit unsigned big integer.
const std::vector< PrefilledProof > & getPrefilledProofs() const
uint64_t getShortID(const ProofId &proofid) const
const std::vector< uint64_t > & getShortIDs() const
ProofId getProofId() const
bool verify(DelegationState &state, CPubKey &auth) const
const DelegationId & getId() const
const LimitedProofId & getLimitedProofId() const
bool addNode(NodeId nodeid, const ProofId &proofid, size_t max_elements)
Node API.
bool shouldRequestMoreNodes()
Returns true if we encountered a lack of node since the last call.
bool exists(const ProofId &proofid) const
Return true if the (valid) proof exists, but only for non-dangling proofs.
bool forPeer(const ProofId &proofid, Callable &&func) const
void clearRemoteProofs(NodeId nodeid)
void removeUnbroadcastProof(const ProofId &proofid)
const ProofRadixTree & getShareableProofsSnapshot() const
bool isBoundToPeer(const ProofId &proofid) const
bool saveRemoteProof(const ProofId &proofid, const NodeId nodeid, const bool present)
void forEachPeer(Callable &&func) const
void setInvalid(const ProofId &proofid)
bool isInvalid(const ProofId &proofid) const
bool isImmature(const ProofId &proofid) const
const ProofPool & getDanglingProofPool() const
auto getUnbroadcastProofs() const
bool isInConflictingPool(const ProofId &proofid) const
void sendResponse(CNode *pfrom, Response response) const
bool addToReconcile(const AnyVoteItem &item) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
bool isStakingPreconsensusActivated(const CBlockIndex *pprev) const
int64_t getAvaproofsNodeCounter() const
bool isPreconsensusActivated(const CBlockIndex *pprev) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizationTip)
bool sendHello(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Send a avahello message.
void setRecentlyFinalized(const uint256 &itemId) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
size_t getMaxElementPoll() const
bool isQuorumEstablished() LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
void cleanupStakingRewards(const int minHeight) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
ProofRef getLocalProof() const
void acceptStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
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...
int getStakeContenderStatus(const StakeContenderId &contenderId) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Track votes on stake contenders.
void sendDelayedAvahello() EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
void finalizeStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
auto withPeerManager(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
bool registerVotes(NodeId nodeid, const Response &response, std::vector< VoteItemUpdate > &updates, bool &disconnect, std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
void rejectStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
void avaproofsSent(NodeId nodeid) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
void forEachProof(Callable &&func) const
std::vector< uint32_t > indices
constexpr bool IsNull() const
std::string ToString() const
std::string GetHex() const
Generate a new block, without valid proof-of-work.
bool ReadRawBlock(std::vector< uint8_t > &block, const FlatFilePos &pos) const
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool LoadingBlocks() const
bool IsPruneMode() const
Whether running in -prune mode.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
Class responsible for deciding what transactions to request and, once downloaded, whether and how to ...
static const uint256 ZERO
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
@ 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.
std::chrono::microseconds ComputeRequestTime(const InvRequestTracker< InvId > &requestTracker, NodeId nodeid, const DataRequestParameters &requestParams, std::chrono::microseconds current_time, bool preferred, bool bypass_limits)
Compute the request time for this announcement, current time plus delays for:
bool TooManyAnnouncements(const InvRequestTracker< InvId > &requestTracker, NodeId nodeid, const DataRequestParameters &requestParams, bool bypass_limits)
Whether the peer already has too many announcements tracked to accept a new one.
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
std::array< uint8_t, CPubKey::SCHNORR_SIZE > SchnorrSig
a Schnorr signature
#define LogPrintLevel(category, level,...)
#define LogDebug(category,...)
CSerializedNetMsg Make(std::string msg_type, Args &&...args)
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
const char * AVAPROOFSREQ
Request for missing avalanche proofs after an avaproofs message has been processed.
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
const char * BLOCK
The block message transmits a single serialized block.
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
const char * AVAPROOFS
The avaproofs message the proof short ids of all the valid proofs that we know.
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
const char * GETAVAPROOFS
The getavaproofs message requests an avaproofs message that provides the proof short ids of all the v...
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
const char * GETAVAADDR
The getavaaddr message requests an addr message from the receiving node, containing IP addresses of t...
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
const char * TX
The tx message transmits a single transaction.
const char * AVAHELLO
Contains a delegation and a signature.
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
const char * AVARESPONSE
Contains an avalanche::Response.
const char * GETDATA
The getdata message requests one or more data objects from another node.
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
const char * BLOCKTXN
Contains a BlockTransactions.
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
const char * AVAPOLL
Contains an avalanche::Poll.
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
const char * AVAPROOF
Contains an avalanche::Proof.
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
ShortIdProcessor< PrefilledProof, ShortIdProcessorPrefilledProofAdapter, ProofRefCompare > ProofShortIdProcessor
std::variant< const ProofRef, const CBlockIndex *, const StakeContenderId, const CTransactionRef > AnyVoteItem
RCUPtr< const Proof > ProofRef
static constexpr DataRequestParameters TX_REQUEST_PARAMS
Parameters for the tx requests, see DataRequestParameters.
Implement std::hash so RCUPtr can be used as a key for maps or sets.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
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.
std::string userAgent(const Config &config)
bool IsReachable(enum Network net)
bool SeenLocal(const CService &addr)
vote for a local address
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
@ BypassProofRequestLimits
static constexpr auto HEADERS_RESPONSE_TIME
How long to wait for a peer to respond to a getheaders request.
static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET
The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND based inc...
static constexpr size_t MAX_AVALANCHE_STALLED_TXIDS_PER_PEER
Maximum number of stalled avalanche txids to store per peer.
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT
Default time during which a peer must stall block download progress before being disconnected.
static constexpr auto GETAVAADDR_INTERVAL
Minimum time between 2 successives getavaaddr messages from the same peer.
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL
Verify that INVENTORY_MAX_RECENT_RELAY is enough to cache everything typically relayed before uncondi...
static constexpr unsigned int INVENTORY_BROADCAST_MAX_PER_MB
Maximum number of inventory items to send per transmission.
static constexpr auto EXTRA_PEER_CHECK_INTERVAL
How frequently to check for extra outbound peers and disconnect.
static const unsigned int BLOCK_DOWNLOAD_WINDOW
Size of the "block download window": how far ahead of our current height do we fetch?...
static uint32_t getAvalancheVoteForProof(const avalanche::Processor &avalanche, const avalanche::ProofId &id)
Decide a response for an Avalanche poll about the given proof.
static constexpr int STALE_RELAY_AGE_LIMIT
Age after which a stale block will no longer be served if requested as protection against fingerprint...
static constexpr int HISTORICAL_BLOCK_AGE
Age after which a block is considered historical for purposes of rate limiting block relay.
static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL
Delay between rotating the peers we relay a particular address to.
static constexpr auto AVALANCHE_INVALID_AVAPROOFS_INTERVAL
Interval to look back for bad avaproofs.
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict.
static constexpr auto CHAIN_SYNC_TIMEOUT
Timeout for (unprotected) outbound peers to sync to our chainwork.
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS
Minimum blocks required to signal NODE_NETWORK_LIMITED.
static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
Average delay between local address broadcasts.
static const int MAX_BLOCKTXN_DEPTH
Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for.
static constexpr uint64_t CMPCTBLOCKS_VERSION
The compactblocks version we support.
bool IsAvalancheMessageType(const std::string &msg_type)
static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT
Protect at least this many outbound peers from disconnection due to slow/behind headers chain.
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for inbound peers.
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY
Maximum feefilter broadcast delay after significant change.
static constexpr uint32_t MAX_GETCFILTERS_SIZE
Maximum number of compact filters that may be requested with one getcfilters.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE
Headers download timeout.
static const unsigned int MAX_GETDATA_SZ
Limit to avoid sending big packets.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in multiples of the block interval (i.e.
static constexpr auto AVALANCHE_AVAPROOFS_TIMEOUT
If no proof was requested from a compact proof message after this timeout expired,...
static constexpr auto STALE_CHECK_INTERVAL
How frequently to check for stale tips.
static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY
The number of most recently announced transactions a peer can request.
static constexpr auto UNCONDITIONAL_RELAY_DELAY
How long a transaction has to be in the mempool before it can unconditionally be relayed.
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL
Average delay between peer address broadcasts.
static constexpr auto GETAVAPROOFS_INTERVAL
Minimum time between 2 successive getavaproofs messages from the same peer.
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
Additional block download timeout per parallel downloading peer (i.e.
static constexpr double MAX_ADDR_RATE_PER_SECOND
The maximum rate of address records we're willing to process on average.
static constexpr auto PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive.
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested.
static constexpr DataRequestParameters PROOF_REQUEST_PARAMS
static constexpr size_t AVALANCHE_MAX_INVALID_AVAPROOFS
Maximum number of failed avaproof registrations (e.g.
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
static constexpr uint32_t MAX_GETCFHEADERS_SIZE
Maximum number of cf hashes that may be requested with one getcfheaders.
static constexpr auto BLOCK_STALLING_TIMEOUT_MAX
Maximum timeout for stalling block download.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY
SHA256("main address relay")[0:8].
static constexpr size_t MAX_PCT_ADDR_TO_SEND
the maximum percentage of addresses from our addrman to return in response to a getaddr message.
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND
Maximum rate of inventory items to send per second.
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of address records permitted in an ADDR message.
static const unsigned int MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK
Maximum number of outstanding CMPCTBLOCK requests for the same block.
static const unsigned int MAX_HEADERS_RESULTS
Number of headers sent in one getheaders result.
bool IsProxy(const CNetAddr &addr)
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
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
static constexpr size_t AVALANCHE_MAX_ELEMENT_POLL_LEGACY
Legacy maximum element poll.
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
@ MSG_AVA_STAKE_CONTENDER
@ MSG_CMPCT_BLOCK
Defined in BIP152.
ServiceFlags
nServices flags.
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
static const int PROTOCOL_VERSION
network protocol versioning
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
static const int AVALANCHE_MAX_ELEMENT_BUMP_VERSION
Avalanche can poll up to 1024 items per message starting with this version.
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
reverse_range< T > reverse_iterate(T &x)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
void Unserialize(Stream &, V)=delete
#define LIMITED_STRING(obj, n)
static auto WithParams(const Params ¶ms, T &&t)
Return a wrapper around t that (de)serializes it with specified parameter params.
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
static const double AVALANCHE_STATISTICS_DECAY_FACTOR
Pre-computed decay factor for the avalanche statistics computation.
static constexpr std::chrono::minutes AVALANCHE_STATISTICS_REFRESH_PERIOD
Refresh period for the avalanche statistics computation.
static constexpr Amount zero() noexcept
A BlockHash is a unqiue identifier for a block.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< BlockHash > vHave
std::chrono::microseconds m_ping_wait
Amount m_fee_filter_received
std::vector< int > vHeightInFlight
bool m_addr_relay_enabled
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
ServiceFlags their_services
Parameters that influence chain consensus.
int64_t nPowTargetSpacing
std::chrono::seconds PowTargetSpacing() const
const size_t max_peer_announcements
Maximum number of inventories to consider for requesting, per peer.
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).
const ResultType m_result_type
Result type.
const TxValidationState m_state
Contains information about why the transaction failed.
@ 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.
std::chrono::time_point< NodeClock > time_point
Validation result for package mempool acceptance.
PackageValidationState m_state
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
This is a radix tree storing values identified by a unique key.
A TxId is the identifier of a transaction.
std::chrono::seconds registration_time
StakeContenderIds are unique for each block to ensure that the peer polling for their acceptance has ...
ValidationSignals * signals
ValidationSignals * signals
CFeeRate min_relay_feerate
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
std::vector< NodeId > m_senders
std::string ToString() const
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
#define ACQUIRED_BEFORE(...)
#define NO_THREAD_SAFETY_ANALYSIS
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
constexpr int64_t count_microseconds(std::chrono::microseconds t)
constexpr int64_t count_seconds(std::chrono::seconds t)
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
NodeClock::time_point GetAdjustedTime()
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
#define TRACE6(context, event, a, b, c, d, e, f)
@ AVALANCHE
Removed by avalanche vote.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
bool IsBlockMutated(const CBlock &block)
Check if a block has been mutated (with respect to its merkle root).
std::optional< std::vector< Coin > > GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view)
Get the coins spent by ptx from the coins_view.
arith_uint256 CalculateClaimedHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the claimed work on a given set of headers.
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...