54#include <boost/multi_index/hashed_index.hpp>
55#include <boost/multi_index/member.hpp>
56#include <boost/multi_index/ordered_index.hpp>
57#include <boost/multi_index_container.hpp>
115 "Max protocol message length must be greater than largest "
116 "possible INV message");
173 std::chrono::seconds(2),
174 std::chrono::seconds(2),
175 std::chrono::seconds(60),
182 std::chrono::seconds(2),
183 std::chrono::seconds(2),
184 std::chrono::seconds(60),
217 "MAX_BLOCKTXN_DEPTH too high");
276 std::chrono::seconds{1},
277 "INVENTORY_RELAY_MAX too low");
328 std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
333 std::chrono::seconds timeAdded;
335 StalledTxId(
TxId txid_, std::chrono::seconds timeAdded_)
336 : txid(txid_), timeAdded(timeAdded_){};
342using StalledTxIdSet = boost::multi_index_container<
344 boost::multi_index::indexed_by<
346 boost::multi_index::hashed_unique<
347 boost::multi_index::tag<by_txid>,
348 boost::multi_index::member<StalledTxId, TxId, &StalledTxId::txid>,
351 boost::multi_index::ordered_non_unique<
352 boost::multi_index::tag<by_time>,
353 boost::multi_index::member<StalledTxId, std::chrono::seconds,
354 &StalledTxId::timeAdded>>>>;
391 std::atomic<ServiceFlags> m_their_services{
NODE_NONE};
394 Mutex m_misbehavior_mutex;
399 bool m_should_discourage
GUARDED_BY(m_misbehavior_mutex){
false};
402 Mutex m_block_inv_mutex;
408 std::vector<BlockHash> m_blocks_for_inv_relay
GUARDED_BY(m_block_inv_mutex);
414 std::vector<BlockHash>
415 m_blocks_for_headers_relay
GUARDED_BY(m_block_inv_mutex);
426 std::atomic<int> m_starting_height{-1};
429 std::atomic<uint64_t> m_ping_nonce_sent{0};
431 std::atomic<std::chrono::microseconds> m_ping_start{0us};
433 std::atomic<bool> m_ping_queued{
false};
443 std::chrono::microseconds m_next_send_feefilter
456 bool m_relay_txs
GUARDED_BY(m_bloom_filter_mutex){
false};
461 std::unique_ptr<CBloomFilter>
477 GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
483 std::set<TxId> m_tx_inventory_to_send
GUARDED_BY(m_tx_inventory_mutex);
489 bool m_send_mempool
GUARDED_BY(m_tx_inventory_mutex){
false};
491 std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
496 std::chrono::microseconds
497 m_next_inv_send_time
GUARDED_BY(m_tx_inventory_mutex){0};
503 std::atomic<Amount> m_fee_filter_received{
Amount::zero()};
509 m_avalanche_stalled_txids
GUARDED_BY(m_tx_inventory_mutex);
517 LOCK(m_tx_relay_mutex);
519 m_tx_relay = std::make_unique<Peer::TxRelay>();
520 return m_tx_relay.get();
524 return WITH_LOCK(m_tx_relay_mutex,
return m_tx_relay.get());
526 const TxRelay *GetTxRelay() const
528 return WITH_LOCK(m_tx_relay_mutex,
return m_tx_relay.get());
533 std::set<avalanche::ProofId>
534 m_proof_inventory_to_send
GUARDED_BY(m_proof_inventory_mutex);
537 GUARDED_BY(m_proof_inventory_mutex){10000, 0.000001};
544 std::chrono::microseconds m_next_inv_send_time{0};
548 std::atomic<std::chrono::seconds> lastSharedProofsUpdate{0s};
549 std::atomic<bool> compactproofs_requested{
false};
556 const std::unique_ptr<ProofRelay> m_proof_relay;
561 std::vector<CAddress>
573 std::unique_ptr<CRollingBloomFilter>
591 std::atomic_bool m_addr_relay_enabled{
false};
595 mutable Mutex m_addr_send_times_mutex;
597 std::chrono::microseconds
598 m_next_addr_send
GUARDED_BY(m_addr_send_times_mutex){0};
600 std::chrono::microseconds
601 m_next_local_addr_send
GUARDED_BY(m_addr_send_times_mutex){0};
606 std::atomic_bool m_wants_addrv2{
false};
610 mutable Mutex m_addr_token_bucket_mutex;
615 double m_addr_token_bucket
GUARDED_BY(m_addr_token_bucket_mutex){1.0};
617 std::chrono::microseconds
619 GetTime<std::chrono::microseconds>()};
621 std::atomic<uint64_t> m_addr_rate_limited{0};
626 std::atomic<uint64_t> m_addr_processed{0};
632 bool m_inv_triggered_getheaders_before_sync
636 Mutex m_getdata_requests_mutex;
638 std::deque<CInv> m_getdata_requests
GUARDED_BY(m_getdata_requests_mutex);
645 Mutex m_headers_sync_mutex;
650 std::unique_ptr<HeadersSyncState>
655 std::atomic<bool> m_sent_sendheaders{
false};
658 std::chrono::microseconds m_headers_sync_timeout
669 : m_id(id), m_our_services{our_services},
670 m_proof_relay(fRelayProofs ?
std::make_unique<ProofRelay>()
674 mutable Mutex m_tx_relay_mutex;
677 std::unique_ptr<TxRelay> m_tx_relay
GUARDED_BY(m_tx_relay_mutex);
680using PeerRef = std::shared_ptr<Peer>;
698 bool fSyncStarted{
false};
701 std::chrono::microseconds m_stalling_since{0us};
702 std::list<QueuedBlock> vBlocksInFlight;
705 std::chrono::microseconds m_downloading_since{0us};
707 bool fPreferredDownload{
false};
712 bool m_requested_hb_cmpctblocks{
false};
714 bool m_provides_cmpctblocks{
false};
742 struct ChainSyncTimeoutState {
745 std::chrono::seconds m_timeout{0s};
749 bool m_sent_getheaders{
false};
752 bool m_protect{
false};
755 ChainSyncTimeoutState m_chain_sync;
758 int64_t m_last_block_announcement{0};
761 const bool m_is_inbound;
763 CNodeState(
bool is_inbound) : m_is_inbound(is_inbound) {}
774 const std::shared_ptr<const CBlock> &pblock,
782 bool fInitialDownload)
override
788 const std::shared_ptr<const CBlock> &pblock)
override
797 !m_headers_presync_mutex);
799 std::atomic<bool> &interrupt)
override
801 !m_recent_confirmed_transactions_mutex,
802 !m_most_recent_block_mutex, !cs_proofrequest,
803 !m_headers_presync_mutex, g_msgproc_mutex);
806 !m_recent_confirmed_transactions_mutex,
807 !m_most_recent_block_mutex, !cs_proofrequest,
813 std::optional<std::string>
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
834 !m_recent_confirmed_transactions_mutex,
835 !m_most_recent_block_mutex, !cs_proofrequest,
836 !m_headers_presync_mutex, g_msgproc_mutex);
838 int64_t time_in_seconds)
override;
845 void ConsiderEviction(
CNode &pto, Peer &peer,
846 std::chrono::seconds time_in_seconds)
853 void EvictExtraOutboundPeers(std::chrono::seconds now)
860 void ReattemptInitialBroadcast(
CScheduler &scheduler)
866 void UpdateAvalancheStatistics()
const;
871 void AvalanchePeriodicNetworking(
CScheduler &scheduler)
const;
889 void Misbehaving(Peer &peer,
const std::string &message);
901 void MaybePunishNodeForBlock(
NodeId nodeid,
903 bool via_compact_block,
904 const std::string &message =
"")
912 const
std::
string &message = "")
924 bool MaybeDiscourageAndDisconnect(
CNode &pnode, Peer &peer);
942 bool maybe_add_extra_compact_tx)
945 struct PackageToValidate {
947 const std::vector<NodeId> m_senders;
952 : m_txns{parent, child}, m_senders{parent_sender, child_sender} {}
955 Assume(m_txns.size() == 2);
957 "parent %s (sender=%d) + child %s (sender=%d)",
958 m_txns.front()->GetId().ToString(), m_senders.front(),
959 m_txns.back()->GetId().ToString(), m_senders.back());
968 void ProcessPackageResult(
const PackageToValidate &package_to_validate,
978 std::optional<PackageToValidate> Find1P1CPackage(
const CTransactionRef &ptx,
1005 bool ProcessOrphanTx(
const Config &config, Peer &peer)
1018 void ProcessHeadersMessage(
const Config &config,
CNode &pfrom, Peer &peer,
1019 std::vector<CBlockHeader> &&headers,
1020 bool via_compact_block)
1030 bool CheckHeadersPoW(
const std::vector<CBlockHeader> &headers,
1040 void HandleUnconnectingHeaders(
CNode &pfrom, Peer &peer,
1041 const std::vector<CBlockHeader> &headers)
1045 CheckHeadersAreContinuous(
const std::vector<CBlockHeader> &headers)
const;
1065 bool IsContinuationOfLowWorkHeadersSync(Peer &peer,
CNode &pfrom,
1066 std::vector<CBlockHeader> &headers)
1068 !m_headers_presync_mutex, g_msgproc_mutex);
1082 bool TryLowWorkHeadersSync(Peer &peer,
CNode &pfrom,
1084 std::vector<CBlockHeader> &headers)
1086 !m_headers_presync_mutex, g_msgproc_mutex);
1092 bool IsAncestorOfBestHeaderOrTip(
const CBlockIndex *header)
1106 void HeadersDirectFetchBlocks(
const Config &config,
CNode &pfrom,
1109 void UpdatePeerStateForReceivedHeaders(
CNode &pfrom, Peer &peer,
1111 bool received_new_header,
1112 bool may_have_more_headers)
1115 void SendBlockTransactions(
CNode &pfrom, Peer &peer,
const CBlock &block,
1124 std::chrono::microseconds current_time)
1134 std::chrono::microseconds current_time,
bool preferred)
1139 m_connman.PushMessage(&
node, std::move(
msg));
1141 template <
typename... Args>
1142 void MakeAndPushMessage(
CNode &
node, std::string msg_type,
1143 Args &&...args)
const {
1145 std::forward<Args>(args)...));
1149 void PushNodeVersion(
const Config &config,
CNode &pnode,
const Peer &peer);
1157 void MaybeSendPing(
CNode &node_to, Peer &peer,
1158 std::chrono::microseconds now);
1161 void MaybeSendAddr(
CNode &
node, Peer &peer,
1162 std::chrono::microseconds current_time)
1169 void MaybeSendSendHeaders(
CNode &
node, Peer &peer)
1173 void MaybeSendFeefilter(
CNode &
node, Peer &peer,
1174 std::chrono::microseconds current_time)
1186 void RelayAddress(
NodeId originator,
const CAddress &addr,
bool fReachable)
1207 Mutex cs_proofrequest;
1212 std::atomic<int> m_best_height{-1};
1217 const Options m_opts;
1219 bool RejectIncomingTxs(
const CNode &peer)
const;
1231 mutable Mutex m_peer_mutex;
1238 std::map<NodeId, PeerRef> m_peer_map
GUARDED_BY(m_peer_mutex);
1247 const CNodeState *State(
NodeId pnode)
const
1252 std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us};
1259 m_last_block_inv_triggering_headers_sync
GUARDED_BY(g_msgproc_mutex){};
1267 std::map<BlockHash, std::pair<NodeId, bool>>
1277 std::atomic<std::chrono::seconds> m_block_stalling_timeout{
1291 bool AlreadyHaveTx(
const TxId &txid,
bool include_reconsiderable)
1293 !m_recent_confirmed_transactions_mutex);
1356 mutable Mutex m_recent_confirmed_transactions_mutex;
1358 GUARDED_BY(m_recent_confirmed_transactions_mutex){24'000, 0.000'001};
1367 std::chrono::microseconds
1368 NextInvToInbounds(std::chrono::microseconds now,
1369 std::chrono::seconds average_interval)
1374 mutable Mutex m_most_recent_block_mutex;
1375 std::shared_ptr<const CBlock>
1376 m_most_recent_block
GUARDED_BY(m_most_recent_block_mutex);
1377 std::shared_ptr<const CBlockHeaderAndShortTxIDs>
1378 m_most_recent_compact_block
GUARDED_BY(m_most_recent_block_mutex);
1380 std::unique_ptr<const std::map<TxId, CTransactionRef>>
1381 m_most_recent_block_txs
GUARDED_BY(m_most_recent_block_mutex);
1386 Mutex m_headers_presync_mutex;
1397 using HeadersPresyncStats =
1398 std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>;
1400 std::map<NodeId, HeadersPresyncStats>
1401 m_headers_presync_stats
GUARDED_BY(m_headers_presync_mutex){};
1405 std::atomic_bool m_headers_presync_should_signal{
false};
1413 bool IsBlockRequested(
const BlockHash &hash)
1417 bool IsBlockRequestedFromOutbound(
const BlockHash &hash)
1428 void RemoveBlockRequest(
const BlockHash &hash,
1429 std::optional<NodeId> from_peer)
1438 bool BlockRequested(
const Config &config,
NodeId nodeid,
1440 std::list<QueuedBlock>::iterator **pit =
nullptr)
1449 void FindNextBlocksToDownload(const Peer &peer,
unsigned int count,
1455 void TryDownloadingHistoricalBlocks(
1456 const Peer &peer,
unsigned int count,
1490 const Peer &peer, CNodeState *state,
1492 int nWindowEnd, const
CChain *activeChain =
nullptr,
1493 NodeId *nodeStaller =
nullptr)
1503 std::atomic<
std::chrono::seconds> m_last_tip_update{0s};
1510 const std::chrono::seconds mempool_req,
1511 const std::chrono::seconds now)
1516 void ProcessGetData(
const Config &config,
CNode &pfrom, Peer &peer,
1517 const std::atomic<bool> &interruptMsgProc)
1519 peer.m_getdata_requests_mutex,
1525 const std::shared_ptr<const CBlock> &block,
1526 bool force_processing,
bool min_pow_checked);
1534 void MaybeSetPeerAsAnnouncingHeaderAndIDs(
NodeId nodeid)
1553 std::vector<CTransactionRef>
1554 vExtraTxnForCompact
GUARDED_BY(g_msgproc_mutex);
1556 size_t vExtraTxnForCompactIt
GUARDED_BY(g_msgproc_mutex) = 0;
1561 void ProcessBlockAvailability(
NodeId nodeid)
1576 bool BlockRequestAllowed(const
CBlockIndex *pindex)
1578 bool AlreadyHaveBlock(const
BlockHash &block_hash)
1580 bool AlreadyHaveProof(const
avalanche::ProofId &proofid);
1581 void ProcessGetBlockData(const
Config &config,
CNode &pfrom, Peer &peer,
1604 bool PrepareBlockFilterRequest(
CNode &
node, Peer &peer,
1606 uint32_t start_height,
1608 uint32_t max_height_diff,
1650 uint32_t GetAvalancheVoteForBlock(const
BlockHash &hash) const
1661 const
TxId &
id) const
1663 !m_recent_confirmed_transactions_mutex);
1672 bool SetupAddressRelay(const
CNode &
node, Peer &peer)
1675 void AddAddressKnown(Peer &peer, const
CAddress &addr)
1677 void PushAddress(Peer &peer, const
CAddress &addr)
1685 bool ReceivedAvalancheProof(
CNode &
node, Peer &peer,
1691 const
std::chrono::seconds now)
1694 bool isPreferredDownloadPeer(const
CNode &pfrom);
1697const CNodeState *PeerManagerImpl::State(
NodeId pnode) const
1699 std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
1700 if (it == m_node_states.end()) {
1707CNodeState *PeerManagerImpl::State(
NodeId pnode)
1709 return const_cast<CNodeState *
>(std::as_const(*this).State(pnode));
1717static bool IsAddrCompatible(
const Peer &peer,
const CAddress &addr) {
1721void PeerManagerImpl::AddAddressKnown(Peer &peer,
const CAddress &addr) {
1722 assert(peer.m_addr_known);
1723 peer.m_addr_known->insert(addr.
GetKey());
1726void PeerManagerImpl::PushAddress(Peer &peer,
const CAddress &addr) {
1730 assert(peer.m_addr_known);
1731 if (addr.
IsValid() && !peer.m_addr_known->contains(addr.
GetKey()) &&
1732 IsAddrCompatible(peer, addr)) {
1733 if (peer.m_addrs_to_send.size() >= m_opts.max_addr_to_send) {
1734 peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] =
1737 peer.m_addrs_to_send.push_back(addr);
1742static void AddKnownTx(Peer &peer,
const TxId &txid) {
1743 auto tx_relay = peer.GetTxRelay();
1748 LOCK(tx_relay->m_tx_inventory_mutex);
1749 tx_relay->m_tx_inventory_known_filter.insert(txid);
1753 if (peer.m_proof_relay !=
nullptr) {
1754 LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
1755 peer.m_proof_relay->m_proof_inventory_known_filter.insert(proofid);
1759bool PeerManagerImpl::isPreferredDownloadPeer(
const CNode &pfrom) {
1761 const CNodeState *state = State(pfrom.
GetId());
1762 return state && state->fPreferredDownload;
1765static bool CanServeBlocks(
const Peer &peer) {
1773static bool IsLimitedPeer(
const Peer &peer) {
1778std::chrono::microseconds
1779PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
1780 std::chrono::seconds average_interval) {
1781 if (m_next_inv_to_inbounds.load() < now) {
1786 m_next_inv_to_inbounds =
1787 now + m_rng.rand_exp_duration(average_interval);
1789 return m_next_inv_to_inbounds;
1792bool PeerManagerImpl::IsBlockRequested(
const BlockHash &hash) {
1793 return mapBlocksInFlight.count(hash);
1796bool PeerManagerImpl::IsBlockRequestedFromOutbound(
const BlockHash &hash) {
1797 for (
auto range = mapBlocksInFlight.equal_range(hash);
1798 range.first != range.second; range.first++) {
1799 auto [nodeid, block_it] = range.first->second;
1800 CNodeState &nodestate = *
Assert(State(nodeid));
1801 if (!nodestate.m_is_inbound) {
1809void PeerManagerImpl::RemoveBlockRequest(
const BlockHash &hash,
1810 std::optional<NodeId> from_peer) {
1811 auto range = mapBlocksInFlight.equal_range(hash);
1812 if (range.first == range.second) {
1820 while (range.first != range.second) {
1821 auto [node_id, list_it] = range.first->second;
1823 if (from_peer && *from_peer != node_id) {
1828 CNodeState &state = *
Assert(State(node_id));
1830 if (state.vBlocksInFlight.begin() == list_it) {
1833 state.m_downloading_since =
1834 std::max(state.m_downloading_since,
1835 GetTime<std::chrono::microseconds>());
1837 state.vBlocksInFlight.erase(list_it);
1839 if (state.vBlocksInFlight.empty()) {
1841 m_peers_downloading_from--;
1843 state.m_stalling_since = 0us;
1845 range.first = mapBlocksInFlight.erase(range.first);
1849bool PeerManagerImpl::BlockRequested(
const Config &config,
NodeId nodeid,
1851 std::list<QueuedBlock>::iterator **pit) {
1854 CNodeState *state = State(nodeid);
1855 assert(state !=
nullptr);
1860 for (
auto range = mapBlocksInFlight.equal_range(hash);
1861 range.first != range.second; range.first++) {
1862 if (range.first->second.first == nodeid) {
1864 *pit = &range.first->second.second;
1871 RemoveBlockRequest(hash, nodeid);
1873 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(
1874 state->vBlocksInFlight.end(),
1875 {&block, std::unique_ptr<PartiallyDownloadedBlock>(
1876 pit ? new PartiallyDownloadedBlock(config, &m_mempool)
1878 if (state->vBlocksInFlight.size() == 1) {
1880 state->m_downloading_since = GetTime<std::chrono::microseconds>();
1881 m_peers_downloading_from++;
1884 auto itInFlight = mapBlocksInFlight.insert(
1885 std::make_pair(hash, std::make_pair(nodeid, it)));
1888 *pit = &itInFlight->second.second;
1894void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(
NodeId nodeid) {
1900 if (m_opts.ignore_incoming_txs) {
1904 CNodeState *nodestate = State(nodeid);
1909 if (!nodestate->m_provides_cmpctblocks) {
1912 int num_outbound_hb_peers = 0;
1913 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin();
1914 it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
1915 if (*it == nodeid) {
1916 lNodesAnnouncingHeaderAndIDs.erase(it);
1917 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
1920 CNodeState *state = State(*it);
1921 if (state !=
nullptr && !state->m_is_inbound) {
1922 ++num_outbound_hb_peers;
1925 if (nodestate->m_is_inbound) {
1928 if (lNodesAnnouncingHeaderAndIDs.size() >= 3 &&
1929 num_outbound_hb_peers == 1) {
1930 CNodeState *remove_node =
1931 State(lNodesAnnouncingHeaderAndIDs.front());
1932 if (remove_node !=
nullptr && !remove_node->m_is_inbound) {
1935 std::swap(lNodesAnnouncingHeaderAndIDs.front(),
1936 *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
1943 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
1947 lNodesAnnouncingHeaderAndIDs.front(), [
this](
CNode *pnodeStop) {
1948 MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT,
1950 CMPCTBLOCKS_VERSION);
1953 pnodeStop->m_bip152_highbandwidth_to = false;
1956 lNodesAnnouncingHeaderAndIDs.pop_front();
1963 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->
GetId());
1968bool PeerManagerImpl::TipMayBeStale() {
1971 if (m_last_tip_update.load() == 0s) {
1972 m_last_tip_update = GetTime<std::chrono::seconds>();
1974 return m_last_tip_update.load() <
1975 GetTime<std::chrono::seconds>() -
1978 mapBlocksInFlight.empty();
1981bool PeerManagerImpl::CanDirectFetch() {
1987static bool PeerHasHeader(CNodeState *state,
const CBlockIndex *pindex)
1989 if (state->pindexBestKnownBlock &&
1990 pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) {
1993 if (state->pindexBestHeaderSent &&
1994 pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) {
2000void PeerManagerImpl::ProcessBlockAvailability(
NodeId nodeid) {
2001 CNodeState *state = State(nodeid);
2002 assert(state !=
nullptr);
2004 if (!state->hashLastUnknownBlock.IsNull()) {
2008 if (state->pindexBestKnownBlock ==
nullptr ||
2009 pindex->
nChainWork >= state->pindexBestKnownBlock->nChainWork) {
2010 state->pindexBestKnownBlock = pindex;
2012 state->hashLastUnknownBlock.SetNull();
2017void PeerManagerImpl::UpdateBlockAvailability(
NodeId nodeid,
2019 CNodeState *state = State(nodeid);
2020 assert(state !=
nullptr);
2022 ProcessBlockAvailability(nodeid);
2027 if (state->pindexBestKnownBlock ==
nullptr ||
2028 pindex->
nChainWork >= state->pindexBestKnownBlock->nChainWork) {
2029 state->pindexBestKnownBlock = pindex;
2034 state->hashLastUnknownBlock = hash;
2040void PeerManagerImpl::FindNextBlocksToDownload(
2041 const Peer &peer,
unsigned int count,
2042 std::vector<const CBlockIndex *> &vBlocks,
NodeId &nodeStaller) {
2047 vBlocks.reserve(vBlocks.size() +
count);
2048 CNodeState *state = State(peer.m_id);
2049 assert(state !=
nullptr);
2052 ProcessBlockAvailability(peer.m_id);
2054 if (state->pindexBestKnownBlock ==
nullptr ||
2055 state->pindexBestKnownBlock->nChainWork <
2057 state->pindexBestKnownBlock->nChainWork <
2067 const CBlockIndex *snap_base{m_chainman.GetSnapshotBaseBlock()};
2068 if (snap_base && state->pindexBestKnownBlock->GetAncestor(
2069 snap_base->nHeight) != snap_base) {
2071 "Not downloading blocks from peer=%d, which doesn't have the "
2072 "snapshot block in its best chain.\n",
2081 if (state->pindexLastCommonBlock ==
nullptr ||
2083 state->pindexLastCommonBlock->nHeight < snap_base->nHeight)) {
2084 state->pindexLastCommonBlock =
2086 .
ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight,
2093 state->pindexLastCommonBlock, state->pindexBestKnownBlock);
2094 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) {
2098 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
2106 FindNextBlocks(vBlocks, peer, state, pindexWalk,
count, nWindowEnd,
2110void PeerManagerImpl::TryDownloadingHistoricalBlocks(
2111 const Peer &peer,
unsigned int count,
2112 std::vector<const CBlockIndex *> &vBlocks,
const CBlockIndex *from_tip,
2117 if (vBlocks.size() >=
count) {
2121 vBlocks.reserve(
count);
2122 CNodeState *state =
Assert(State(peer.m_id));
2124 if (state->pindexBestKnownBlock ==
nullptr ||
2125 state->pindexBestKnownBlock->GetAncestor(target_block->
nHeight) !=
2140 FindNextBlocks(vBlocks, peer, state, from_tip,
count,
2145void PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex *> &vBlocks,
2146 const Peer &peer, CNodeState *state,
2148 unsigned int count,
int nWindowEnd,
2149 const CChain *activeChain,
2151 std::vector<const CBlockIndex *> vToFetch;
2153 std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
2155 while (pindexWalk->
nHeight < nMaxHeight) {
2160 int nToFetch = std::min(nMaxHeight - pindexWalk->
nHeight,
2161 std::max<int>(
count - vBlocks.size(), 128));
2162 vToFetch.resize(nToFetch);
2163 pindexWalk = state->pindexBestKnownBlock->
GetAncestor(
2164 pindexWalk->
nHeight + nToFetch);
2165 vToFetch[nToFetch - 1] = pindexWalk;
2166 for (
unsigned int i = nToFetch - 1; i > 0; i--) {
2167 vToFetch[i - 1] = vToFetch[i]->
pprev;
2180 if (pindex->nStatus.hasData() ||
2181 (activeChain && activeChain->
Contains(pindex))) {
2183 state->pindexLastCommonBlock = pindex;
2185 }
else if (!IsBlockRequested(pindex->
GetBlockHash())) {
2187 if (pindex->
nHeight > nWindowEnd) {
2189 if (vBlocks.size() == 0 && waitingfor != peer.m_id) {
2193 *nodeStaller = waitingfor;
2198 vBlocks.push_back(pindex);
2199 if (vBlocks.size() ==
count) {
2202 }
else if (waitingfor == -1) {
2214template <
class InvId>
2218 return !
node.HasPermission(
2231template <
class InvId>
2232static std::chrono::microseconds
2236 std::chrono::microseconds current_time,
bool preferred) {
2237 auto delay = std::chrono::microseconds{0};
2249 return current_time + delay;
2252void PeerManagerImpl::PushNodeVersion(
const Config &config,
CNode &pnode,
2254 uint64_t my_services{peer.m_our_services};
2255 const int64_t nTime{
count_seconds(GetTime<std::chrono::seconds>())};
2257 const int nNodeStartingHeight{m_best_height};
2268 const bool tx_relay{!RejectIncomingTxs(pnode)};
2277 nNodeStartingHeight, tx_relay, extraEntropy);
2281 "send version message: version %d, blocks=%d, them=%s, "
2282 "txrelay=%d, peer=%d\n",
2287 "send version message: version %d, blocks=%d, "
2288 "txrelay=%d, peer=%d\n",
2293void PeerManagerImpl::AddTxAnnouncement(
2295 std::chrono::microseconds current_time) {
2303 const bool preferred = isPreferredDownloadPeer(
node);
2305 current_time, preferred);
2307 m_txrequest.ReceivedInv(
node.GetId(), txid, preferred, reqtime);
2310void PeerManagerImpl::AddProofAnnouncement(
2312 std::chrono::microseconds current_time,
bool preferred) {
2323 m_proofrequest.ReceivedInv(
node.GetId(), proofid, preferred, reqtime);
2326void PeerManagerImpl::UpdateLastBlockAnnounceTime(
NodeId node,
2327 int64_t time_in_seconds) {
2329 CNodeState *state = State(
node);
2331 state->m_last_block_announcement = time_in_seconds;
2335void PeerManagerImpl::InitializeNode(
const Config &config,
CNode &
node,
2340 m_node_states.emplace_hint(m_node_states.end(),
2341 std::piecewise_construct,
2342 std::forward_as_tuple(nodeid),
2343 std::forward_as_tuple(
node.IsInboundConn()));
2344 assert(m_txrequest.Count(nodeid) == 0);
2352 PeerRef peer = std::make_shared<Peer>(nodeid, our_services, !!m_avalanche);
2355 m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
2357 if (!
node.IsInboundConn()) {
2358 PushNodeVersion(config,
node, *peer);
2362void PeerManagerImpl::ReattemptInitialBroadcast(
CScheduler &scheduler) {
2365 for (
const TxId &txid : unbroadcast_txids) {
2367 if (m_mempool.
exists(txid)) {
2368 RelayTransaction(txid);
2379 auto unbroadcasted_proofids =
2383 auto it = unbroadcasted_proofids.begin();
2384 while (it != unbroadcasted_proofids.end()) {
2387 if (!pm.isBoundToPeer(*it)) {
2388 pm.removeUnbroadcastProof(*it);
2389 it = unbroadcasted_proofids.erase(it);
2396 return unbroadcasted_proofids;
2400 for (
const auto &proofid : unbroadcasted_proofids) {
2401 RelayProof(proofid);
2408 const auto reattemptBroadcastInterval =
2410 scheduler.
scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2411 reattemptBroadcastInterval);
2414void PeerManagerImpl::UpdateAvalancheStatistics()
const {
2420void PeerManagerImpl::AvalanchePeriodicNetworking(
CScheduler &scheduler)
const {
2421 const auto now = GetTime<std::chrono::seconds>();
2422 std::vector<NodeId> avanode_ids;
2423 bool fQuorumEstablished;
2424 bool fShouldRequestMoreNodes;
2434 fShouldRequestMoreNodes =
2442 avanode_ids.push_back(pnode->GetId());
2445 PeerRef peer = GetPeerRef(pnode->
GetId());
2446 if (peer ==
nullptr) {
2450 if (peer->m_proof_relay &&
2451 now > (peer->m_proof_relay->lastSharedProofsUpdate.load() +
2453 peer->m_proof_relay->sharedProofs = {};
2457 if (avanode_ids.empty()) {
2465 for (
NodeId avanodeId : avanode_ids) {
2466 const bool sentGetavaaddr =
2469 MakeAndPushMessage(*pavanode, NetMsgType::GETAVAADDR);
2470 PeerRef peer = GetPeerRef(avanodeId);
2471 WITH_LOCK(peer->m_addr_token_bucket_mutex,
2472 peer->m_addr_token_bucket +=
2473 m_opts.max_addr_to_send);
2481 if (sentGetavaaddr && fQuorumEstablished && !fShouldRequestMoreNodes) {
2496 avanode_ids.resize(std::min<size_t>(avanode_ids.size(), 3));
2499 for (
NodeId nodeid : avanode_ids) {
2502 PeerRef peer = GetPeerRef(nodeid);
2503 if (peer->m_proof_relay) {
2505 peer->m_proof_relay->compactproofs_requested =
true;
2515 const auto avalanchePeriodicNetworkingInterval =
2517 scheduler.
scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2518 avalanchePeriodicNetworkingInterval);
2521void PeerManagerImpl::FinalizeNode(
const Config &config,
const CNode &
node) {
2531 PeerRef peer = RemovePeer(nodeid);
2534 m_peer_map.erase(nodeid);
2536 CNodeState *state = State(nodeid);
2537 assert(state !=
nullptr);
2539 if (state->fSyncStarted) {
2543 for (
const QueuedBlock &entry : state->vBlocksInFlight) {
2545 mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash());
2546 while (range.first != range.second) {
2547 auto [node_id, list_it] = range.first->second;
2548 if (node_id != nodeid) {
2551 range.first = mapBlocksInFlight.erase(range.first);
2558 m_txrequest.DisconnectedPeer(nodeid);
2559 m_num_preferred_download_peers -= state->fPreferredDownload;
2560 m_peers_downloading_from -= (!state->vBlocksInFlight.empty());
2561 assert(m_peers_downloading_from >= 0);
2562 m_outbound_peers_with_protect_from_disconnect -=
2563 state->m_chain_sync.m_protect;
2564 assert(m_outbound_peers_with_protect_from_disconnect >= 0);
2566 m_node_states.erase(nodeid);
2568 if (m_node_states.empty()) {
2570 assert(mapBlocksInFlight.empty());
2571 assert(m_num_preferred_download_peers == 0);
2572 assert(m_peers_downloading_from == 0);
2573 assert(m_outbound_peers_with_protect_from_disconnect == 0);
2574 assert(m_txrequest.Size() == 0);
2576 return orphanage.Size();
2581 if (
node.fSuccessfullyConnected && !
node.IsBlockOnlyConn() &&
2582 !
node.IsInboundConn()) {
2589 LOCK(m_headers_presync_mutex);
2590 m_headers_presync_stats.erase(nodeid);
2593 WITH_LOCK(cs_proofrequest, m_proofrequest.DisconnectedPeer(nodeid));
2598PeerRef PeerManagerImpl::GetPeerRef(
NodeId id)
const {
2600 auto it = m_peer_map.find(
id);
2601 return it != m_peer_map.end() ? it->second :
nullptr;
2604PeerRef PeerManagerImpl::RemovePeer(
NodeId id) {
2607 auto it = m_peer_map.find(
id);
2608 if (it != m_peer_map.end()) {
2609 ret = std::move(it->second);
2610 m_peer_map.erase(it);
2615bool PeerManagerImpl::GetNodeStateStats(
NodeId nodeid,
2619 const CNodeState *state = State(nodeid);
2620 if (state ==
nullptr) {
2624 ? state->pindexBestKnownBlock->nHeight
2627 ? state->pindexLastCommonBlock->nHeight
2629 for (
const QueuedBlock &queue : state->vBlocksInFlight) {
2636 PeerRef peer = GetPeerRef(nodeid);
2637 if (peer ==
nullptr) {
2649 auto ping_wait{0us};
2650 if ((0 != peer->m_ping_nonce_sent) &&
2651 (0 != peer->m_ping_start.load().count())) {
2653 GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
2656 if (
auto tx_relay = peer->GetTxRelay()) {
2658 return tx_relay->m_relay_txs);
2670 LOCK(peer->m_headers_sync_mutex);
2671 if (peer->m_headers_sync) {
2679void PeerManagerImpl::AddToCompactExtraTransactions(
const CTransactionRef &tx) {
2680 if (m_opts.max_extra_txs <= 0) {
2684 if (!vExtraTxnForCompact.size()) {
2685 vExtraTxnForCompact.resize(m_opts.max_extra_txs);
2688 vExtraTxnForCompact[vExtraTxnForCompactIt] = tx;
2689 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs;
2692void PeerManagerImpl::Misbehaving(Peer &peer,
const std::string &message) {
2693 LOCK(peer.m_misbehavior_mutex);
2695 const std::string message_prefixed =
2696 message.empty() ?
"" : (
": " + message);
2697 peer.m_should_discourage =
true;
2702void PeerManagerImpl::MaybePunishNodeForBlock(
NodeId nodeid,
2704 bool via_compact_block,
2705 const std::string &message) {
2706 PeerRef peer{GetPeerRef(nodeid)};
2717 if (!via_compact_block) {
2719 Misbehaving(*peer, message);
2726 CNodeState *node_state = State(nodeid);
2727 if (node_state ==
nullptr) {
2734 if (!via_compact_block && !node_state->m_is_inbound) {
2736 Misbehaving(*peer, message);
2746 Misbehaving(*peer, message);
2752 Misbehaving(*peer, message);
2758 if (message !=
"") {
2763void PeerManagerImpl::MaybePunishNodeForTx(
NodeId nodeid,
2765 const std::string &message) {
2766 PeerRef peer{GetPeerRef(nodeid)};
2773 Misbehaving(*peer, message);
2791 if (message !=
"") {
2796bool PeerManagerImpl::BlockRequestAllowed(
const CBlockIndex *pindex) {
2802 (m_chainman.m_best_header !=
nullptr) &&
2803 (m_chainman.m_best_header->GetBlockTime() - pindex->
GetBlockTime() <
2806 *m_chainman.m_best_header, *pindex, *m_chainman.m_best_header,
2810std::optional<std::string>
2811PeerManagerImpl::FetchBlock(
const Config &config,
NodeId peer_id,
2814 return "Loading blocks ...";
2820 CNodeState *state = State(peer_id);
2821 if (state ==
nullptr) {
2822 return "Peer does not exist";
2826 RemoveBlockRequest(block_index.
GetBlockHash(), std::nullopt);
2831 if (!BlockRequested(config, peer_id, block_index)) {
2832 return "Already requested from this peer";
2841 this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs);
2844 return "Node not fully connected";
2849 return std::nullopt;
2852std::unique_ptr<PeerManager>
2856 return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman,
2865 : m_rng{opts.deterministic_rng},
2867 m_chainparams(chainman.GetParams()), m_connman(connman),
2868 m_addrman(addrman), m_banman(banman), m_chainman(chainman),
2869 m_mempool(pool), m_avalanche(
avalanche), m_opts{opts} {}
2871void PeerManagerImpl::StartScheduledTasks(
CScheduler &scheduler) {
2878 "peer eviction timer should be less than stale tip check timer");
2881 this->CheckForStaleTipAndEvictPeers();
2887 const auto reattemptBroadcastInterval =
2889 scheduler.
scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2890 reattemptBroadcastInterval);
2895 UpdateAvalancheStatistics();
2901 const auto avalanchePeriodicNetworkingInterval =
2903 scheduler.
scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2904 avalanchePeriodicNetworkingInterval);
2913void PeerManagerImpl::BlockConnected(
2914 ChainstateRole role,
const std::shared_ptr<const CBlock> &pblock,
2918 m_last_tip_update = GetTime<std::chrono::seconds>();
2922 auto stalling_timeout = m_block_stalling_timeout.load();
2925 const auto new_timeout =
2926 std::max(std::chrono::duration_cast<std::chrono::seconds>(
2927 stalling_timeout * 0.85),
2929 if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout,
2949 LOCK(m_recent_confirmed_transactions_mutex);
2951 m_recent_confirmed_transactions.insert(ptx->GetId());
2956 for (
const auto &ptx : pblock->vtx) {
2957 m_txrequest.ForgetInvId(ptx->GetId());
2962void PeerManagerImpl::BlockDisconnected(
2963 const std::shared_ptr<const CBlock> &block,
const CBlockIndex *pindex) {
2972 LOCK(m_recent_confirmed_transactions_mutex);
2973 m_recent_confirmed_transactions.reset();
2980void PeerManagerImpl::NewPoWValidBlock(
2981 const CBlockIndex *pindex,
const std::shared_ptr<const CBlock> &pblock) {
2982 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock =
2983 std::make_shared<const CBlockHeaderAndShortTxIDs>(
2988 if (pindex->
nHeight <= m_highest_fast_announce) {
2991 m_highest_fast_announce = pindex->
nHeight;
2994 const std::shared_future<CSerializedNetMsg> lazy_ser{
2995 std::async(std::launch::deferred, [&] {
3000 auto most_recent_block_txs =
3001 std::make_unique<std::map<TxId, CTransactionRef>>();
3002 for (
const auto &tx : pblock->vtx) {
3003 most_recent_block_txs->emplace(tx->GetId(), tx);
3006 LOCK(m_most_recent_block_mutex);
3007 m_most_recent_block_hash = hashBlock;
3008 m_most_recent_block = pblock;
3009 m_most_recent_compact_block = pcmpctblock;
3010 m_most_recent_block_txs = std::move(most_recent_block_txs);
3014 [
this, pindex, &lazy_ser, &hashBlock](
CNode *pnode)
3022 ProcessBlockAvailability(pnode->
GetId());
3023 CNodeState &state = *State(pnode->
GetId());
3027 if (state.m_requested_hb_cmpctblocks &&
3028 !PeerHasHeader(&state, pindex) &&
3029 PeerHasHeader(&state, pindex->
pprev)) {
3031 "%s sending header-and-ids %s to peer=%d\n",
3032 "PeerManager::NewPoWValidBlock",
3033 hashBlock.ToString(), pnode->
GetId());
3036 PushMessage(*pnode, ser_cmpctblock.Copy());
3037 state.pindexBestHeaderSent = pindex;
3046void PeerManagerImpl::UpdatedBlockTip(
const CBlockIndex *pindexNew,
3048 bool fInitialDownload) {
3049 SetBestHeight(pindexNew->
nHeight);
3053 if (fInitialDownload) {
3058 std::vector<BlockHash> vHashes;
3060 while (pindexToAnnounce != pindexFork) {
3062 pindexToAnnounce = pindexToAnnounce->
pprev;
3072 for (
auto &it : m_peer_map) {
3073 Peer &peer = *it.second;
3074 LOCK(peer.m_block_inv_mutex);
3076 peer.m_blocks_for_headers_relay.push_back(hash);
3088void PeerManagerImpl::BlockChecked(
const CBlock &block,
3093 std::map<BlockHash, std::pair<NodeId, bool>>::iterator it =
3094 mapBlockSource.find(hash);
3098 if (state.
IsInvalid() && it != mapBlockSource.end() &&
3099 State(it->second.first)) {
3100 MaybePunishNodeForBlock(it->second.first, state,
3101 !it->second.second);
3110 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
3111 if (it != mapBlockSource.end()) {
3112 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
3116 if (it != mapBlockSource.end()) {
3117 mapBlockSource.erase(it);
3126bool PeerManagerImpl::AlreadyHaveTx(
const TxId &txid,
3127 bool include_reconsiderable) {
3129 hashRecentRejectsChainTip) {
3134 hashRecentRejectsChainTip =
3136 m_recent_rejects.reset();
3137 m_recent_rejects_package_reconsiderable.reset();
3141 return orphanage.HaveTx(txid);
3147 return conflicting.HaveTx(txid);
3152 if (include_reconsiderable &&
3153 m_recent_rejects_package_reconsiderable.contains(txid)) {
3158 LOCK(m_recent_confirmed_transactions_mutex);
3159 if (m_recent_confirmed_transactions.contains(txid)) {
3164 return m_recent_rejects.contains(txid) || m_mempool.
exists(txid);
3167bool PeerManagerImpl::AlreadyHaveBlock(
const BlockHash &block_hash) {
3172 if (!
Assume(m_avalanche)) {
3177 if (localProof && localProof->getId() == proofid) {
3186void PeerManagerImpl::SendPings() {
3188 for (
auto &it : m_peer_map) {
3189 it.second->m_ping_queued =
true;
3193void PeerManagerImpl::RelayTransaction(
const TxId &txid) {
3195 for (
auto &it : m_peer_map) {
3196 Peer &peer = *it.second;
3197 auto tx_relay = peer.GetTxRelay();
3201 LOCK(tx_relay->m_tx_inventory_mutex);
3207 if (tx_relay->m_next_inv_send_time == 0s) {
3211 if (!tx_relay->m_tx_inventory_known_filter.contains(txid) ||
3212 tx_relay->m_avalanche_stalled_txids.count(txid) > 0) {
3213 tx_relay->m_tx_inventory_to_send.insert(txid);
3220 for (
auto &it : m_peer_map) {
3221 Peer &peer = *it.second;
3223 if (!peer.m_proof_relay) {
3226 LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
3227 if (!peer.m_proof_relay->m_proof_inventory_known_filter.contains(
3229 peer.m_proof_relay->m_proof_inventory_to_send.insert(proofid);
3234void PeerManagerImpl::RelayAddress(
NodeId originator,
const CAddress &addr,
3250 const auto current_time{GetTime<std::chrono::seconds>()};
3253 const uint64_t time_addr{
3254 (
static_cast<uint64_t
>(
count_seconds(current_time)) + hash_addr) /
3264 unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
3265 std::array<std::pair<uint64_t, Peer *>, 2> best{
3266 {{0,
nullptr}, {0,
nullptr}}};
3267 assert(nRelayNodes <= best.size());
3271 for (
auto &[
id, peer] : m_peer_map) {
3272 if (peer->m_addr_relay_enabled &&
id != originator &&
3273 IsAddrCompatible(*peer, addr)) {
3275 for (
unsigned int i = 0; i < nRelayNodes; i++) {
3276 if (hashKey > best[i].first) {
3277 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1,
3278 best.begin() + i + 1);
3279 best[i] = std::make_pair(hashKey, peer.get());
3286 for (
unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
3287 PushAddress(*best[i].second, addr);
3291void PeerManagerImpl::ProcessGetBlockData(
const Config &config,
CNode &pfrom,
3292 Peer &peer,
const CInv &inv) {
3295 std::shared_ptr<const CBlock> a_recent_block;
3296 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
3298 LOCK(m_most_recent_block_mutex);
3299 a_recent_block = m_most_recent_block;
3300 a_recent_compact_block = m_most_recent_compact_block;
3303 bool need_activate_chain =
false;
3317 need_activate_chain =
true;
3321 if (need_activate_chain) {
3324 state, a_recent_block, m_avalanche)) {
3332 bool can_direct_fetch{
false};
3340 if (!BlockRequestAllowed(pindex)) {
3342 "%s: ignoring request from peer=%i for old "
3343 "block that isn't in the main chain\n",
3344 __func__, pfrom.
GetId());
3350 (((m_chainman.m_best_header !=
nullptr) &&
3351 (m_chainman.m_best_header->GetBlockTime() -
3359 "historical block serving limit reached, disconnect peer=%d\n",
3372 (tip->nHeight - pindex->
nHeight >
3375 "Ignore block request below NODE_NETWORK_LIMITED "
3376 "threshold, disconnect peer=%d\n",
3386 if (!pindex->nStatus.hasData()) {
3389 can_direct_fetch = CanDirectFetch();
3393 std::shared_ptr<const CBlock> pblock;
3394 auto handle_block_read_error = [&]() {
3396 return m_chainman.
m_blockman.IsBlockPruned(*pindex))) {
3398 "Block was pruned before it could be read, disconnect "
3402 LogError(
"Cannot load block from disk, disconnect peer=%d\n",
3408 if (a_recent_block && a_recent_block->GetHash() == pindex->
GetBlockHash()) {
3409 pblock = a_recent_block;
3413 std::vector<uint8_t> block_data;
3415 handle_block_read_error();
3422 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
3424 handle_block_read_error();
3427 pblock = pblockRead;
3433 bool sendMerkleBlock =
false;
3435 if (
auto tx_relay = peer.GetTxRelay()) {
3436 LOCK(tx_relay->m_bloom_filter_mutex);
3437 if (tx_relay->m_bloom_filter) {
3438 sendMerkleBlock =
true;
3443 if (sendMerkleBlock) {
3454 typedef std::pair<size_t, uint256> PairType;
3457 *pblock->vtx[pair.first]);
3467 if (can_direct_fetch &&
3469 if (a_recent_compact_block &&
3470 a_recent_compact_block->header.GetHash() ==
3473 *a_recent_compact_block);
3487 LOCK(peer.m_block_inv_mutex);
3490 if (hash == peer.m_continuation_block) {
3494 std::vector<CInv> vInv;
3497 peer.m_continuation_block =
BlockHash();
3503PeerManagerImpl::FindTxForGetData(
const Peer &peer,
const TxId &txid,
3504 const std::chrono::seconds mempool_req,
3505 const std::chrono::seconds now) {
3506 auto txinfo = m_mempool.
info(txid);
3511 if ((mempool_req.count() && txinfo.m_time <= mempool_req) ||
3513 return std::move(txinfo.tx);
3522 Assume(peer.GetTxRelay())->m_recently_announced_invs.contains(txid);
3523 if (recent && txinfo.tx) {
3524 return std::move(txinfo.tx);
3529 LOCK(m_most_recent_block_mutex);
3530 if (m_most_recent_block_txs !=
nullptr) {
3531 auto it = m_most_recent_block_txs->find(txid);
3532 if (it != m_most_recent_block_txs->end()) {
3545PeerManagerImpl::FindProofForGetData(
const Peer &peer,
3547 const std::chrono::seconds now) {
3550 bool send_unconditionally =
3576 if (send_unconditionally) {
3581 if (peer.m_proof_relay->m_recently_announced_proofs.contains(proofid)) {
3588void PeerManagerImpl::ProcessGetData(
3590 const std::atomic<bool> &interruptMsgProc) {
3593 auto tx_relay = peer.GetTxRelay();
3595 std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
3596 std::vector<CInv> vNotFound;
3598 const auto now{GetTime<std::chrono::seconds>()};
3600 const auto mempool_req = tx_relay !=
nullptr
3601 ? tx_relay->m_last_mempool_req.load()
3602 : std::chrono::seconds::min();
3607 while (it != peer.m_getdata_requests.end() &&
3608 (it->IsMsgProof() || it->IsMsgTx())) {
3609 if (interruptMsgProc) {
3618 const CInv &inv = *it++;
3622 vNotFound.push_back(inv);
3626 auto proof = FindProofForGetData(peer, proofid, now);
3633 vNotFound.push_back(inv);
3640 if (tx_relay ==
nullptr) {
3654 std::vector<TxId> parent_ids_to_add;
3657 auto tx_iter = m_mempool.
GetIter(tx->GetId());
3659 auto &pentry = *tx_iter;
3661 (*pentry)->GetMemPoolParentsConst();
3662 parent_ids_to_add.reserve(parents.size());
3663 for (
const auto &parent : parents) {
3664 if (parent.get()->GetTime() >
3666 parent_ids_to_add.push_back(
3667 parent.get()->GetTx().GetId());
3672 for (
const TxId &parent_txid : parent_ids_to_add) {
3675 if (
WITH_LOCK(tx_relay->m_tx_inventory_mutex,
3676 return !tx_relay->m_tx_inventory_known_filter
3677 .contains(parent_txid))) {
3678 tx_relay->m_recently_announced_invs.insert(parent_txid);
3682 vNotFound.push_back(inv);
3694 if (it != peer.m_getdata_requests.end() && !pfrom.
fPauseSend) {
3695 const CInv &inv = *it++;
3697 ProcessGetBlockData(config, pfrom, peer, inv);
3703 peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
3705 if (!vNotFound.empty()) {
3722void PeerManagerImpl::SendBlockTransactions(
3726 for (
size_t i = 0; i < req.
indices.size(); i++) {
3728 Misbehaving(peer,
"getblocktxn with out-of-bounds tx indices");
3737bool PeerManagerImpl::CheckHeadersPoW(
const std::vector<CBlockHeader> &headers,
3742 Misbehaving(peer,
"header with invalid proof of work");
3747 if (!CheckHeadersAreContinuous(headers)) {
3748 Misbehaving(peer,
"non-continuous headers sequence");
3761 near_chaintip_work =
3774void PeerManagerImpl::HandleUnconnectingHeaders(
3775 CNode &pfrom, Peer &peer,
const std::vector<CBlockHeader> &headers) {
3779 if (MaybeSendGetHeaders(pfrom,
GetLocator(best_header), peer)) {
3782 "received header %s: missing prev block %s, sending getheaders "
3783 "(%d) to end (peer=%d)\n",
3785 headers[0].hashPrevBlock.ToString(), best_header->nHeight,
3793 UpdateBlockAvailability(pfrom.
GetId(), headers.back().GetHash()));
3796bool PeerManagerImpl::CheckHeadersAreContinuous(
3797 const std::vector<CBlockHeader> &headers)
const {
3800 if (!hashLastBlock.
IsNull() && header.hashPrevBlock != hashLastBlock) {
3803 hashLastBlock = header.GetHash();
3808bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(
3809 Peer &peer,
CNode &pfrom, std::vector<CBlockHeader> &headers) {
3810 if (peer.m_headers_sync) {
3811 auto result = peer.m_headers_sync->ProcessNextHeaders(
3815 if (result.success) {
3816 peer.m_last_getheaders_timestamp = {};
3818 if (result.request_more) {
3819 auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
3822 Assume(!locator.vHave.empty());
3826 if (!locator.vHave.empty()) {
3829 bool sent_getheaders =
3830 MaybeSendGetHeaders(pfrom, locator, peer);
3833 locator.vHave.front().ToString(), pfrom.
GetId());
3838 peer.m_headers_sync.reset(
nullptr);
3843 LOCK(m_headers_presync_mutex);
3844 m_headers_presync_stats.erase(pfrom.
GetId());
3847 HeadersPresyncStats stats;
3848 stats.first = peer.m_headers_sync->GetPresyncWork();
3849 if (peer.m_headers_sync->GetState() ==
3851 stats.second = {peer.m_headers_sync->GetPresyncHeight(),
3852 peer.m_headers_sync->GetPresyncTime()};
3856 LOCK(m_headers_presync_mutex);
3857 m_headers_presync_stats[pfrom.
GetId()] = stats;
3859 m_headers_presync_stats.find(m_headers_presync_bestpeer);
3860 bool best_updated =
false;
3861 if (best_it == m_headers_presync_stats.end()) {
3866 const HeadersPresyncStats *stat_best{
nullptr};
3867 for (
const auto &[_peer, _stat] : m_headers_presync_stats) {
3868 if (!stat_best || _stat > *stat_best) {
3873 m_headers_presync_bestpeer = peer_best;
3874 best_updated = (peer_best == pfrom.
GetId());
3875 }
else if (best_it->first == pfrom.
GetId() ||
3876 stats > best_it->second) {
3879 m_headers_presync_bestpeer = pfrom.
GetId();
3880 best_updated =
true;
3882 if (best_updated && stats.second.has_value()) {
3885 m_headers_presync_should_signal =
true;
3889 if (result.success) {
3892 headers.swap(result.pow_validated_headers);
3895 return result.success;
3903bool PeerManagerImpl::TryLowWorkHeadersSync(
3905 std::vector<CBlockHeader> &headers) {
3912 arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
3916 if (total_work < minimum_chain_work) {
3930 LOCK(peer.m_headers_sync_mutex);
3931 peer.m_headers_sync.reset(
3933 chain_start_header, minimum_chain_work));
3938 (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3941 "Ignoring low-work chain (height=%u) from peer=%d\n",
3942 chain_start_header->
nHeight + headers.size(),
3954bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(
const CBlockIndex *header) {
3955 return header !=
nullptr &&
3956 ((m_chainman.m_best_header !=
nullptr &&
3958 m_chainman.m_best_header->GetAncestor(header->
nHeight)) ||
3962bool PeerManagerImpl::MaybeSendGetHeaders(
CNode &pfrom,
3969 if (current_time - peer.m_last_getheaders_timestamp >
3972 peer.m_last_getheaders_timestamp = current_time;
3984void PeerManagerImpl::HeadersDirectFetchBlocks(
const Config &config,
3988 CNodeState *nodestate = State(pfrom.
GetId());
3992 std::vector<const CBlockIndex *> vToFetch;
3998 if (!pindexWalk->nStatus.hasData() &&
4001 vToFetch.push_back(pindexWalk);
4003 pindexWalk = pindexWalk->
pprev;
4014 std::vector<CInv> vGetData;
4017 if (nodestate->vBlocksInFlight.size() >=
4023 BlockRequested(config, pfrom.
GetId(), *pindex);
4027 if (vGetData.size() > 1) {
4029 "Downloading blocks toward %s (%d) via headers "
4034 if (vGetData.size() > 0) {
4035 if (!m_opts.ignore_incoming_txs &&
4036 nodestate->m_provides_cmpctblocks && vGetData.size() == 1 &&
4037 mapBlocksInFlight.size() == 1 &&
4054void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(
4056 bool received_new_header,
bool may_have_more_headers) {
4059 CNodeState *nodestate = State(pfrom.
GetId());
4067 if (received_new_header &&
4069 nodestate->m_last_block_announcement =
GetTime();
4077 if (nodestate->pindexBestKnownBlock &&
4078 nodestate->pindexBestKnownBlock->nChainWork <
4089 LogPrintf(
"Disconnecting outbound peer %d -- headers "
4090 "chain has insufficient work\n",
4104 nodestate->pindexBestKnownBlock !=
nullptr) {
4105 if (m_outbound_peers_with_protect_from_disconnect <
4107 nodestate->pindexBestKnownBlock->nChainWork >=
4109 !nodestate->m_chain_sync.m_protect) {
4112 nodestate->m_chain_sync.m_protect =
true;
4113 ++m_outbound_peers_with_protect_from_disconnect;
4118void PeerManagerImpl::ProcessHeadersMessage(
const Config &config,
CNode &pfrom,
4120 std::vector<CBlockHeader> &&headers,
4121 bool via_compact_block) {
4122 size_t nCount = headers.size();
4130 LOCK(peer.m_headers_sync_mutex);
4131 if (peer.m_headers_sync) {
4132 peer.m_headers_sync.reset(
nullptr);
4133 LOCK(m_headers_presync_mutex);
4134 m_headers_presync_stats.erase(pfrom.
GetId());
4139 peer.m_last_getheaders_timestamp = {};
4147 if (!CheckHeadersPoW(headers, m_chainparams.
GetConsensus(), peer)) {
4162 bool already_validated_work =
false;
4165 bool have_headers_sync =
false;
4167 LOCK(peer.m_headers_sync_mutex);
4169 already_validated_work =
4170 IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
4182 if (headers.empty()) {
4186 have_headers_sync = !!peer.m_headers_sync;
4192 headers[0].hashPrevBlock))};
4193 bool headers_connect_blockindex{chain_start_header !=
nullptr};
4195 if (!headers_connect_blockindex) {
4199 HandleUnconnectingHeaders(pfrom, peer, headers);
4207 peer.m_last_getheaders_timestamp = {};
4216 last_received_header =
4218 if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
4219 already_validated_work =
true;
4227 already_validated_work =
true;
4233 if (!already_validated_work &&
4234 TryLowWorkHeadersSync(peer, pfrom, chain_start_header, headers)) {
4246 bool received_new_header{last_received_header ==
nullptr};
4251 state, &pindexLast)) {
4253 MaybePunishNodeForBlock(pfrom.
GetId(), state, via_compact_block,
4254 "invalid header received");
4260 LogError(
"headers message processed but no pindexLast\n");
4269 if (MaybeSendGetHeaders(pfrom,
GetLocator(pindexLast), peer)) {
4272 "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
4273 pindexLast->
nHeight, pfrom.
GetId(), peer.m_starting_height);
4277 UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast,
4278 received_new_header,
4282 HeadersDirectFetchBlocks(config, pfrom, *pindexLast);
4285void PeerManagerImpl::ProcessInvalidTx(
NodeId nodeid,
4288 bool maybe_add_extra_compact_tx) {
4293 const TxId &txid = ptx->GetId();
4313 m_recent_rejects_package_reconsiderable.insert(txid);
4315 m_recent_rejects.insert(txid);
4317 m_txrequest.ForgetInvId(txid);
4320 AddToCompactExtraTransactions(ptx);
4323 MaybePunishNodeForTx(nodeid, state);
4329 return orphanage.EraseTx(txid);
4343 m_txrequest.ForgetInvId(tx->GetId());
4349 orphanage.
EraseTx(tx->GetId());
4354 "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4355 nodeid, tx->GetId().ToString(), m_mempool.
size(),
4358 RelayTransaction(tx->GetId());
4361void PeerManagerImpl::ProcessPackageResult(
4362 const PackageToValidate &package_to_validate,
4368 const auto &
package = package_to_validate.m_txns;
4369 const auto &senders = package_to_validate.m_senders;
4372 m_recent_rejects_package_reconsiderable.insert(
GetPackageHash(package));
4376 if (!
Assume(package.size() == 2)) {
4382 auto package_iter = package.rbegin();
4383 auto senders_iter = senders.rbegin();
4384 while (package_iter != package.rend()) {
4385 const auto &tx = *package_iter;
4386 const NodeId nodeid = *senders_iter;
4387 const auto it_result{package_result.
m_tx_results.find(tx->GetId())};
4391 const auto &tx_result = it_result->second;
4392 switch (tx_result.m_result_type) {
4394 ProcessValidTx(nodeid, tx);
4404 ProcessInvalidTx(nodeid, tx, tx_result.m_state,
4421std::optional<PeerManagerImpl::PackageToValidate>
4427 const auto &parent_txid{ptx->GetId()};
4429 Assume(m_recent_rejects_package_reconsiderable.contains(parent_txid));
4435 const auto cpfp_candidates_same_peer{
4441 for (
const auto &child : cpfp_candidates_same_peer) {
4442 Package maybe_cpfp_package{ptx, child};
4443 if (!m_recent_rejects_package_reconsiderable.contains(
4445 return PeerManagerImpl::PackageToValidate{ptx, child, nodeid,
4459 const auto cpfp_candidates_different_peer{
4469 std::vector<size_t> tx_indices(cpfp_candidates_different_peer.size());
4470 std::iota(tx_indices.begin(), tx_indices.end(), 0);
4471 Shuffle(tx_indices.begin(), tx_indices.end(), m_rng);
4473 for (
const auto index : tx_indices) {
4476 const auto [child_tx, child_sender] =
4477 cpfp_candidates_different_peer.at(index);
4478 Package maybe_cpfp_package{ptx, child_tx};
4479 if (!m_recent_rejects_package_reconsiderable.contains(
4481 return PeerManagerImpl::PackageToValidate{ptx, child_tx, nodeid,
4485 return std::nullopt;
4488bool PeerManagerImpl::ProcessOrphanTx(
const Config &config, Peer &peer) {
4494 return orphanage.GetTxToReconsider(peer.m_id);
4499 const TxId &orphanTxId = porphanTx->GetId();
4504 ProcessValidTx(peer.m_id, porphanTx);
4510 " invalid orphan tx %s from peer=%d. %s\n",
4517 ProcessInvalidTx(peer.m_id, porphanTx, state,
4528bool PeerManagerImpl::PrepareBlockFilterRequest(
4530 const BlockHash &stop_hash, uint32_t max_height_diff,
4532 const bool supported_filter_type =
4535 if (!supported_filter_type) {
4537 "peer %d requested unsupported block filter type: %d\n",
4538 node.GetId(),
static_cast<uint8_t
>(filter_type));
4539 node.fDisconnect =
true;
4549 if (!stop_index || !BlockRequestAllowed(stop_index)) {
4552 node.fDisconnect =
true;
4557 uint32_t stop_height = stop_index->
nHeight;
4558 if (start_height > stop_height) {
4561 "peer %d sent invalid getcfilters/getcfheaders with "
4563 "start height %d and stop height %d\n",
4564 node.GetId(), start_height, stop_height);
4565 node.fDisconnect =
true;
4568 if (stop_height - start_height >= max_height_diff) {
4570 "peer %d requested too many cfilters/cfheaders: %d / %d\n",
4571 node.GetId(), stop_height - start_height + 1, max_height_diff);
4572 node.fDisconnect =
true;
4577 if (!filter_index) {
4586void PeerManagerImpl::ProcessGetCFilters(
CNode &
node, Peer &peer,
4588 uint8_t filter_type_ser;
4589 uint32_t start_height;
4592 vRecv >> filter_type_ser >> start_height >> stop_hash;
4599 if (!PrepareBlockFilterRequest(
node, peer, filter_type, start_height,
4605 std::vector<BlockFilter> filters;
4608 "Failed to find block filter in index: filter_type=%s, "
4609 "start_height=%d, stop_hash=%s\n",
4615 for (
const auto &filter : filters) {
4620void PeerManagerImpl::ProcessGetCFHeaders(
CNode &
node, Peer &peer,
4622 uint8_t filter_type_ser;
4623 uint32_t start_height;
4626 vRecv >> filter_type_ser >> start_height >> stop_hash;
4633 if (!PrepareBlockFilterRequest(
node, peer, filter_type, start_height,
4640 if (start_height > 0) {
4642 stop_index->
GetAncestor(
static_cast<int>(start_height - 1));
4645 "Failed to find block filter header in index: "
4646 "filter_type=%s, block_hash=%s\n",
4653 std::vector<uint256> filter_hashes;
4657 "Failed to find block filter hashes in index: filter_type=%s, "
4658 "start_height=%d, stop_hash=%s\n",
4665 stop_index->
GetBlockHash(), prev_header, filter_hashes);
4668void PeerManagerImpl::ProcessGetCFCheckPt(
CNode &
node, Peer &peer,
4670 uint8_t filter_type_ser;
4673 vRecv >> filter_type_ser >> stop_hash;
4680 if (!PrepareBlockFilterRequest(
4681 node, peer, filter_type, 0, stop_hash,
4682 std::numeric_limits<uint32_t>::max(),
4683 stop_index, filter_index)) {
4691 for (
int i = headers.size() - 1; i >= 0; i--) {
4697 "Failed to find block filter header in index: "
4698 "filter_type=%s, block_hash=%s\n",
4721PeerManagerImpl::GetAvalancheVoteForBlock(
const BlockHash &hash)
const {
4732 if (pindex->nStatus.isInvalid()) {
4737 if (pindex->nStatus.isOnParkedChain()) {
4745 if (pindex == pindexFork) {
4750 if (pindexFork != pindexTip) {
4755 if (!pindex->nStatus.hasData()) {
4766 const TxId &
id)
const {
4768 if (
WITH_LOCK(m_recent_confirmed_transactions_mutex,
4769 return m_recent_confirmed_transactions.contains(
id))) {
4778 if (m_recent_rejects.contains(
id)) {
4790 if (
auto iter = m_mempool.
GetIter(
id)) {
4791 mempool_tx = (**iter)->GetSharedTx();
4796 return conflicting.HaveTx(id);
4803 return orphanage.HaveTx(id);
4869 const std::shared_ptr<const CBlock> &block,
4870 bool force_processing,
4871 bool min_pow_checked) {
4872 bool new_block{
false};
4874 &new_block, m_avalanche);
4876 node.m_last_block_time = GetTime<std::chrono::seconds>();
4881 RemoveBlockRequest(block->GetHash(), std::nullopt);
4884 mapBlockSource.erase(block->GetHash());
4888void PeerManagerImpl::ProcessMessage(
4889 const Config &config,
CNode &pfrom,
const std::string &msg_type,
4890 DataStream &vRecv,
const std::chrono::microseconds time_received,
4891 const std::atomic<bool> &interruptMsgProc) {
4897 PeerRef peer = GetPeerRef(pfrom.
GetId());
4898 if (peer ==
nullptr) {
4904 "Avalanche is not initialized, ignoring %s message\n",
4919 uint64_t nNonce = 1;
4922 std::string cleanSubVer;
4923 int starting_height = -1;
4925 uint64_t nExtraEntropy = 1;
4927 vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
4940 "peer=%d does not offer the expected services "
4941 "(%08x offered, %08x expected); disconnecting\n",
4942 pfrom.
GetId(), nServices,
4952 "peer=%d does not offer the avalanche service; disconnecting\n",
4961 "peer=%d using obsolete version %i; disconnecting\n",
4962 pfrom.
GetId(), nVersion);
4967 if (!vRecv.
empty()) {
4976 if (!vRecv.
empty()) {
4977 std::string strSubVer;
4981 if (!vRecv.
empty()) {
4982 vRecv >> starting_height;
4984 if (!vRecv.
empty()) {
4987 if (!vRecv.
empty()) {
4988 vRecv >> nExtraEntropy;
4992 LogPrintf(
"connected to self at %s, disconnecting\n",
5005 PushNodeVersion(config, pfrom, *peer);
5009 const int greatest_common_version =
5021 peer->m_their_services = nServices;
5025 pfrom.cleanSubVer = cleanSubVer;
5027 peer->m_starting_height = starting_height;
5035 (fRelay || (peer->m_our_services &
NODE_BLOOM))) {
5036 auto *
const tx_relay = peer->SetTxRelay();
5038 LOCK(tx_relay->m_bloom_filter_mutex);
5040 tx_relay->m_relay_txs = fRelay;
5053 CNodeState *state = State(pfrom.
GetId());
5054 state->fPreferredDownload =
5058 m_num_preferred_download_peers += state->fPreferredDownload;
5064 bool send_getaddr{
false};
5066 send_getaddr = SetupAddressRelay(pfrom, *peer);
5077 peer->m_getaddr_sent =
true;
5081 WITH_LOCK(peer->m_addr_token_bucket_mutex,
5082 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
5103 std::string remoteAddr;
5109 "receive version message: [%s] %s: version %d, blocks=%d, "
5110 "us=%s, txrelay=%d, peer=%d%s\n",
5113 pfrom.
GetId(), remoteAddr);
5115 int64_t currentTime =
GetTime();
5116 int64_t nTimeOffset = nTime - currentTime;
5121 Misbehaving(*peer,
"Ignoring invalid timestamp in version message");
5131 "feeler connection completed peer=%d; disconnecting\n",
5140 Misbehaving(*peer,
"non-version message before version handshake");
5147 "ignoring redundant verack message from peer=%d\n",
5153 LogPrintf(
"New outbound peer connected: version: %d, blocks=%d, "
5155 pfrom.
nVersion.load(), peer->m_starting_height,
5178 AddKnownProof(*peer, localProof->getId());
5182 peer->m_proof_relay->m_recently_announced_proofs.insert(
5183 localProof->getId());
5188 if (
auto tx_relay = peer->GetTxRelay()) {
5197 return tx_relay->m_tx_inventory_to_send.empty() &&
5198 tx_relay->m_next_inv_send_time == 0s));
5207 Misbehaving(*peer,
"non-verack message before version handshake");
5212 const auto ser_params{
5221 std::vector<CAddress> vAddr;
5225 if (!SetupAddressRelay(pfrom, *peer)) {
5231 if (vAddr.size() > m_opts.max_addr_to_send) {
5232 Misbehaving(*peer,
strprintf(
"%s message size = %u", msg_type,
5238 std::vector<CAddress> vAddrOk;
5239 const auto current_a_time{Now<NodeSeconds>()};
5242 const auto current_time = GetTime<std::chrono::microseconds>();
5244 LOCK(peer->m_addr_token_bucket_mutex);
5247 const auto time_diff =
5248 std::max(current_time - peer->m_addr_token_timestamp, 0us);
5249 const double increment =
5251 peer->m_addr_token_bucket =
5252 std::min<double>(peer->m_addr_token_bucket + increment,
5256 peer->m_addr_token_timestamp = current_time;
5258 const bool rate_limited =
5260 uint64_t num_proc = 0;
5261 uint64_t num_rate_limit = 0;
5262 Shuffle(vAddr.begin(), vAddr.end(), m_rng);
5264 if (interruptMsgProc) {
5269 LOCK(peer->m_addr_token_bucket_mutex);
5271 if (peer->m_addr_token_bucket < 1.0) {
5277 peer->m_addr_token_bucket -= 1.0;
5290 addr.
nTime > current_a_time + 10min) {
5291 addr.
nTime = current_a_time - 5 * 24h;
5293 AddAddressKnown(*peer, addr);
5302 if (addr.
nTime > current_a_time - 10min && !peer->m_getaddr_sent &&
5305 RelayAddress(pfrom.
GetId(), addr, fReachable);
5309 vAddrOk.push_back(addr);
5312 peer->m_addr_processed += num_proc;
5313 peer->m_addr_rate_limited += num_rate_limit;
5315 "Received addr: %u addresses (%u processed, %u rate-limited) "
5317 vAddr.size(), num_proc, num_rate_limit, pfrom.
GetId());
5319 m_addrman.
Add(vAddrOk, pfrom.
addr, 2h);
5320 if (vAddr.size() < 1000) {
5321 peer->m_getaddr_sent =
false;
5328 "addrfetch connection completed peer=%d; disconnecting\n",
5336 peer->m_wants_addrv2 =
true;
5341 peer->m_prefers_headers =
true;
5346 bool sendcmpct_hb{
false};
5347 uint64_t sendcmpct_version{0};
5348 vRecv >> sendcmpct_hb >> sendcmpct_version;
5355 CNodeState *nodestate = State(pfrom.
GetId());
5356 nodestate->m_provides_cmpctblocks =
true;
5357 nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
5366 std::vector<CInv> vInv;
5369 Misbehaving(*peer,
strprintf(
"inv message size = %u", vInv.size()));
5373 const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
5375 const auto current_time{GetTime<std::chrono::microseconds>()};
5376 std::optional<BlockHash> best_block;
5378 auto logInv = [&](
const CInv &inv,
bool fAlreadyHave) {
5380 fAlreadyHave ?
"have" :
"new", pfrom.
GetId());
5383 for (
CInv &inv : vInv) {
5384 if (interruptMsgProc) {
5396 const bool fAlreadyHave = AlreadyHaveBlock(
BlockHash(inv.
hash));
5397 logInv(inv, fAlreadyHave);
5400 UpdateBlockAvailability(pfrom.
GetId(), hash);
5402 !IsBlockRequested(hash)) {
5409 best_block = std::move(hash);
5420 const bool fAlreadyHave = AlreadyHaveProof(proofid);
5421 logInv(inv, fAlreadyHave);
5422 AddKnownProof(*peer, proofid);
5424 if (!fAlreadyHave && m_avalanche &&
5426 const bool preferred = isPreferredDownloadPeer(pfrom);
5428 LOCK(cs_proofrequest);
5429 AddProofAnnouncement(pfrom, proofid, current_time,
5438 const bool fAlreadyHave =
5439 AlreadyHaveTx(txid,
true);
5440 logInv(inv, fAlreadyHave);
5442 AddKnownTx(*peer, txid);
5443 if (reject_tx_invs) {
5445 "transaction (%s) inv sent in violation of "
5446 "protocol, disconnecting peer=%d\n",
5450 }
else if (!fAlreadyHave &&
5452 AddTxAnnouncement(pfrom, txid, current_time);
5459 "Unknown inv type \"%s\" received from peer=%d\n",
5476 if (state.fSyncStarted ||
5477 (!peer->m_inv_triggered_getheaders_before_sync &&
5478 *best_block != m_last_block_inv_triggering_headers_sync)) {
5479 if (MaybeSendGetHeaders(
5480 pfrom,
GetLocator(m_chainman.m_best_header), *peer)) {
5482 m_chainman.m_best_header->nHeight,
5483 best_block->ToString(), pfrom.
GetId());
5485 if (!state.fSyncStarted) {
5486 peer->m_inv_triggered_getheaders_before_sync =
true;
5490 m_last_block_inv_triggering_headers_sync = *best_block;
5499 std::vector<CInv> vInv;
5503 strprintf(
"getdata message size = %u", vInv.size()));
5508 vInv.size(), pfrom.
GetId());
5510 if (vInv.size() > 0) {
5516 LOCK(peer->m_getdata_requests_mutex);
5517 peer->m_getdata_requests.insert(peer->m_getdata_requests.end(),
5518 vInv.begin(), vInv.end());
5519 ProcessGetData(config, pfrom, *peer, interruptMsgProc);
5528 vRecv >> locator >> hashStop;
5532 "getblocks locator size %lld > %d, disconnect peer=%d\n",
5546 std::shared_ptr<const CBlock> a_recent_block;
5548 LOCK(m_most_recent_block_mutex);
5549 a_recent_block = m_most_recent_block;
5553 state, a_recent_block, m_avalanche)) {
5571 (pindex ? pindex->
nHeight : -1),
5574 for (; pindex; pindex = m_chainman.
ActiveChain().Next(pindex)) {
5583 const int nPrunedBlocksLikelyToHave =
5587 (!pindex->nStatus.hasData() ||
5589 nPrunedBlocksLikelyToHave)) {
5592 " getblocks stopping, pruned or too old block at %d %s\n",
5597 peer->m_block_inv_mutex,
5598 peer->m_blocks_for_inv_relay.push_back(pindex->
GetBlockHash()));
5599 if (--nLimit <= 0) {
5605 peer->m_continuation_block = pindex->GetBlockHash();
5617 std::shared_ptr<const CBlock> recent_block;
5619 LOCK(m_most_recent_block_mutex);
5620 if (m_most_recent_block_hash == req.
blockhash) {
5621 recent_block = m_most_recent_block;
5626 SendBlockTransactions(pfrom, *peer, *recent_block, req);
5636 if (!pindex || !pindex->nStatus.hasData()) {
5639 "Peer %d sent us a getblocktxn for a block we don't have\n",
5650 if (!block_pos.IsNull()) {
5657 LogError(
"getblocktxn: block read failed for block %s\n",
5663 SendBlockTransactions(pfrom, *peer, block, req);
5675 "Peer %d sent us a getblocktxn for a block > %i deep\n",
5680 WITH_LOCK(peer->m_getdata_requests_mutex,
5681 peer->m_getdata_requests.push_back(inv));
5690 vRecv >> locator >> hashStop;
5694 "getheaders locator size %lld > %d, disconnect peer=%d\n",
5703 "Ignoring getheaders from peer=%d while importing/reindexing\n",
5717 if (m_chainman.
ActiveTip() ==
nullptr ||
5722 "Ignoring getheaders from peer=%d because active chain "
5723 "has too little work; sending empty response\n",
5728 std::vector<CBlock>());
5732 CNodeState *nodestate = State(pfrom.
GetId());
5741 if (!BlockRequestAllowed(pindex)) {
5743 "%s: ignoring request from peer=%i for old block "
5744 "header that isn't in the main chain\n",
5745 __func__, pfrom.
GetId());
5759 std::vector<CBlock> vHeaders;
5762 (pindex ? pindex->
nHeight : -1),
5765 for (; pindex; pindex = m_chainman.
ActiveChain().Next(pindex)) {
5767 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) {
5784 nodestate->pindexBestHeaderSent =
5791 if (RejectIncomingTxs(pfrom)) {
5793 "transaction sent in violation of protocol peer=%d\n",
5809 const CTransaction &tx = *ptx;
5810 const TxId &txid = tx.GetId();
5811 AddKnownTx(*peer, txid);
5816 m_txrequest.ReceivedResponse(pfrom.
GetId(), txid);
5818 if (AlreadyHaveTx(txid,
true)) {
5824 if (!m_mempool.
exists(tx.GetId())) {
5826 "Not relaying non-mempool transaction %s from "
5827 "forcerelay peer=%d\n",
5828 tx.GetId().ToString(), pfrom.
GetId());
5830 LogPrintf(
"Force relaying tx %s from peer=%d\n",
5831 tx.GetId().ToString(), pfrom.
GetId());
5832 RelayTransaction(tx.GetId());
5836 if (m_recent_rejects_package_reconsiderable.contains(txid)) {
5844 "found tx %s in reconsiderable rejects, looking for "
5845 "child in orphanage\n",
5847 if (
auto package_to_validate{
5848 Find1P1CPackage(ptx, pfrom.
GetId())}) {
5851 package_to_validate->m_txns,
5854 "package evaluation for %s: %s (%s)\n",
5855 package_to_validate->ToString(),
5857 ?
"package accepted"
5858 :
"package rejected",
5860 ProcessPackageResult(package_to_validate.value(),
5889 ProcessValidTx(pfrom.
GetId(), ptx);
5895 bool fRejectedParents =
false;
5899 std::vector<TxId> unique_parents;
5900 unique_parents.reserve(tx.vin.size());
5901 for (
const CTxIn &txin : tx.vin) {
5904 unique_parents.push_back(txin.prevout.GetTxId());
5906 std::sort(unique_parents.begin(), unique_parents.end());
5907 unique_parents.erase(
5908 std::unique(unique_parents.begin(), unique_parents.end()),
5909 unique_parents.end());
5917 std::optional<TxId> rejected_parent_reconsiderable;
5918 for (
const TxId &parent_txid : unique_parents) {
5919 if (m_recent_rejects.contains(parent_txid)) {
5920 fRejectedParents =
true;
5924 if (m_recent_rejects_package_reconsiderable.contains(
5926 !m_mempool.
exists(parent_txid)) {
5931 if (rejected_parent_reconsiderable.has_value()) {
5932 fRejectedParents =
true;
5935 rejected_parent_reconsiderable = parent_txid;
5938 if (!fRejectedParents) {
5939 const auto current_time{
5940 GetTime<std::chrono::microseconds>()};
5942 for (
const TxId &parent_txid : unique_parents) {
5944 AddKnownTx(*peer, parent_txid);
5948 if (!AlreadyHaveTx(parent_txid,
5950 AddTxAnnouncement(pfrom, parent_txid, current_time);
5956 if (
unsigned int nEvicted =
5960 if (orphanage.AddTx(ptx,
5962 AddToCompactExtraTransactions(ptx);
5965 m_opts.max_orphan_txs, m_rng);
5968 "orphanage overflow, removed %u tx\n",
5974 m_txrequest.ForgetInvId(tx.GetId());
5978 "not keeping orphan with rejected parents %s\n",
5979 tx.GetId().ToString());
5982 m_recent_rejects.insert(tx.GetId());
5983 m_txrequest.ForgetInvId(tx.GetId());
5987 ProcessInvalidTx(pfrom.
GetId(), ptx, state,
5997 "tx %s failed but reconsiderable, looking for child in "
6000 if (
auto package_to_validate{
6001 Find1P1CPackage(ptx, pfrom.
GetId())}) {
6004 package_to_validate->m_txns,
false)};
6006 "package evaluation for %s: %s (%s)\n",
6007 package_to_validate->ToString(),
6009 ?
"package accepted"
6010 :
"package rejected",
6012 ProcessPackageResult(package_to_validate.value(),
6021 m_txrequest.ForgetInvId(tx.GetId());
6023 unsigned int nEvicted{0};
6030 m_opts.max_conflicting_txs, m_rng);
6035 "conflicting pool overflow, removed %u tx\n",
6048 "Unexpected cmpctblock message received from peer %d\n",
6055 vRecv >> cmpctblock;
6056 }
catch (std::ios_base::failure &e) {
6058 Misbehaving(*peer,
"cmpctblock-bad-indexes");
6062 bool received_new_header =
false;
6075 MaybeSendGetHeaders(
6076 pfrom,
GetLocator(m_chainman.m_best_header), *peer);
6082 GetAntiDoSWorkThreshold()) {
6086 "Ignoring low-work compact block from peer %d\n",
6092 received_new_header =
true;
6102 MaybePunishNodeForBlock(pfrom.
GetId(), state,
6104 "invalid header via cmpctblock");
6109 if (received_new_header) {
6110 LogInfo(
"Saw new cmpctblock header hash=%s peer=%d\n",
6111 blockhash.ToString(), pfrom.
GetId());
6118 bool fProcessBLOCKTXN =
false;
6124 bool fRevertToHeaderProcessing =
false;
6128 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6129 bool fBlockReconstructed =
false;
6137 "cmpctblock: header accepted but no pindex for block %s\n",
6138 blockhash.ToString());
6145 CNodeState *nodestate = State(pfrom.
GetId());
6149 if (received_new_header &&
6152 nodestate->m_last_block_announcement =
GetTime();
6155 if (pindex->nStatus.hasData()) {
6162 size_t already_in_flight =
6163 std::distance(range_flight.first, range_flight.second);
6164 bool requested_block_from_this_peer{
false};
6168 bool first_in_flight =
6169 already_in_flight == 0 ||
6170 (range_flight.first->second.first == pfrom.
GetId());
6172 while (range_flight.first != range_flight.second) {
6173 if (range_flight.first->second.first == pfrom.
GetId()) {
6174 requested_block_from_this_peer =
true;
6177 range_flight.first++;
6186 if (requested_block_from_this_peer) {
6190 std::vector<CInv> vInv(1);
6199 if (!already_in_flight && !CanDirectFetch()) {
6207 nodestate->vBlocksInFlight.size() <
6209 requested_block_from_this_peer) {
6210 std::list<QueuedBlock>::iterator *queuedBlockIt =
nullptr;
6211 if (!BlockRequested(config, pfrom.
GetId(), *pindex,
6213 if (!(*queuedBlockIt)->partialBlock) {
6215 ->partialBlock.reset(
6222 "we were already syncing!\n");
6228 *(*queuedBlockIt)->partialBlock;
6230 partialBlock.
InitData(cmpctblock, vExtraTxnForCompact);
6236 Misbehaving(*peer,
"invalid compact block");
6239 if (first_in_flight) {
6242 std::vector<CInv> vInv(1);
6255 for (
size_t i = 0; i < cmpctblock.
BlockTxCount(); i++) {
6266 fProcessBLOCKTXN =
true;
6267 }
else if (first_in_flight) {
6274 IsBlockRequestedFromOutbound(blockhash) ||
6297 tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
6302 std::vector<CTransactionRef> dummy;
6303 status = tempBlock.FillBlock(*pblock, dummy);
6305 fBlockReconstructed =
true;
6309 if (requested_block_from_this_peer) {
6313 std::vector<CInv> vInv(1);
6320 fRevertToHeaderProcessing =
true;
6325 if (fProcessBLOCKTXN) {
6327 blockTxnMsg, time_received, interruptMsgProc);
6330 if (fRevertToHeaderProcessing) {
6336 return ProcessHeadersMessage(config, pfrom, *peer,
6341 if (fBlockReconstructed) {
6346 mapBlockSource.emplace(pblock->GetHash(),
6347 std::make_pair(pfrom.
GetId(),
false));
6358 ProcessBlock(config, pfrom, pblock,
true,
6367 RemoveBlockRequest(pblock->GetHash(), std::nullopt);
6377 "Unexpected blocktxn message received from peer %d\n",
6385 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6386 bool fBlockRead =
false;
6390 auto range_flight = mapBlocksInFlight.equal_range(resp.
blockhash);
6391 size_t already_in_flight =
6392 std::distance(range_flight.first, range_flight.second);
6393 bool requested_block_from_this_peer{
false};
6397 bool first_in_flight =
6398 already_in_flight == 0 ||
6399 (range_flight.first->second.first == pfrom.
GetId());
6401 while (range_flight.first != range_flight.second) {
6402 auto [node_id, block_it] = range_flight.first->second;
6403 if (node_id == pfrom.
GetId() && block_it->partialBlock) {
6404 requested_block_from_this_peer =
true;
6407 range_flight.first++;
6410 if (!requested_block_from_this_peer) {
6412 "Peer %d sent us block transactions for block "
6413 "we weren't expecting\n",
6419 *range_flight.first->second.second->partialBlock;
6427 "invalid compact block/non-matching block transactions");
6430 if (first_in_flight) {
6432 std::vector<CInv> invs;
6439 "Peer %d sent us a compact block but it failed to "
6440 "reconstruct, waiting on first download to complete\n",
6473 std::make_pair(pfrom.
GetId(),
false));
6484 ProcessBlock(config, pfrom, pblock,
true,
6494 "Unexpected headers message received from peer %d\n",
6499 std::vector<CBlockHeader> headers;
6506 strprintf(
"too-many-headers: headers message size = %u",
6510 headers.resize(nCount);
6511 for (
unsigned int n = 0; n < nCount; n++) {
6512 vRecv >> headers[n];
6517 ProcessHeadersMessage(config, pfrom, *peer, std::move(headers),
6523 if (m_headers_presync_should_signal.exchange(
false)) {
6524 HeadersPresyncStats stats;
6526 LOCK(m_headers_presync_mutex);
6528 m_headers_presync_stats.find(m_headers_presync_bestpeer);
6529 if (it != m_headers_presync_stats.end()) {
6535 stats.first, stats.second->first, stats.second->second);
6546 "Unexpected block message received from peer %d\n",
6551 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6555 pblock->GetHash().ToString(), pfrom.
GetId());
6560 pblock->hashPrevBlock))};
6564 "Received mutated block from peer=%d\n", peer->m_id);
6565 Misbehaving(*peer,
"mutated block");
6567 RemoveBlockRequest(pblock->GetHash(), peer->m_id));
6577 const BlockHash hash = pblock->GetHash();
6578 bool min_pow_checked =
false;
6583 forceProcessing = IsBlockRequested(hash);
6584 RemoveBlockRequest(hash, pfrom.
GetId());
6588 mapBlockSource.emplace(hash, std::make_pair(pfrom.
GetId(),
true));
6594 GetAntiDoSWorkThreshold()) {
6595 min_pow_checked =
true;
6598 ProcessBlock(config, pfrom, pblock, forceProcessing, min_pow_checked);
6608 if (pfrom.m_avalanche_pubkey.has_value()) {
6611 "Ignoring avahello from peer %d: already in our node set\n",
6617 vRecv >> delegation;
6624 if (!delegation.
verify(state, pubkey)) {
6625 Misbehaving(*peer,
"invalid-delegation");
6628 pfrom.m_avalanche_pubkey = std::move(pubkey);
6631 sighasher << delegation.
getId();
6639 if (!(*pfrom.m_avalanche_pubkey)
6640 .VerifySchnorr(sighasher.GetHash(),
sig)) {
6641 Misbehaving(*peer,
"invalid-avahello-signature");
6648 if (!AlreadyHaveProof(proofid)) {
6649 const bool preferred = isPreferredDownloadPeer(pfrom);
6650 LOCK(cs_proofrequest);
6651 AddProofAnnouncement(pfrom, proofid,
6652 GetTime<std::chrono::microseconds>(),
6660 vRecv >> max_elements;
6664 Misbehaving(*peer,
"avahello-max-elements-too-low");
6672 return pm.
addNode(pfrom.
GetId(), proofid, max_elements);
6683 WITH_LOCK(peer->m_addr_token_bucket_mutex,
6684 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
6688 peer->m_proof_relay->compactproofs_requested =
true;
6699 const auto now = Now<SteadyMilliseconds>();
6705 last_poll + std::chrono::milliseconds(m_opts.avalanche_cooldown)) {
6707 "Ignoring repeated avapoll from peer %d: cooldown not "
6722 strprintf(
"too-many-ava-poll: poll message size = %u", nCount));
6726 std::vector<avalanche::Vote> votes;
6727 votes.reserve(nCount);
6729 bool fPreconsensus{
false};
6730 bool fStakingPreconsensus{
false};
6735 fStakingPreconsensus =
6739 for (
unsigned int n = 0; n < nCount; n++) {
6747 if (!quorum_established) {
6748 votes.emplace_back(vote, inv.
hash);
6755 if (fPreconsensus) {
6757 GetAvalancheVoteForTx(*m_avalanche,
TxId(inv.
hash));
6769 if (fStakingPreconsensus) {
6776 "poll inv type %d unknown from peer=%d\n",
6781 votes.emplace_back(vote, inv.
hash);
6807 if (!pfrom.m_avalanche_pubkey.has_value() ||
6808 !(*pfrom.m_avalanche_pubkey)
6809 .VerifySchnorr(verifier.GetHash(),
sig)) {
6810 Misbehaving(*peer,
"invalid-ava-response-signature");
6815 auto now = GetTime<std::chrono::seconds>();
6817 std::vector<avalanche::VoteItemUpdate> updates;
6818 bool disconnect{
false};
6821 disconnect, error)) {
6823 Misbehaving(*peer, error);
6841 "Repeated failure to register votes from peer %d: %s\n",
6842 pfrom.
GetId(), error);
6845 Misbehaving(*peer, error);
6858 auto logVoteUpdate = [](
const auto &voteUpdate,
6859 const std::string &voteItemTypeStr,
6860 const auto &voteItemId) {
6861 std::string voteOutcome;
6862 bool alwaysPrint =
false;
6863 switch (voteUpdate.getStatus()) {
6865 voteOutcome =
"invalidated";
6869 voteOutcome =
"rejected";
6872 voteOutcome =
"accepted";
6875 voteOutcome =
"finalized";
6878 alwaysPrint = voteItemTypeStr !=
"tx";
6881 voteOutcome =
"stalled";
6890 alwaysPrint &= (voteItemTypeStr !=
"contender");
6893 LogPrintf(
"Avalanche %s %s %s\n", voteOutcome, voteItemTypeStr,
6894 voteItemId.ToString());
6898 voteItemTypeStr, voteItemId.ToString());
6902 bool shouldActivateBestChain =
false;
6904 bool fPreconsensus{
false};
6905 bool fStakingPreconsensus{
false};
6910 fStakingPreconsensus =
6914 for (
const auto &u : updates) {
6919 if (
auto pitem = std::get_if<const avalanche::ProofRef>(&item)) {
6923 logVoteUpdate(u,
"proof", proofid);
6925 auto rejectionMode =
6927 auto nextCooldownTimePoint = GetTime<std::chrono::seconds>();
6928 switch (u.getStatus()) {
6944 return pm.rejectProof(proofid,
6948 "ERROR: Failed to reject proof: %s\n",
6954 nextCooldownTimePoint += std::chrono::seconds(
6955 m_opts.avalanche_peer_replacement_cooldown);
6961 avalanche::PeerManager::
6962 RegistrationMode::FORCE_ACCEPT);
6965 [&](const avalanche::Peer &peer) {
6966 pm.updateNextPossibleConflictTime(
6968 nextCooldownTimePoint);
6969 if (u.getStatus() ==
6970 avalanche::VoteStatus::
6972 pm.setFinalized(peer.peerid);
6980 "ERROR: Failed to accept proof: %s\n",
6987 auto getBlockFromIndex = [
this](
const CBlockIndex *pindex)
6988 -> std::shared_ptr<const CBlock> {
6991 std::shared_ptr<const CBlock> pblock =
WITH_LOCK(
6992 m_most_recent_block_mutex,
return m_most_recent_block);
6994 if (!pblock || pblock->GetHash() != pindex->
GetBlockHash()) {
6995 std::shared_ptr<CBlock> pblockRead =
6996 std::make_shared<CBlock>();
6999 LogError(
"getBlockFromIndex: cannot load block from "
7004 pblock = pblockRead;
7009 if (
auto pitem = std::get_if<const CBlockIndex *>(&item)) {
7012 shouldActivateBestChain =
true;
7016 switch (u.getStatus()) {
7021 LogPrintf(
"ERROR: Database error: %s\n",
7030 LogPrintf(
"ERROR: Database error: %s\n",
7035 auto pblock = getBlockFromIndex(pindex);
7037 LogError(
"avaresponse: failed to get invalidated "
7038 "block from index\n");
7055 std::unique_ptr<node::CBlockTemplate> blockTemplate;
7059 chainstate.UnparkBlock(pindex);
7061 const bool newlyFinalized =
7062 !chainstate.IsBlockAvalancheFinalized(pindex) &&
7063 chainstate.AvalancheFinalizeBlock(pindex,
7068 if (fPreconsensus && newlyFinalized) {
7078 std::unordered_set<TxId, SaltedTxIdHasher>
7079 confirmedTxIdsInNonFinalizedBlocks;
7080 bool missing_block =
false;
7082 block !=
nullptr && block != pindex;
7083 block = block->pprev) {
7085 getBlockFromIndex(block);
7086 if (!currentBlock) {
7088 "avaresponse: failed to get "
7089 "finalized block descendant from "
7092 missing_block =
true;
7095 for (
const auto &tx : currentBlock->vtx) {
7096 confirmedTxIdsInNonFinalizedBlocks
7097 .insert(tx->GetId());
7101 if (missing_block) {
7113 confirmedTxIdsInNonFinalizedBlocks);
7125 config, chainstate, &m_mempool,
7127 blockAssembler.pblocktemplate.reset(
7130 if (blockAssembler.pblocktemplate) {
7131 blockAssembler.addTxs(m_mempool);
7132 blockTemplate = std::move(
7133 blockAssembler.pblocktemplate);
7138 if (blockTemplate) {
7143 for (
const auto &templateEntry :
7157 if (fStakingPreconsensus) {
7159 std::get_if<const avalanche::StakeContenderId>(&item)) {
7161 logVoteUpdate(u,
"contender", contenderId);
7163 switch (u.getStatus()) {
7184 if (!fPreconsensus) {
7188 if (
auto pitem = std::get_if<const CTransactionRef>(&item)) {
7192 const TxId &txid = tx->GetId();
7193 const auto status{u.getStatus()};
7198 logVoteUpdate(u,
"tx", txid);
7210 std::shared_ptr<const std::vector<Coin>> spentCoins;
7222 _spentCoins.has_value()
7223 ? std::make_shared<const std::vector<Coin>>(
7224 std::move(*_spentCoins))
7228 if (m_mempool.
exists(txid)) {
7232 std::vector<CTransactionRef> conflictingTxs =
7238 if (conflictingTxs.size() > 0) {
7246 "Attempting to pull a now invalid "
7247 "conflicting tx %s to mempool\n",
7248 conflictingTxs[0]->GetId().
ToString());
7255 for (
const auto &conflictingTx :
7258 conflictingTx->GetId());
7277 m_recent_rejects.insert(txid);
7279 AddToCompactExtraTransactions(tx);
7294 return conflicting.HaveTx(txid);
7297 std::vector<CTransactionRef>
7298 mempool_conflicting_txs;
7299 for (
const auto &txin : tx->vin) {
7304 mempool_conflicting_txs.push_back(
7305 std::move(conflict));
7312 LogError(
"accepted tx %s failed mempool "
7320 [&txid, &mempool_conflicting_txs](
7325 if (mempool_conflicting_txs.size() >
7328 mempool_conflicting_txs[0],
7337 auto it = m_mempool.
GetIter(txid);
7338 if (!it.has_value()) {
7341 "Error: finalized tx (%s) is not in the "
7347 std::vector<TxId> finalizedTxIds;
7348 m_mempool.setAvalancheFinalized(
7353 for (
const auto &finalized_txid : finalizedTxIds) {
7358 logVoteUpdate(u,
"tx", finalized_txid);
7366 std::vector<CTransactionRef>
7369 for (
const auto &conflictingTx :
7371 m_recent_rejects.insert(
7372 conflictingTx->GetId());
7374 conflictingTx->GetId());
7400 m_txrequest.ForgetInvId(txid);
7406 for (
auto &it : m_peer_map) {
7407 auto tx_relay = (*it.second).GetTxRelay();
7412 LOCK(tx_relay->m_tx_inventory_mutex);
7419 auto &stalled_by_time =
7420 tx_relay->m_avalanche_stalled_txids
7422 if (stalled_by_time.size() >=
7424 stalled_by_time.erase(
7425 stalled_by_time.begin()->timeAdded);
7428 tx_relay->m_avalanche_stalled_txids.insert(
7433 AddToCompactExtraTransactions(tx);
7441 if (shouldActivateBestChain) {
7444 state,
nullptr, m_avalanche)) {
7459 ReceivedAvalancheProof(pfrom, *peer, proof);
7468 if (peer->m_proof_relay ==
nullptr) {
7472 peer->m_proof_relay->lastSharedProofsUpdate =
7473 GetTime<std::chrono::seconds>();
7475 peer->m_proof_relay->sharedProofs =
7481 peer->m_proof_relay->sharedProofs);
7491 if (peer->m_proof_relay ==
nullptr) {
7496 if (!peer->m_proof_relay->compactproofs_requested) {
7500 peer->m_proof_relay->compactproofs_requested =
false;
7504 vRecv >> compactProofs;
7505 }
catch (std::ios_base::failure &e) {
7507 Misbehaving(*peer,
"avaproofs-bad-indexes");
7513 if (!ReceivedAvalancheProof(pfrom, *peer, prefilledProof.proof)) {
7543 auto shortIdProcessor =
7547 if (shortIdProcessor.hasOutOfBoundIndex()) {
7550 Misbehaving(*peer,
"avaproofs-bad-indexes");
7553 if (!shortIdProcessor.isEvenlyDistributed()) {
7558 std::vector<std::pair<avalanche::ProofId, bool>> remoteProofsStatus;
7565 shortIdProcessor.matchKnownItem(shortid, peer.
proof);
7572 remoteProofsStatus.emplace_back(peer.
getProofId(),
7583 for (
size_t i = 0; i < compactProofs.
size(); i++) {
7584 if (shortIdProcessor.getItem(i) ==
nullptr) {
7600 return pfrom.m_avalanche_pubkey.has_value())) {
7603 for (
const auto &[proofid, present] : remoteProofsStatus) {
7613 if (peer->m_proof_relay ==
nullptr) {
7620 auto requestedIndiceIt = proofreq.
indices.begin();
7621 uint32_t treeIndice = 0;
7622 peer->m_proof_relay->sharedProofs.forEachLeaf([&](
const auto &proof) {
7623 if (requestedIndiceIt == proofreq.
indices.end()) {
7628 if (treeIndice++ == *requestedIndiceIt) {
7630 requestedIndiceIt++;
7636 peer->m_proof_relay->sharedProofs = {};
7649 "Ignoring \"getaddr\" from %s connection. peer=%d\n",
7656 Assume(SetupAddressRelay(pfrom, *peer));
7660 if (peer->m_getaddr_recvd) {
7665 peer->m_getaddr_recvd =
true;
7667 peer->m_addrs_to_send.clear();
7668 std::vector<CAddress> vAddr;
7669 const size_t maxAddrToSend = m_opts.max_addr_to_send;
7677 for (
const CAddress &addr : vAddr) {
7678 PushAddress(*peer, addr);
7684 auto now = GetTime<std::chrono::seconds>();
7694 if (!SetupAddressRelay(pfrom, *peer)) {
7696 "Ignoring getavaaddr message from %s peer=%d\n",
7701 auto availabilityScoreComparator = [](
const CNode *lhs,
7704 double scoreRhs = rhs->getAvailabilityScore();
7706 if (scoreLhs != scoreRhs) {
7707 return scoreLhs > scoreRhs;
7716 std::set<
const CNode *,
decltype(availabilityScoreComparator)> avaNodes(
7717 availabilityScoreComparator);
7724 avaNodes.insert(pnode);
7725 if (avaNodes.size() > m_opts.max_addr_to_send) {
7726 avaNodes.erase(std::prev(avaNodes.end()));
7730 peer->m_addrs_to_send.clear();
7731 for (
const CNode *pnode : avaNodes) {
7732 PushAddress(*peer, pnode->
addr);
7743 "mempool request with bloom filters disabled, "
7744 "disconnect peer=%d\n",
7755 "mempool request with bandwidth limit reached, "
7756 "disconnect peer=%d\n",
7763 if (
auto tx_relay = peer->GetTxRelay()) {
7764 LOCK(tx_relay->m_tx_inventory_mutex);
7765 tx_relay->m_send_mempool =
true;
7794 const auto ping_end = time_received;
7797 bool bPingFinished =
false;
7798 std::string sProblem;
7800 if (nAvail >=
sizeof(nonce)) {
7805 if (peer->m_ping_nonce_sent != 0) {
7806 if (nonce == peer->m_ping_nonce_sent) {
7809 bPingFinished =
true;
7810 const auto ping_time = ping_end - peer->m_ping_start.load();
7811 if (ping_time.count() >= 0) {
7816 sProblem =
"Timing mishap";
7820 sProblem =
"Nonce mismatch";
7824 bPingFinished =
true;
7825 sProblem =
"Nonce zero";
7829 sProblem =
"Unsolicited pong without ping";
7834 bPingFinished =
true;
7835 sProblem =
"Short payload";
7838 if (!(sProblem.empty())) {
7840 "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
7841 pfrom.
GetId(), sProblem, peer->m_ping_nonce_sent, nonce,
7844 if (bPingFinished) {
7845 peer->m_ping_nonce_sent = 0;
7853 "filterload received despite not offering bloom services "
7854 "from peer=%d; disconnecting\n",
7864 Misbehaving(*peer,
"too-large bloom filter");
7865 }
else if (
auto tx_relay = peer->GetTxRelay()) {
7867 LOCK(tx_relay->m_bloom_filter_mutex);
7868 tx_relay->m_bloom_filter.reset(
new CBloomFilter(filter));
7869 tx_relay->m_relay_txs =
true;
7879 "filteradd received despite not offering bloom services "
7880 "from peer=%d; disconnecting\n",
7885 std::vector<uint8_t> vData;
7894 }
else if (
auto tx_relay = peer->GetTxRelay()) {
7895 LOCK(tx_relay->m_bloom_filter_mutex);
7896 if (tx_relay->m_bloom_filter) {
7897 tx_relay->m_bloom_filter->insert(vData);
7905 Misbehaving(*peer,
"bad filteradd message");
7913 "filterclear received despite not offering bloom services "
7914 "from peer=%d; disconnecting\n",
7919 auto tx_relay = peer->GetTxRelay();
7925 LOCK(tx_relay->m_bloom_filter_mutex);
7926 tx_relay->m_bloom_filter =
nullptr;
7927 tx_relay->m_relay_txs =
true;
7936 vRecv >> newFeeFilter;
7938 if (
auto tx_relay = peer->GetTxRelay()) {
7939 tx_relay->m_fee_filter_received = newFeeFilter;
7948 ProcessGetCFilters(pfrom, *peer, vRecv);
7953 ProcessGetCFHeaders(pfrom, *peer, vRecv);
7958 ProcessGetCFCheckPt(pfrom, *peer, vRecv);
7963 std::vector<CInv> vInv;
7969 for (
CInv &inv : vInv) {
7975 m_txrequest.ReceivedResponse(pfrom.
GetId(),
TxId(inv.
hash));
7982 LOCK(cs_proofrequest);
7983 m_proofrequest.ReceivedResponse(
7997bool PeerManagerImpl::MaybeDiscourageAndDisconnect(
CNode &pnode, Peer &peer) {
7999 LOCK(peer.m_misbehavior_mutex);
8002 if (!peer.m_should_discourage) {
8006 peer.m_should_discourage =
false;
8012 LogPrintf(
"Warning: not punishing noban peer %d!\n", peer.m_id);
8018 LogPrintf(
"Warning: not punishing manually connected peer %d!\n",
8027 "Warning: disconnecting but not discouraging %s peer %d!\n",
8044bool PeerManagerImpl::ProcessMessages(
const Config &config,
CNode *pfrom,
8045 std::atomic<bool> &interruptMsgProc) {
8048 PeerRef peer = GetPeerRef(pfrom->
GetId());
8049 if (peer ==
nullptr) {
8054 LOCK(peer->m_getdata_requests_mutex);
8055 if (!peer->m_getdata_requests.empty()) {
8056 ProcessGetData(config, *pfrom, *peer, interruptMsgProc);
8060 const bool processed_orphan = ProcessOrphanTx(config, *peer);
8066 if (processed_orphan) {
8073 LOCK(peer->m_getdata_requests_mutex);
8074 if (!peer->m_getdata_requests.empty()) {
8091 bool fMoreWork = poll_result->second;
8095 msg.m_recv.size(),
msg.m_recv.data());
8097 if (m_opts.capture_messages) {
8103 ProcessMessage(config, *pfrom,
msg.m_type,
msg.m_recv,
msg.m_time,
8105 if (interruptMsgProc) {
8110 LOCK(peer->m_getdata_requests_mutex);
8111 if (!peer->m_getdata_requests.empty()) {
8120 return orphanage.HaveTxToReconsider(peer->m_id);
8124 }
catch (
const std::exception &e) {
8127 e.what(),
typeid(e).name());
8136void PeerManagerImpl::ConsiderEviction(
CNode &pto, Peer &peer,
8137 std::chrono::seconds time_in_seconds) {
8140 CNodeState &state = *State(pto.
GetId());
8143 state.fSyncStarted) {
8150 if (state.pindexBestKnownBlock !=
nullptr &&
8151 state.pindexBestKnownBlock->nChainWork >=
8153 if (state.m_chain_sync.m_timeout != 0s) {
8154 state.m_chain_sync.m_timeout = 0s;
8155 state.m_chain_sync.m_work_header =
nullptr;
8156 state.m_chain_sync.m_sent_getheaders =
false;
8158 }
else if (state.m_chain_sync.m_timeout == 0s ||
8159 (state.m_chain_sync.m_work_header !=
nullptr &&
8160 state.pindexBestKnownBlock !=
nullptr &&
8161 state.pindexBestKnownBlock->nChainWork >=
8162 state.m_chain_sync.m_work_header->nChainWork)) {
8168 state.m_chain_sync.m_work_header = m_chainman.
ActiveChain().
Tip();
8169 state.m_chain_sync.m_sent_getheaders =
false;
8170 }
else if (state.m_chain_sync.m_timeout > 0s &&
8171 time_in_seconds > state.m_chain_sync.m_timeout) {
8176 if (state.m_chain_sync.m_sent_getheaders) {
8179 "Disconnecting outbound peer %d for old chain, best known "
8182 state.pindexBestKnownBlock !=
nullptr
8183 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
8187 assert(state.m_chain_sync.m_work_header);
8192 MaybeSendGetHeaders(
8193 pto,
GetLocator(state.m_chain_sync.m_work_header->pprev),
8197 "sending getheaders to outbound peer=%d to verify chain "
8198 "work (current best known block:%s, benchmark blockhash: "
8201 state.pindexBestKnownBlock !=
nullptr
8202 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
8204 state.m_chain_sync.m_work_header->GetBlockHash()
8206 state.m_chain_sync.m_sent_getheaders =
true;
8213 state.m_chain_sync.m_timeout =
8220void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) {
8229 std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0},
8230 next_youngest_peer{-1, 0};
8236 if (pnode->
GetId() > youngest_peer.first) {
8237 next_youngest_peer = youngest_peer;
8238 youngest_peer.first = pnode->GetId();
8239 youngest_peer.second = pnode->m_last_block_time;
8243 NodeId to_disconnect = youngest_peer.first;
8244 if (youngest_peer.second > next_youngest_peer.second) {
8247 to_disconnect = next_youngest_peer.first;
8259 CNodeState *node_state = State(pnode->
GetId());
8260 if (node_state ==
nullptr ||
8262 node_state->vBlocksInFlight.empty())) {
8265 "disconnecting extra block-relay-only peer=%d "
8266 "(last block received at time %d)\n",
8273 "keeping block-relay-only peer=%d chosen for eviction "
8274 "(connect time: %d, blocks_in_flight: %d)\n",
8276 node_state->vBlocksInFlight.size());
8292 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
8303 CNodeState *state = State(pnode->
GetId());
8304 if (state ==
nullptr) {
8309 if (state->m_chain_sync.m_protect) {
8312 if (state->m_last_block_announcement < oldest_block_announcement ||
8313 (state->m_last_block_announcement == oldest_block_announcement &&
8314 pnode->
GetId() > worst_peer)) {
8315 worst_peer = pnode->
GetId();
8316 oldest_block_announcement = state->m_last_block_announcement;
8320 if (worst_peer == -1) {
8324 bool disconnected = m_connman.
ForNode(
8332 CNodeState &state = *State(pnode->
GetId());
8334 state.vBlocksInFlight.empty()) {
8336 "disconnecting extra outbound peer=%d (last block "
8337 "announcement received at time %d)\n",
8338 pnode->
GetId(), oldest_block_announcement);
8343 "keeping outbound peer=%d chosen for eviction "
8344 "(connect time: %d, blocks_in_flight: %d)\n",
8346 state.vBlocksInFlight.size());
8361void PeerManagerImpl::CheckForStaleTipAndEvictPeers() {
8364 auto now{GetTime<std::chrono::seconds>()};
8366 EvictExtraOutboundPeers(now);
8368 if (now > m_stale_tip_check_time) {
8374 LogPrintf(
"Potential stale tip detected, will try using extra "
8375 "outbound peer (last tip update: %d seconds ago)\n",
8384 if (!m_initial_sync_finished && CanDirectFetch()) {
8386 m_initial_sync_finished =
true;
8390void PeerManagerImpl::MaybeSendPing(
CNode &node_to, Peer &peer,
8391 std::chrono::microseconds now) {
8393 node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
8394 peer.m_ping_nonce_sent &&
8405 bool pingSend =
false;
8407 if (peer.m_ping_queued) {
8412 if (peer.m_ping_nonce_sent == 0 &&
8422 }
while (nonce == 0);
8423 peer.m_ping_queued =
false;
8424 peer.m_ping_start = now;
8426 peer.m_ping_nonce_sent = nonce;
8431 peer.m_ping_nonce_sent = 0;
8437void PeerManagerImpl::MaybeSendAddr(
CNode &
node, Peer &peer,
8438 std::chrono::microseconds current_time) {
8440 if (!peer.m_addr_relay_enabled) {
8444 LOCK(peer.m_addr_send_times_mutex);
8446 peer.m_next_local_addr_send < current_time) {
8453 if (peer.m_next_local_addr_send != 0us) {
8454 peer.m_addr_known->reset();
8457 CAddress local_addr{*local_service, peer.m_our_services,
8458 Now<NodeSeconds>()};
8459 PushAddress(peer, local_addr);
8461 peer.m_next_local_addr_send =
8467 if (current_time <= peer.m_next_addr_send) {
8471 peer.m_next_addr_send =
8474 const size_t max_addr_to_send = m_opts.max_addr_to_send;
8475 if (!
Assume(peer.m_addrs_to_send.size() <= max_addr_to_send)) {
8478 peer.m_addrs_to_send.resize(max_addr_to_send);
8483 auto addr_already_known =
8486 bool ret = peer.m_addr_known->contains(addr.
GetKey());
8488 peer.m_addr_known->insert(addr.
GetKey());
8492 peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(),
8493 peer.m_addrs_to_send.end(),
8494 addr_already_known),
8495 peer.m_addrs_to_send.end());
8498 if (peer.m_addrs_to_send.empty()) {
8502 const char *msg_type;
8504 if (peer.m_wants_addrv2) {
8514 peer.m_addrs_to_send));
8515 peer.m_addrs_to_send.clear();
8518 if (peer.m_addrs_to_send.capacity() > 40) {
8519 peer.m_addrs_to_send.shrink_to_fit();
8523void PeerManagerImpl::MaybeSendSendHeaders(
CNode &
node, Peer &peer) {
8528 if (!peer.m_sent_sendheaders &&
8531 CNodeState &state = *State(
node.GetId());
8532 if (state.pindexBestKnownBlock !=
nullptr &&
8533 state.pindexBestKnownBlock->nChainWork >
8540 peer.m_sent_sendheaders =
true;
8545void PeerManagerImpl::MaybeSendFeefilter(
8546 CNode &pto, Peer &peer, std::chrono::microseconds current_time) {
8547 if (m_opts.ignore_incoming_txs) {
8571 static const Amount MAX_FILTER{m_fee_filter_rounder.round(
MAX_MONEY)};
8572 if (peer.m_fee_filter_sent == MAX_FILTER) {
8575 peer.m_next_send_feefilter = 0us;
8578 if (current_time > peer.m_next_send_feefilter) {
8579 Amount filterToSend = m_fee_filter_rounder.round(currentFilter);
8583 if (filterToSend != peer.m_fee_filter_sent) {
8585 peer.m_fee_filter_sent = filterToSend;
8587 peer.m_next_send_feefilter =
8595 peer.m_next_send_feefilter &&
8596 (currentFilter < 3 * peer.m_fee_filter_sent / 4 ||
8597 currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
8598 peer.m_next_send_feefilter =
8606class CompareInvMempoolOrder {
8610 explicit CompareInvMempoolOrder(
CTxMemPool *_mempool) : mp(_mempool) {}
8612 bool operator()(std::set<TxId>::iterator a, std::set<TxId>::iterator b) {
8622bool PeerManagerImpl::RejectIncomingTxs(
const CNode &peer)
const {
8631 if (m_opts.ignore_incoming_txs &&
8638bool PeerManagerImpl::SetupAddressRelay(
const CNode &
node, Peer &peer) {
8642 if (
node.IsBlockOnlyConn()) {
8646 if (!peer.m_addr_relay_enabled.exchange(
true)) {
8650 peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
8656bool PeerManagerImpl::SendMessages(
const Config &config,
CNode *pto) {
8659 PeerRef peer = GetPeerRef(pto->
GetId());
8668 if (MaybeDiscourageAndDisconnect(*pto, *peer)) {
8677 const auto current_time{GetTime<std::chrono::microseconds>()};
8682 "addrfetch connection timeout; disconnecting peer=%d\n",
8688 MaybeSendPing(*pto, *peer, current_time);
8695 bool sync_blocks_and_headers_from_peer =
false;
8697 MaybeSendAddr(*pto, *peer, current_time);
8699 MaybeSendSendHeaders(*pto, *peer);
8704 CNodeState &state = *State(pto->
GetId());
8707 if (m_chainman.m_best_header ==
nullptr) {
8714 if (state.fPreferredDownload) {
8715 sync_blocks_and_headers_from_peer =
true;
8726 if (m_num_preferred_download_peers == 0 ||
8727 mapBlocksInFlight.empty()) {
8728 sync_blocks_and_headers_from_peer =
true;
8732 if (!state.fSyncStarted && CanServeBlocks(*peer) &&
8736 if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) ||
8738 const CBlockIndex *pindexStart = m_chainman.m_best_header;
8747 if (pindexStart->
pprev) {
8748 pindexStart = pindexStart->
pprev;
8750 if (MaybeSendGetHeaders(*pto,
GetLocator(pindexStart), *peer)) {
8753 "initial getheaders (%d) to peer=%d (startheight:%d)\n",
8755 peer->m_starting_height);
8757 state.fSyncStarted =
true;
8758 peer->m_headers_sync_timeout =
8763 std::chrono::microseconds{
8765 Ticks<std::chrono::seconds>(
8767 m_chainman.m_best_header->Time()) /
8784 LOCK(peer->m_block_inv_mutex);
8785 std::vector<CBlock> vHeaders;
8787 ((!peer->m_prefers_headers &&
8788 (!state.m_requested_hb_cmpctblocks ||
8789 peer->m_blocks_for_headers_relay.size() > 1)) ||
8790 peer->m_blocks_for_headers_relay.size() >
8795 ProcessBlockAvailability(pto->
GetId());
8797 if (!fRevertToInv) {
8798 bool fFoundStartingHeader =
false;
8802 for (
const BlockHash &hash : peer->m_blocks_for_headers_relay) {
8808 fRevertToInv =
true;
8811 if (pBestIndex !=
nullptr && pindex->
pprev != pBestIndex) {
8822 fRevertToInv =
true;
8825 pBestIndex = pindex;
8826 if (fFoundStartingHeader) {
8829 }
else if (PeerHasHeader(&state, pindex)) {
8832 }
else if (pindex->
pprev ==
nullptr ||
8833 PeerHasHeader(&state, pindex->
pprev)) {
8836 fFoundStartingHeader =
true;
8841 fRevertToInv =
true;
8846 if (!fRevertToInv && !vHeaders.empty()) {
8847 if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
8852 "%s sending header-and-ids %s to peer=%d\n",
8853 __func__, vHeaders.front().GetHash().ToString(),
8856 std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
8858 LOCK(m_most_recent_block_mutex);
8859 if (m_most_recent_block_hash ==
8861 cached_cmpctblock_msg =
8863 *m_most_recent_compact_block);
8866 if (cached_cmpctblock_msg.has_value()) {
8868 std::move(cached_cmpctblock_msg.value()));
8872 block, *pBestIndex)};
8879 state.pindexBestHeaderSent = pBestIndex;
8880 }
else if (peer->m_prefers_headers) {
8881 if (vHeaders.size() > 1) {
8883 "%s: %u headers, range (%s, %s), to peer=%d\n",
8884 __func__, vHeaders.size(),
8885 vHeaders.front().GetHash().ToString(),
8886 vHeaders.back().GetHash().ToString(),
8890 "%s: sending header %s to peer=%d\n", __func__,
8891 vHeaders.front().GetHash().ToString(),
8895 state.pindexBestHeaderSent = pBestIndex;
8897 fRevertToInv =
true;
8904 if (!peer->m_blocks_for_headers_relay.empty()) {
8906 peer->m_blocks_for_headers_relay.back();
8917 "Announcing block %s not on main chain (tip=%s)\n",
8926 if (!PeerHasHeader(&state, pindex)) {
8927 peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
8929 "%s: sending inv peer=%d hash=%s\n", __func__,
8934 peer->m_blocks_for_headers_relay.clear();
8941 std::vector<CInv> vInv;
8942 auto addInvAndMaybeFlush = [&](uint32_t type,
const uint256 &hash) {
8943 vInv.emplace_back(type, hash);
8954 LOCK(peer->m_block_inv_mutex);
8956 vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(),
8962 for (
const BlockHash &hash : peer->m_blocks_for_inv_relay) {
8965 peer->m_blocks_for_inv_relay.clear();
8968 auto computeNextInvSendTime =
8969 [&](std::chrono::microseconds &next)
8973 if (next < current_time) {
8974 fSendTrickle =
true;
8976 next = NextInvToInbounds(
8981 next = current_time;
8985 return fSendTrickle;
8989 if (peer->m_proof_relay !=
nullptr) {
8990 LOCK(peer->m_proof_relay->m_proof_inventory_mutex);
8992 if (computeNextInvSendTime(
8993 peer->m_proof_relay->m_next_inv_send_time)) {
8995 peer->m_proof_relay->m_proof_inventory_to_send.begin();
8997 peer->m_proof_relay->m_proof_inventory_to_send.end()) {
9000 it = peer->m_proof_relay->m_proof_inventory_to_send.erase(
9003 if (peer->m_proof_relay->m_proof_inventory_known_filter
9004 .contains(proofid)) {
9008 peer->m_proof_relay->m_proof_inventory_known_filter.insert(
9011 peer->m_proof_relay->m_recently_announced_proofs.insert(
9017 if (
auto tx_relay = peer->GetTxRelay()) {
9018 LOCK(tx_relay->m_tx_inventory_mutex);
9020 const bool fSendTrickle =
9021 computeNextInvSendTime(tx_relay->m_next_inv_send_time);
9026 LOCK(tx_relay->m_bloom_filter_mutex);
9027 if (!tx_relay->m_relay_txs) {
9028 tx_relay->m_tx_inventory_to_send.clear();
9033 if (fSendTrickle && tx_relay->m_send_mempool) {
9034 auto vtxinfo = m_mempool.
infoAll();
9035 tx_relay->m_send_mempool =
false;
9037 tx_relay->m_fee_filter_received.load()};
9039 LOCK(tx_relay->m_bloom_filter_mutex);
9041 for (
const auto &txinfo : vtxinfo) {
9042 const TxId &txid = txinfo.tx->GetId();
9043 tx_relay->m_tx_inventory_to_send.erase(txid);
9046 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
9049 if (tx_relay->m_bloom_filter &&
9050 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
9054 tx_relay->m_tx_inventory_known_filter.insert(txid);
9057 addInvAndMaybeFlush(
MSG_TX, txid);
9059 tx_relay->m_last_mempool_req =
9060 std::chrono::duration_cast<std::chrono::seconds>(
9067 std::vector<std::set<TxId>::iterator> vInvTx;
9068 vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
9069 for (std::set<TxId>::iterator it =
9070 tx_relay->m_tx_inventory_to_send.begin();
9071 it != tx_relay->m_tx_inventory_to_send.end(); it++) {
9072 vInvTx.push_back(it);
9075 tx_relay->m_fee_filter_received.load()};
9080 CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool);
9081 std::make_heap(vInvTx.begin(), vInvTx.end(),
9082 compareInvMempoolOrder);
9086 unsigned int nRelayedTransactions = 0;
9087 LOCK(tx_relay->m_bloom_filter_mutex);
9088 while (!vInvTx.empty() &&
9093 std::pop_heap(vInvTx.begin(), vInvTx.end(),
9094 compareInvMempoolOrder);
9095 std::set<TxId>::iterator it = vInvTx.back();
9097 const TxId txid = *it;
9099 tx_relay->m_tx_inventory_to_send.erase(it);
9101 if (tx_relay->m_tx_inventory_known_filter.contains(txid) &&
9102 tx_relay->m_avalanche_stalled_txids.count(txid) == 0) {
9106 auto txinfo = m_mempool.
info(txid);
9112 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
9115 if (tx_relay->m_bloom_filter &&
9116 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
9121 tx_relay->m_recently_announced_invs.insert(txid);
9122 addInvAndMaybeFlush(
MSG_TX, txid);
9123 nRelayedTransactions++;
9124 tx_relay->m_tx_inventory_known_filter.insert(txid);
9125 tx_relay->m_avalanche_stalled_txids.erase(txid);
9131 if (!vInv.empty()) {
9138 CNodeState &state = *State(pto->
GetId());
9141 auto stalling_timeout = m_block_stalling_timeout.load();
9142 if (state.m_stalling_since.count() &&
9143 state.m_stalling_since < current_time - stalling_timeout) {
9148 LogPrintf(
"Peer=%d is stalling block download, disconnecting\n",
9153 const auto new_timeout =
9155 if (stalling_timeout != new_timeout &&
9156 m_block_stalling_timeout.compare_exchange_strong(
9157 stalling_timeout, new_timeout)) {
9160 "Increased stalling timeout temporarily to %d seconds\n",
9172 if (state.vBlocksInFlight.size() > 0) {
9173 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
9174 int nOtherPeersWithValidatedDownloads =
9175 m_peers_downloading_from - 1;
9177 state.m_downloading_since +
9178 std::chrono::seconds{consensusParams.nPowTargetSpacing} *
9181 nOtherPeersWithValidatedDownloads)) {
9182 LogPrintf(
"Timeout downloading block %s from peer=%d, "
9184 queuedBlock.pindex->GetBlockHash().ToString(),
9192 if (state.fSyncStarted &&
9193 peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
9196 if (current_time > peer->m_headers_sync_timeout &&
9197 nSyncStarted == 1 &&
9198 (m_num_preferred_download_peers -
9199 state.fPreferredDownload >=
9208 LogPrintf(
"Timeout downloading headers from peer=%d, "
9214 LogPrintf(
"Timeout downloading headers from noban "
9215 "peer=%d, not disconnecting\n",
9221 state.fSyncStarted =
false;
9223 peer->m_headers_sync_timeout = 0us;
9229 peer->m_headers_sync_timeout = std::chrono::microseconds::max();
9235 ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
9238 std::vector<CInv> vGetData;
9246 CNodeState &state = *State(pto->
GetId());
9248 if (CanServeBlocks(*peer) &&
9249 ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) ||
9252 std::vector<const CBlockIndex *> vToDownload;
9254 auto get_inflight_budget = [&state]() {
9257 static_cast<int>(state.vBlocksInFlight.size()));
9263 FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload,
9266 !IsLimitedPeer(*peer)) {
9272 m_chainman.GetSnapshotBaseBlock());
9274 TryDownloadingHistoricalBlocks(
9275 *peer, get_inflight_budget(), vToDownload, from_tip,
9276 Assert(m_chainman.GetSnapshotBaseBlock()));
9280 BlockRequested(config, pto->
GetId(), *pindex);
9285 if (state.vBlocksInFlight.empty() && staller != -1) {
9286 if (State(staller)->m_stalling_since == 0us) {
9287 State(staller)->m_stalling_since = current_time;
9294 auto addGetDataAndMaybeFlush = [&](uint32_t type,
const uint256 &hash) {
9295 CInv inv(type, hash);
9298 vGetData.push_back(std::move(inv));
9309 LOCK(cs_proofrequest);
9310 std::vector<std::pair<NodeId, avalanche::ProofId>> expired;
9312 m_proofrequest.GetRequestable(pto->
GetId(), current_time, &expired);
9313 for (
const auto &entry : expired) {
9315 "timeout of inflight proof %s from peer=%d\n",
9316 entry.second.ToString(), entry.first);
9318 for (
const auto &proofid : requestable) {
9319 if (!AlreadyHaveProof(proofid)) {
9321 m_proofrequest.RequestedData(
9322 pto->
GetId(), proofid,
9329 m_proofrequest.ForgetInvId(proofid);
9339 std::vector<std::pair<NodeId, TxId>> expired;
9341 m_txrequest.GetRequestable(pto->
GetId(), current_time, &expired);
9342 for (
const auto &entry : expired) {
9344 entry.second.ToString(), entry.first);
9346 for (
const TxId &txid : requestable) {
9350 if (!AlreadyHaveTx(txid,
false)) {
9351 addGetDataAndMaybeFlush(
MSG_TX, txid);
9352 m_txrequest.RequestedData(
9359 m_txrequest.ForgetInvId(txid);
9363 if (!vGetData.empty()) {
9368 MaybeSendFeefilter(*pto, *peer, current_time);
9372bool PeerManagerImpl::ReceivedAvalancheProof(
CNode &
node, Peer &peer,
9375 LogError(
"ReceivedAvalancheProof: proof is null\n");
9381 AddKnownProof(peer, proofid);
9393 return node.m_avalanche_pubkey.has_value());
9394 auto saveProofIfStaker = [
this, isStaker](
const CNode &
node,
9396 const NodeId nodeid) ->
bool {
9408 LOCK(cs_proofrequest);
9409 m_proofrequest.ReceivedResponse(nodeid, proofid);
9411 if (AlreadyHaveProof(proofid)) {
9412 m_proofrequest.ForgetInvId(proofid);
9413 saveProofIfStaker(
node, proofid, nodeid);
9423 return pm.registerProof(proof, state);
9425 WITH_LOCK(cs_proofrequest, m_proofrequest.ForgetInvId(proofid));
9426 RelayProof(proofid);
9428 node.m_last_proof_time = GetTime<std::chrono::seconds>();
9431 nodeid, proofid.ToString());
9453 "Not polling the avalanche proof (%s): peer=%d, proofid %s\n",
9454 state.
IsValid() ?
"not-worth-polling"
9456 nodeid, proofid.ToString());
9459 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.
#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 kilobyte: Amount / kB.
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
void TransactionInvalidated(const CTransactionRef &tx, std::shared_ptr< const std::vector< Coin > > spent_coins)
Used to create a Merkle proof (usually from a subset of transactions), which consists of a block head...
std::vector< std::pair< size_t, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
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
std::chrono::seconds m_nextGetAvaAddr
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.
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 CompareTopologically(const TxId &txida, const TxId &txidb) const
TxMempoolInfo info(const TxId &txid) const
size_t DynamicMemoryUsage() const
bool setAvalancheFinalized(const CTxMemPoolEntryRef &tx, const Consensus::Params ¶ms, const CBlockIndex &active_chain_tip, std::vector< TxId > &finalizedTxIds) EXCLUSIVE_LOCKS_REQUIRED(bool isAvalancheFinalizedPreConsensus(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
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)
const CFeeRate m_min_relay_feerate
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 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.
size_t Count(NodeId peer) const
Count how many announcements a peer has (REQUESTED, CANDIDATE, and COMPLETED combined).
size_t CountInFlight(NodeId peer) const
Count how many REQUESTED announcements a peer has.
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 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 bool IgnoresIncomingTxs()=0
Whether this node ignores txs received over p2p.
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.
int EraseTx(const TxId &txid) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase a tx by txid.
void EraseForPeer(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase all txs announced by a peer (eg, after that peer disconnects)
std::vector< CTransactionRef > GetChildrenFromSamePeer(const CTransactionRef &parent, NodeId nodeid) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get all children that spend from this tx and were received from nodeid.
bool AddTx(const CTransactionRef &tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Add a new transaction to the pool.
unsigned int LimitTxs(unsigned int max_txs, FastRandomContext &rng) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Limit the txs to the given maximum.
void EraseForBlock(const CBlock &block) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Erase all txs included in or invalidated by a new block.
std::vector< CTransactionRef > GetConflictTxs(const CTransactionRef &tx) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void AddChildrenToWorkSet(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Add any tx that list a particular tx as a parent into the from peer's work set.
std::vector< std::pair< CTransactionRef, NodeId > > GetChildrenFromDifferentPeer(const CTransactionRef &parent, NodeId nodeid) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get all children that spend from this tx but were not received from nodeid.
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 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
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 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
bool isPreconsensusActivated(const CBlockIndex *pprev) const
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)
std::vector< uint32_t > indices
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.
static const uint256 ZERO
@ 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.
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 LogPrint(category,...)
#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
Implement std::hash so RCUPtr can be used as a key for maps or sets.
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 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 std::chrono::microseconds ComputeRequestTime(const CNode &node, const InvRequestTracker< InvId > &requestTracker, const DataRequestParameters &requestParams, std::chrono::microseconds current_time, bool preferred)
Compute the request time for this announcement, current time plus delays for:
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for inbound peers.
static constexpr DataRequestParameters TX_REQUEST_PARAMS
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY
Maximum feefilter broadcast delay after significant change.
static constexpr uint32_t MAX_GETCFILTERS_SIZE
Maximum number of compact filters that may be requested with one getcfilters.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE
Headers download timeout.
static const unsigned int MAX_GETDATA_SZ
Limit to avoid sending big packets.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in multiples of the block interval (i.e.
static constexpr auto AVALANCHE_AVAPROOFS_TIMEOUT
If no proof was requested from a compact proof message after this timeout expired,...
static constexpr auto STALE_CHECK_INTERVAL
How frequently to check for stale tips.
static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY
The number of most recently announced transactions a peer can request.
static constexpr auto UNCONDITIONAL_RELAY_DELAY
How long a transaction has to be in the mempool before it can unconditionally be relayed.
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL
Average delay between peer address broadcasts.
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
Additional block download timeout per parallel downloading peer (i.e.
static constexpr double MAX_ADDR_RATE_PER_SECOND
The maximum rate of address records we're willing to process on average.
static constexpr auto PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive.
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested.
static constexpr DataRequestParameters PROOF_REQUEST_PARAMS
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
static bool TooManyAnnouncements(const CNode &node, const InvRequestTracker< InvId > &requestTracker, const DataRequestParameters &requestParams)
static constexpr uint32_t MAX_GETCFHEADERS_SIZE
Maximum number of cf hashes that may be requested with one getcfheaders.
static constexpr auto BLOCK_STALLING_TIMEOUT_MAX
Maximum timeout for stalling block download.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY
SHA256("main address relay")[0:8].
static constexpr size_t MAX_PCT_ADDR_TO_SEND
the maximum percentage of addresses from our addrman to return in response to a getaddr message.
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND
Maximum rate of inventory items to send per second.
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of address records permitted in an ADDR message.
static const unsigned int MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK
Maximum number of outstanding CMPCTBLOCK requests for the same block.
static const 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.
uint256 GetPackageHash(const Package &package)
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
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 SHORT_IDS_BLOCKS_VERSION
short-id-based block download starts with this version
static const int SENDHEADERS_VERSION
"sendheaders" command and announcing blocks with headers starts with this version
static const int PROTOCOL_VERSION
network protocol versioning
static const int FEEFILTER_VERSION
"feefilter" tells peers to filter invs to you by fee starts with this version
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
static const int INVALID_CB_NO_BAN_VERSION
not banning for invalid compact blocks starts with this version
static const int BIP0031_VERSION
BIP 0031, pong message, is enabled for all versions AFTER this one.
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
static std::string ToString(const CService &ip)
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 std::chrono::seconds overloaded_peer_delay
How long to delay requesting data from overloaded peers (see max_peer_request_in_flight).
const size_t max_peer_announcements
Maximum number of inventories to consider for requesting, per peer.
const std::chrono::seconds nonpref_peer_delay
How long to delay requesting data from non-preferred peers.
const NetPermissionFlags bypass_request_limits_permissions
Permission flags a peer requires to bypass the request limits tracking limits and delay penalty.
const std::chrono::microseconds getdata_interval
How long to wait (in microseconds) before a data request from an additional peer.
const size_t max_peer_request_in_flight
Maximum number of in-flight data requests from a peer.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
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
const ProofId & getProofId() const
StakeContenderIds are unique for each block to ensure that the peer polling for their acceptance has ...
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
#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.
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
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.
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...
CMainSignals & GetMainSignals()