57#include <boost/multi_index/hashed_index.hpp>
58#include <boost/multi_index/member.hpp>
59#include <boost/multi_index/ordered_index.hpp>
60#include <boost/multi_index_container.hpp>
72#include <unordered_set>
121 "Max protocol message length must be greater than largest "
122 "possible INV message");
154 .max_peer_announcements = 5000,
155 .nonpref_peer_delay = 2s,
156 .overloaded_peer_delay = 2s,
157 .getdata_interval = 60s,
158 .bypass_request_limits_permissions =
190 "MAX_BLOCKTXN_DEPTH too high");
249 std::chrono::seconds{1},
250 "INVENTORY_RELAY_MAX too low");
301 std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
306 std::chrono::seconds timeAdded;
308 StalledTxId(
TxId txid_, std::chrono::seconds timeAdded_)
309 : txid(txid_), timeAdded(timeAdded_) {};
315using StalledTxIdSet = boost::multi_index_container<
317 boost::multi_index::indexed_by<
319 boost::multi_index::hashed_unique<
320 boost::multi_index::tag<by_txid>,
321 boost::multi_index::member<StalledTxId, TxId, &StalledTxId::txid>,
324 boost::multi_index::ordered_non_unique<
325 boost::multi_index::tag<by_time>,
326 boost::multi_index::member<StalledTxId, std::chrono::seconds,
327 &StalledTxId::timeAdded>>>>;
364 std::atomic<ServiceFlags> m_their_services{
NODE_NONE};
367 Mutex m_misbehavior_mutex;
372 bool m_should_discourage
GUARDED_BY(m_misbehavior_mutex){
false};
375 Mutex m_block_inv_mutex;
381 std::vector<BlockHash> m_blocks_for_inv_relay
GUARDED_BY(m_block_inv_mutex);
387 std::vector<BlockHash>
388 m_blocks_for_headers_relay
GUARDED_BY(m_block_inv_mutex);
399 std::atomic<int> m_starting_height{-1};
402 std::atomic<uint64_t> m_ping_nonce_sent{0};
404 std::atomic<std::chrono::microseconds> m_ping_start{0us};
406 std::atomic<bool> m_ping_queued{
false};
416 std::chrono::microseconds m_next_send_feefilter
429 bool m_relay_txs
GUARDED_BY(m_bloom_filter_mutex){
false};
434 std::unique_ptr<CBloomFilter>
450 GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
456 std::set<TxId> m_tx_inventory_to_send
GUARDED_BY(m_tx_inventory_mutex);
462 bool m_send_mempool
GUARDED_BY(m_tx_inventory_mutex){
false};
464 std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
469 std::chrono::microseconds
470 m_next_inv_send_time
GUARDED_BY(m_tx_inventory_mutex){0};
476 std::atomic<Amount> m_fee_filter_received{
Amount::zero()};
482 m_avalanche_stalled_txids
GUARDED_BY(m_tx_inventory_mutex);
490 LOCK(m_tx_relay_mutex);
492 m_tx_relay = std::make_unique<Peer::TxRelay>();
493 return m_tx_relay.get();
497 return WITH_LOCK(m_tx_relay_mutex,
return m_tx_relay.get());
499 const TxRelay *GetTxRelay() const
501 return WITH_LOCK(m_tx_relay_mutex,
return m_tx_relay.get());
506 std::set<avalanche::ProofId>
507 m_proof_inventory_to_send
GUARDED_BY(m_proof_inventory_mutex);
510 GUARDED_BY(m_proof_inventory_mutex){10000, 0.000001};
517 std::chrono::microseconds m_next_inv_send_time{0};
521 std::atomic<std::chrono::seconds> lastSharedProofsUpdate{0s};
522 std::atomic<bool> compactproofs_requested{
false};
529 const std::unique_ptr<ProofRelay> m_proof_relay;
548 std::vector<std::chrono::seconds> m_invalid_avaproof_times
554 std::vector<CAddress>
566 std::unique_ptr<CRollingBloomFilter>
584 std::atomic_bool m_addr_relay_enabled{
false};
588 mutable Mutex m_addr_send_times_mutex;
590 std::chrono::microseconds
591 m_next_addr_send
GUARDED_BY(m_addr_send_times_mutex){0};
593 std::chrono::microseconds
594 m_next_local_addr_send
GUARDED_BY(m_addr_send_times_mutex){0};
599 std::atomic_bool m_wants_addrv2{
false};
603 mutable Mutex m_addr_token_bucket_mutex;
608 double m_addr_token_bucket
GUARDED_BY(m_addr_token_bucket_mutex){1.0};
610 std::chrono::microseconds
612 GetTime<std::chrono::microseconds>()};
614 std::atomic<uint64_t> m_addr_rate_limited{0};
619 std::atomic<uint64_t> m_addr_processed{0};
625 bool m_inv_triggered_getheaders_before_sync
629 Mutex m_getdata_requests_mutex;
631 std::deque<CInv> m_getdata_requests
GUARDED_BY(m_getdata_requests_mutex);
638 Mutex m_headers_sync_mutex;
643 std::unique_ptr<HeadersSyncState>
648 std::atomic<bool> m_sent_sendheaders{
false};
651 std::chrono::microseconds m_headers_sync_timeout
662 : m_id(id), m_our_services{our_services},
663 m_proof_relay(fRelayProofs ?
std::make_unique<ProofRelay>()
669 mutable Mutex m_tx_relay_mutex;
672 std::unique_ptr<TxRelay> m_tx_relay
GUARDED_BY(m_tx_relay_mutex);
675using PeerRef = std::shared_ptr<Peer>;
693 bool fSyncStarted{
false};
696 std::chrono::microseconds m_stalling_since{0us};
697 std::list<QueuedBlock> vBlocksInFlight;
700 std::chrono::microseconds m_downloading_since{0us};
702 bool fPreferredDownload{
false};
707 bool m_requested_hb_cmpctblocks{
false};
709 bool m_provides_cmpctblocks{
false};
737 struct ChainSyncTimeoutState {
740 std::chrono::seconds m_timeout{0s};
744 bool m_sent_getheaders{
false};
747 bool m_protect{
false};
750 ChainSyncTimeoutState m_chain_sync;
753 int64_t m_last_block_announcement{0};
756 const bool m_is_inbound;
758 CNodeState(
bool is_inbound) : m_is_inbound(is_inbound) {}
771 const std::shared_ptr<const CBlock> &pblock,
779 bool fInitialDownload)
override
785 const std::shared_ptr<const CBlock> &pblock)
override
794 !m_headers_presync_mutex,
795 !m_tx_download_mutex);
797 std::atomic<bool> &interrupt)
override
800 !m_most_recent_block_mutex, !cs_proofrequest,
801 !m_headers_presync_mutex, g_msgproc_mutex,
802 !m_tx_download_mutex);
806 !m_most_recent_block_mutex, !cs_proofrequest,
807 g_msgproc_mutex, !m_tx_download_mutex);
812 std::optional<std::string>
819 bool IgnoresIncomingTxs()
override {
return m_opts.ignore_incoming_txs; }
821 void RelayTransaction(const
TxId &txid) override
823 void RelayProof(const
avalanche::ProofId &proofid) override
825 void SetBestHeight(
int height)
override { m_best_height = height; };
828 Misbehaving(*
Assert(GetPeerRef(peer_id)),
"");
831 const std::string &msg_type,
DataStream &vRecv,
832 const std::chrono::microseconds time_received,
833 const std::atomic<bool> &interruptMsgProc)
override
836 !m_most_recent_block_mutex, !cs_proofrequest,
837 !m_headers_presync_mutex, g_msgproc_mutex,
838 !m_tx_download_mutex);
840 int64_t time_in_seconds)
override;
847 void ConsiderEviction(
CNode &pto, Peer &peer,
848 std::chrono::seconds time_in_seconds)
855 void EvictExtraOutboundPeers(std::chrono::seconds now)
862 void ReattemptInitialBroadcast(
CScheduler &scheduler)
868 void UpdateAvalancheStatistics()
const;
873 void AvalanchePeriodicNetworking(
CScheduler &scheduler)
const;
891 void Misbehaving(Peer &peer,
const std::string &message);
903 void MaybePunishNodeForBlock(
NodeId nodeid,
905 bool via_compact_block,
906 const std::string &message =
"")
914 const
std::
string &message = "")
926 bool MaybeDiscourageAndDisconnect(
CNode &pnode, Peer &peer);
948 std::optional<
node::PackageToValidate>
952 m_tx_download_mutex);
961 m_tx_download_mutex);
969 ProcessPackageResult(const
node::PackageToValidate &package_to_validate,
972 m_tx_download_mutex);
989 bool ProcessOrphanTx(const
Config &config, Peer &peer)
991 !m_tx_download_mutex);
1003 void ProcessHeadersMessage(const
Config &config,
CNode &pfrom, Peer &peer,
1005 bool via_compact_block)
1025 void HandleUnconnectingHeaders(
CNode &pfrom, Peer &peer,
1030 CheckHeadersAreContinuous(const
std::vector<
CBlockHeader> &headers) const;
1050 bool IsContinuationOfLowWorkHeadersSync(Peer &peer,
CNode &pfrom,
1053 !m_headers_presync_mutex, g_msgproc_mutex);
1067 bool TryLowWorkHeadersSync(Peer &peer,
CNode &pfrom,
1071 !m_headers_presync_mutex, g_msgproc_mutex);
1077 bool IsAncestorOfBestHeaderOrTip(const
CBlockIndex *header)
1091 void HeadersDirectFetchBlocks(const
Config &config,
CNode &pfrom,
1094 void UpdatePeerStateForReceivedHeaders(
CNode &pfrom, Peer &peer,
1096 bool received_new_header,
1097 bool may_have_more_headers)
1100 void SendBlockTransactions(
CNode &pfrom, Peer &peer, const
CBlock &block,
1110 std::chrono::microseconds current_time,
bool preferred)
1115 m_connman.PushMessage(&
node, std::move(msg));
1117 template <
typename... Args>
1118 void MakeAndPushMessage(
CNode &
node, std::string msg_type,
1119 Args &&...args)
const {
1121 std::forward<Args>(args)...));
1125 void PushNodeVersion(
const Config &config,
CNode &pnode,
const Peer &peer);
1133 void MaybeSendPing(
CNode &node_to, Peer &peer,
1134 std::chrono::microseconds now);
1137 void MaybeSendAddr(
CNode &
node, Peer &peer,
1138 std::chrono::microseconds current_time)
1145 void MaybeSendSendHeaders(
CNode &
node, Peer &peer)
1149 void MaybeSendFeefilter(
CNode &
node, Peer &peer,
1150 std::chrono::microseconds current_time)
1162 void RelayAddress(
NodeId originator,
const CAddress &addr,
bool fReachable)
1203 Mutex cs_proofrequest;
1208 std::atomic<int> m_best_height{-1};
1211 std::chrono::seconds m_stale_tip_check_time
GUARDED_BY(cs_main){0s};
1213 const Options m_opts;
1215 bool RejectIncomingTxs(
const CNode &peer)
const;
1221 bool m_initial_sync_finished
GUARDED_BY(cs_main){
false};
1227 mutable Mutex m_peer_mutex;
1234 std::map<NodeId, PeerRef> m_peer_map
GUARDED_BY(m_peer_mutex);
1237 std::map<NodeId, CNodeState> m_node_states
GUARDED_BY(cs_main);
1243 const CNodeState *State(
NodeId pnode)
const
1248 std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us};
1255 m_last_block_inv_triggering_headers_sync
GUARDED_BY(g_msgproc_mutex){};
1263 std::map<BlockHash, std::pair<NodeId, bool>>
1267 int m_outbound_peers_with_protect_from_disconnect
GUARDED_BY(cs_main) = 0;
1270 int m_num_preferred_download_peers
GUARDED_BY(cs_main){0};
1273 std::atomic<std::chrono::seconds> m_block_stalling_timeout{
1283 std::chrono::microseconds
1284 NextInvToInbounds(std::chrono::microseconds now,
1285 std::chrono::seconds average_interval)
1290 mutable Mutex m_most_recent_block_mutex;
1291 std::shared_ptr<const CBlock>
1292 m_most_recent_block
GUARDED_BY(m_most_recent_block_mutex);
1293 std::shared_ptr<const CBlockHeaderAndShortTxIDs>
1294 m_most_recent_compact_block
GUARDED_BY(m_most_recent_block_mutex);
1296 std::unique_ptr<const std::map<TxId, CTransactionRef>>
1297 m_most_recent_block_txs
GUARDED_BY(m_most_recent_block_mutex);
1302 Mutex m_headers_presync_mutex;
1313 using HeadersPresyncStats =
1314 std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>;
1316 std::map<NodeId, HeadersPresyncStats>
1317 m_headers_presync_stats
GUARDED_BY(m_headers_presync_mutex){};
1321 std::atomic_bool m_headers_presync_should_signal{
false};
1326 int m_highest_fast_announce
GUARDED_BY(::cs_main){0};
1329 bool IsBlockRequested(
const BlockHash &hash)
1333 bool IsBlockRequestedFromOutbound(
const BlockHash &hash)
1344 void RemoveBlockRequest(
const BlockHash &hash,
1345 std::optional<NodeId> from_peer)
1354 bool BlockRequested(
const Config &config,
NodeId nodeid,
1356 std::list<QueuedBlock>::iterator **pit =
nullptr)
1365 void FindNextBlocksToDownload(const Peer &peer,
unsigned int count,
1371 void TryDownloadingHistoricalBlocks(
1372 const Peer &peer,
unsigned int count,
1406 const Peer &peer, CNodeState *state,
1408 int nWindowEnd, const
CChain *activeChain =
nullptr,
1409 NodeId *nodeStaller =
nullptr)
1416 BlockDownloadMap mapBlocksInFlight
GUARDED_BY(cs_main);
1419 std::atomic<
std::chrono::seconds> m_last_tip_update{0s};
1426 const std::chrono::seconds mempool_req,
1427 const std::chrono::seconds now)
1432 void ProcessGetData(
const Config &config,
CNode &pfrom, Peer &peer,
1433 const std::atomic<bool> &interruptMsgProc)
1435 peer.m_getdata_requests_mutex,
1441 const std::shared_ptr<const CBlock> &block,
1442 bool force_processing,
bool min_pow_checked);
1445 void ProcessCompactBlockTxns(
const Config &config,
CNode &pfrom, Peer &peer,
1455 void MaybeSetPeerAsAnnouncingHeaderAndIDs(
NodeId nodeid)
1459 std::list<NodeId> lNodesAnnouncingHeaderAndIDs
GUARDED_BY(cs_main);
1462 int m_peers_downloading_from
GUARDED_BY(cs_main) = 0;
1474 std::vector<CTransactionRef>
1475 vExtraTxnForCompact
GUARDED_BY(g_msgproc_mutex);
1477 size_t vExtraTxnForCompactIt
GUARDED_BY(g_msgproc_mutex) = 0;
1482 void ProcessBlockAvailability(
NodeId nodeid)
1497 bool BlockRequestAllowed(const
CBlockIndex *pindex)
1499 bool AlreadyHaveBlock(const
BlockHash &block_hash)
1501 bool AlreadyHaveProof(const
avalanche::ProofId &proofid);
1502 void ProcessGetBlockData(const
Config &config,
CNode &pfrom, Peer &peer,
1525 bool PrepareBlockFilterRequest(
CNode &
node, Peer &peer,
1527 uint32_t start_height,
1529 uint32_t max_height_diff,
1571 uint32_t GetAvalancheVoteForBlock(const
BlockHash &hash) const
1592 bool SetupAddressRelay(const
CNode &
node, Peer &peer)
1595 void AddAddressKnown(Peer &peer, const
CAddress &addr)
1597 void PushAddress(Peer &peer, const
CAddress &addr)
1605 bool ReceivedAvalancheProof(
CNode &
node, Peer &peer,
1610 avalanche::ProofRef FindProofForGetData(const Peer &peer,
1612 const
std::chrono::seconds now)
1615 bool isPreferredDownloadPeer(const
CNode &pfrom);
1618const CNodeState *PeerManagerImpl::State(
NodeId pnode) const
1620 std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode);
1621 if (it == m_node_states.end()) {
1628CNodeState *PeerManagerImpl::State(
NodeId pnode)
1630 return const_cast<CNodeState *
>(std::as_const(*this).State(pnode));
1638static bool IsAddrCompatible(
const Peer &peer,
const CAddress &addr) {
1642void PeerManagerImpl::AddAddressKnown(Peer &peer,
const CAddress &addr) {
1643 assert(peer.m_addr_known);
1644 peer.m_addr_known->insert(addr.
GetKey());
1647void PeerManagerImpl::PushAddress(Peer &peer,
const CAddress &addr) {
1651 assert(peer.m_addr_known);
1652 if (addr.
IsValid() && !peer.m_addr_known->contains(addr.
GetKey()) &&
1653 IsAddrCompatible(peer, addr)) {
1654 if (peer.m_addrs_to_send.size() >= m_opts.max_addr_to_send) {
1655 peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] =
1658 peer.m_addrs_to_send.push_back(addr);
1663static void AddKnownTx(Peer &peer,
const TxId &txid) {
1664 auto tx_relay = peer.GetTxRelay();
1669 LOCK(tx_relay->m_tx_inventory_mutex);
1670 tx_relay->m_tx_inventory_known_filter.insert(txid);
1674 if (peer.m_proof_relay !=
nullptr) {
1675 LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
1676 peer.m_proof_relay->m_proof_inventory_known_filter.insert(proofid);
1680bool PeerManagerImpl::isPreferredDownloadPeer(
const CNode &pfrom) {
1682 const CNodeState *state = State(pfrom.
GetId());
1683 return state && state->fPreferredDownload;
1686static bool CanServeBlocks(
const Peer &peer) {
1694static bool IsLimitedPeer(
const Peer &peer) {
1699std::chrono::microseconds
1700PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
1701 std::chrono::seconds average_interval) {
1702 if (m_next_inv_to_inbounds.load() < now) {
1707 m_next_inv_to_inbounds =
1708 now + m_rng.rand_exp_duration(average_interval);
1710 return m_next_inv_to_inbounds;
1713bool PeerManagerImpl::IsBlockRequested(
const BlockHash &hash) {
1714 return mapBlocksInFlight.count(hash);
1717bool PeerManagerImpl::IsBlockRequestedFromOutbound(
const BlockHash &hash) {
1718 for (
auto range = mapBlocksInFlight.equal_range(hash);
1719 range.first != range.second; range.first++) {
1720 auto [nodeid, block_it] = range.first->second;
1721 CNodeState &nodestate = *
Assert(State(nodeid));
1722 if (!nodestate.m_is_inbound) {
1730void PeerManagerImpl::RemoveBlockRequest(
const BlockHash &hash,
1731 std::optional<NodeId> from_peer) {
1732 auto range = mapBlocksInFlight.equal_range(hash);
1733 if (range.first == range.second) {
1741 while (range.first != range.second) {
1742 auto [node_id, list_it] = range.first->second;
1744 if (from_peer && *from_peer != node_id) {
1749 CNodeState &state = *
Assert(State(node_id));
1751 if (state.vBlocksInFlight.begin() == list_it) {
1754 state.m_downloading_since =
1755 std::max(state.m_downloading_since,
1756 GetTime<std::chrono::microseconds>());
1758 state.vBlocksInFlight.erase(list_it);
1760 if (state.vBlocksInFlight.empty()) {
1762 m_peers_downloading_from--;
1764 state.m_stalling_since = 0us;
1766 range.first = mapBlocksInFlight.erase(range.first);
1770bool PeerManagerImpl::BlockRequested(
const Config &config,
NodeId nodeid,
1772 std::list<QueuedBlock>::iterator **pit) {
1775 CNodeState *state = State(nodeid);
1776 assert(state !=
nullptr);
1781 for (
auto range = mapBlocksInFlight.equal_range(hash);
1782 range.first != range.second; range.first++) {
1783 if (range.first->second.first == nodeid) {
1785 *pit = &range.first->second.second;
1792 RemoveBlockRequest(hash, nodeid);
1794 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(
1795 state->vBlocksInFlight.end(),
1796 {&block, std::unique_ptr<PartiallyDownloadedBlock>(
1797 pit ? new PartiallyDownloadedBlock(config, &m_mempool)
1799 if (state->vBlocksInFlight.size() == 1) {
1801 state->m_downloading_since = GetTime<std::chrono::microseconds>();
1802 m_peers_downloading_from++;
1805 auto itInFlight = mapBlocksInFlight.insert(
1806 std::make_pair(hash, std::make_pair(nodeid, it)));
1809 *pit = &itInFlight->second.second;
1815void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(
NodeId nodeid) {
1821 if (m_opts.ignore_incoming_txs) {
1825 CNodeState *nodestate = State(nodeid);
1830 if (!nodestate->m_provides_cmpctblocks) {
1833 int num_outbound_hb_peers = 0;
1834 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin();
1835 it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
1836 if (*it == nodeid) {
1837 lNodesAnnouncingHeaderAndIDs.erase(it);
1838 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
1841 CNodeState *state = State(*it);
1842 if (state !=
nullptr && !state->m_is_inbound) {
1843 ++num_outbound_hb_peers;
1846 if (nodestate->m_is_inbound) {
1849 if (lNodesAnnouncingHeaderAndIDs.size() >= 3 &&
1850 num_outbound_hb_peers == 1) {
1851 CNodeState *remove_node =
1852 State(lNodesAnnouncingHeaderAndIDs.front());
1853 if (remove_node !=
nullptr && !remove_node->m_is_inbound) {
1856 std::swap(lNodesAnnouncingHeaderAndIDs.front(),
1857 *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
1864 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
1868 lNodesAnnouncingHeaderAndIDs.front(), [
this](
CNode *pnodeStop) {
1869 MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT,
1871 CMPCTBLOCKS_VERSION);
1874 pnodeStop->m_bip152_highbandwidth_to = false;
1877 lNodesAnnouncingHeaderAndIDs.pop_front();
1884 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->
GetId());
1889bool PeerManagerImpl::TipMayBeStale() {
1892 if (m_last_tip_update.load() == 0s) {
1893 m_last_tip_update = GetTime<std::chrono::seconds>();
1895 return m_last_tip_update.load() <
1896 GetTime<std::chrono::seconds>() -
1899 mapBlocksInFlight.empty();
1902bool PeerManagerImpl::CanDirectFetch() {
1908static bool PeerHasHeader(CNodeState *state,
const CBlockIndex *pindex)
1910 if (state->pindexBestKnownBlock &&
1911 pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) {
1914 if (state->pindexBestHeaderSent &&
1915 pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) {
1921void PeerManagerImpl::ProcessBlockAvailability(
NodeId nodeid) {
1922 CNodeState *state = State(nodeid);
1923 assert(state !=
nullptr);
1925 if (!state->hashLastUnknownBlock.IsNull()) {
1929 if (state->pindexBestKnownBlock ==
nullptr ||
1930 pindex->
nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1931 state->pindexBestKnownBlock = pindex;
1933 state->hashLastUnknownBlock.SetNull();
1938void PeerManagerImpl::UpdateBlockAvailability(
NodeId nodeid,
1940 CNodeState *state = State(nodeid);
1941 assert(state !=
nullptr);
1943 ProcessBlockAvailability(nodeid);
1948 if (state->pindexBestKnownBlock ==
nullptr ||
1949 pindex->
nChainWork >= state->pindexBestKnownBlock->nChainWork) {
1950 state->pindexBestKnownBlock = pindex;
1955 state->hashLastUnknownBlock = hash;
1961void PeerManagerImpl::FindNextBlocksToDownload(
1962 const Peer &peer,
unsigned int count,
1963 std::vector<const CBlockIndex *> &vBlocks,
NodeId &nodeStaller) {
1968 vBlocks.reserve(vBlocks.size() +
count);
1969 CNodeState *state = State(peer.m_id);
1970 assert(state !=
nullptr);
1973 ProcessBlockAvailability(peer.m_id);
1975 if (state->pindexBestKnownBlock ==
nullptr ||
1976 state->pindexBestKnownBlock->nChainWork <
1978 state->pindexBestKnownBlock->nChainWork <
1988 const CBlockIndex *snap_base{m_chainman.GetSnapshotBaseBlock()};
1989 if (snap_base && state->pindexBestKnownBlock->GetAncestor(
1990 snap_base->nHeight) != snap_base) {
1992 "Not downloading blocks from peer=%d, which doesn't have the "
1993 "snapshot block in its best chain.\n",
2002 if (state->pindexLastCommonBlock ==
nullptr ||
2004 state->pindexLastCommonBlock->nHeight < snap_base->nHeight)) {
2005 state->pindexLastCommonBlock =
2007 .
ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight,
2014 state->pindexLastCommonBlock, state->pindexBestKnownBlock);
2015 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) {
2019 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
2027 FindNextBlocks(vBlocks, peer, state, pindexWalk,
count, nWindowEnd,
2031void PeerManagerImpl::TryDownloadingHistoricalBlocks(
2032 const Peer &peer,
unsigned int count,
2033 std::vector<const CBlockIndex *> &vBlocks,
const CBlockIndex *from_tip,
2038 if (vBlocks.size() >=
count) {
2042 vBlocks.reserve(
count);
2043 CNodeState *state =
Assert(State(peer.m_id));
2045 if (state->pindexBestKnownBlock ==
nullptr ||
2046 state->pindexBestKnownBlock->GetAncestor(target_block->
nHeight) !=
2061 FindNextBlocks(vBlocks, peer, state, from_tip,
count,
2066void PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex *> &vBlocks,
2067 const Peer &peer, CNodeState *state,
2069 unsigned int count,
int nWindowEnd,
2070 const CChain *activeChain,
2072 std::vector<const CBlockIndex *> vToFetch;
2074 std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
2076 while (pindexWalk->
nHeight < nMaxHeight) {
2081 int nToFetch = std::min(nMaxHeight - pindexWalk->
nHeight,
2082 std::max<int>(
count - vBlocks.size(), 128));
2083 vToFetch.resize(nToFetch);
2084 pindexWalk = state->pindexBestKnownBlock->GetAncestor(
2085 pindexWalk->
nHeight + nToFetch);
2086 vToFetch[nToFetch - 1] = pindexWalk;
2087 for (
unsigned int i = nToFetch - 1; i > 0; i--) {
2088 vToFetch[i - 1] = vToFetch[i]->
pprev;
2101 if (pindex->nStatus.hasData() ||
2102 (activeChain && activeChain->
Contains(pindex))) {
2104 state->pindexLastCommonBlock = pindex;
2106 }
else if (!IsBlockRequested(pindex->
GetBlockHash())) {
2108 if (pindex->
nHeight > nWindowEnd) {
2110 if (vBlocks.size() == 0 && waitingfor != peer.m_id) {
2114 *nodeStaller = waitingfor;
2119 vBlocks.push_back(pindex);
2120 if (vBlocks.size() ==
count) {
2123 }
else if (waitingfor == -1) {
2135void PeerManagerImpl::PushNodeVersion(
const Config &config,
CNode &pnode,
2137 uint64_t my_services{peer.m_our_services};
2138 const int64_t nTime{
count_seconds(GetTime<std::chrono::seconds>())};
2140 const int nNodeStartingHeight{m_best_height};
2151 const bool tx_relay{!RejectIncomingTxs(pnode)};
2160 nNodeStartingHeight, tx_relay, extraEntropy);
2164 "send version message: version %d, blocks=%d, them=%s, "
2165 "txrelay=%d, peer=%d\n",
2170 "send version message: version %d, blocks=%d, "
2171 "txrelay=%d, peer=%d\n",
2176void PeerManagerImpl::AddProofAnnouncement(
2178 std::chrono::microseconds current_time,
bool preferred) {
2182 const bool bypass_limits =
node.HasPermission(
2191 current_time, preferred, bypass_limits);
2193 m_proofrequest.ReceivedInv(
node.GetId(), proofid, preferred, reqtime);
2196void PeerManagerImpl::UpdateLastBlockAnnounceTime(
NodeId node,
2197 int64_t time_in_seconds) {
2199 CNodeState *state = State(
node);
2201 state->m_last_block_announcement = time_in_seconds;
2205void PeerManagerImpl::InitializeNode(
const Config &config,
CNode &
node,
2210 m_node_states.emplace_hint(m_node_states.end(),
2211 std::piecewise_construct,
2212 std::forward_as_tuple(nodeid),
2213 std::forward_as_tuple(
node.IsInboundConn()));
2215 WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty(nodeid));
2222 PeerRef peer = std::make_shared<Peer>(nodeid, our_services, !!m_avalanche);
2225 m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
2227 if (!
node.IsInboundConn()) {
2228 PushNodeVersion(config,
node, *peer);
2232void PeerManagerImpl::ReattemptInitialBroadcast(
CScheduler &scheduler) {
2235 for (
const TxId &txid : unbroadcast_txids) {
2237 if (m_mempool.
exists(txid)) {
2238 RelayTransaction(txid);
2249 auto unbroadcasted_proofids =
2253 auto it = unbroadcasted_proofids.begin();
2254 while (it != unbroadcasted_proofids.end()) {
2257 if (!pm.isBoundToPeer(*it)) {
2258 pm.removeUnbroadcastProof(*it);
2259 it = unbroadcasted_proofids.erase(it);
2266 return unbroadcasted_proofids;
2270 for (
const auto &proofid : unbroadcasted_proofids) {
2271 RelayProof(proofid);
2278 const auto reattemptBroadcastInterval =
2280 scheduler.
scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2281 reattemptBroadcastInterval);
2284void PeerManagerImpl::UpdateAvalancheStatistics()
const {
2290void PeerManagerImpl::AvalanchePeriodicNetworking(
CScheduler &scheduler)
const {
2291 const auto now = GetTime<std::chrono::seconds>();
2292 std::vector<NodeId> avanode_ids;
2293 bool fQuorumEstablished;
2294 bool fShouldRequestMoreNodes;
2304 fShouldRequestMoreNodes =
2312 avanode_ids.push_back(pnode->GetId());
2315 PeerRef peer = GetPeerRef(pnode->
GetId());
2316 if (peer ==
nullptr) {
2320 if (peer->m_proof_relay &&
2321 now > (peer->m_proof_relay->lastSharedProofsUpdate.load() +
2323 peer->m_proof_relay->sharedProofs = {};
2327 if (avanode_ids.empty()) {
2335 for (
NodeId avanodeId : avanode_ids) {
2336 const bool sentGetavaaddr =
2339 MakeAndPushMessage(*pavanode, NetMsgType::GETAVAADDR);
2340 PeerRef peer = GetPeerRef(avanodeId);
2341 WITH_LOCK(peer->m_addr_token_bucket_mutex,
2342 peer->m_addr_token_bucket +=
2343 m_opts.max_addr_to_send);
2351 if (sentGetavaaddr && fQuorumEstablished && !fShouldRequestMoreNodes) {
2366 avanode_ids.resize(std::min<size_t>(avanode_ids.size(), 3));
2369 for (
NodeId nodeid : avanode_ids) {
2372 PeerRef peer = GetPeerRef(nodeid);
2373 if (peer->m_proof_relay) {
2375 peer->m_proof_relay->compactproofs_requested =
true;
2385 const auto avalanchePeriodicNetworkingInterval =
2387 scheduler.
scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2388 avalanchePeriodicNetworkingInterval);
2391void PeerManagerImpl::FinalizeNode(
const Config &config,
const CNode &
node) {
2401 PeerRef peer = RemovePeer(nodeid);
2404 m_peer_map.erase(nodeid);
2406 CNodeState *state = State(nodeid);
2407 assert(state !=
nullptr);
2409 if (state->fSyncStarted) {
2413 for (
const QueuedBlock &entry : state->vBlocksInFlight) {
2415 mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash());
2416 while (range.first != range.second) {
2417 auto [node_id, list_it] = range.first->second;
2418 if (node_id != nodeid) {
2421 range.first = mapBlocksInFlight.erase(range.first);
2426 LOCK(m_tx_download_mutex);
2427 m_txdownloadman.DisconnectedPeer(nodeid);
2429 m_num_preferred_download_peers -= state->fPreferredDownload;
2430 m_peers_downloading_from -= (!state->vBlocksInFlight.empty());
2431 assert(m_peers_downloading_from >= 0);
2432 m_outbound_peers_with_protect_from_disconnect -=
2433 state->m_chain_sync.m_protect;
2434 assert(m_outbound_peers_with_protect_from_disconnect >= 0);
2436 m_node_states.erase(nodeid);
2438 if (m_node_states.empty()) {
2440 assert(mapBlocksInFlight.empty());
2441 assert(m_num_preferred_download_peers == 0);
2442 assert(m_peers_downloading_from == 0);
2443 assert(m_outbound_peers_with_protect_from_disconnect == 0);
2444 WITH_LOCK(m_tx_download_mutex, m_txdownloadman.CheckIsEmpty());
2448 if (
node.fSuccessfullyConnected && !
node.IsBlockOnlyConn() &&
2449 !
node.IsInboundConn()) {
2456 LOCK(m_headers_presync_mutex);
2457 m_headers_presync_stats.erase(nodeid);
2460 WITH_LOCK(cs_proofrequest, m_proofrequest.DisconnectedPeer(nodeid));
2465PeerRef PeerManagerImpl::GetPeerRef(
NodeId id)
const {
2467 auto it = m_peer_map.find(
id);
2468 return it != m_peer_map.end() ? it->second :
nullptr;
2471PeerRef PeerManagerImpl::RemovePeer(
NodeId id) {
2474 auto it = m_peer_map.find(
id);
2475 if (it != m_peer_map.end()) {
2476 ret = std::move(it->second);
2477 m_peer_map.erase(it);
2482bool PeerManagerImpl::GetNodeStateStats(
NodeId nodeid,
2486 const CNodeState *state = State(nodeid);
2487 if (state ==
nullptr) {
2491 ? state->pindexBestKnownBlock->nHeight
2494 ? state->pindexLastCommonBlock->nHeight
2496 for (
const QueuedBlock &queue : state->vBlocksInFlight) {
2503 PeerRef peer = GetPeerRef(nodeid);
2504 if (peer ==
nullptr) {
2516 auto ping_wait{0us};
2517 if ((0 != peer->m_ping_nonce_sent) &&
2518 (0 != peer->m_ping_start.load().count())) {
2520 GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
2523 if (
auto tx_relay = peer->GetTxRelay()) {
2525 return tx_relay->m_relay_txs);
2537 LOCK(peer->m_headers_sync_mutex);
2538 if (peer->m_headers_sync) {
2546std::vector<TxOrphanage::PoolTx> PeerManagerImpl::GetOrphanTransactions() {
2547 LOCK(m_tx_download_mutex);
2548 return m_txdownloadman.GetOrphanTransactions();
2551void PeerManagerImpl::AddToCompactExtraTransactions(
const CTransactionRef &tx) {
2552 if (m_opts.max_extra_txs <= 0) {
2556 if (!vExtraTxnForCompact.size()) {
2557 vExtraTxnForCompact.resize(m_opts.max_extra_txs);
2560 vExtraTxnForCompact[vExtraTxnForCompactIt] = tx;
2561 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs;
2564void PeerManagerImpl::Misbehaving(Peer &peer,
const std::string &message) {
2565 LOCK(peer.m_misbehavior_mutex);
2567 const std::string message_prefixed =
2568 message.empty() ?
"" : (
": " + message);
2569 peer.m_should_discourage =
true;
2574void PeerManagerImpl::MaybePunishNodeForBlock(
NodeId nodeid,
2576 bool via_compact_block,
2577 const std::string &message) {
2578 PeerRef peer{GetPeerRef(nodeid)};
2589 if (!via_compact_block) {
2591 Misbehaving(*peer, message);
2598 CNodeState *node_state = State(nodeid);
2599 if (node_state ==
nullptr) {
2606 if (!via_compact_block && !node_state->m_is_inbound) {
2608 Misbehaving(*peer, message);
2618 Misbehaving(*peer, message);
2624 Misbehaving(*peer, message);
2630 if (message !=
"") {
2635void PeerManagerImpl::MaybePunishNodeForTx(
NodeId nodeid,
2637 const std::string &message) {
2638 PeerRef peer{GetPeerRef(nodeid)};
2645 Misbehaving(*peer, message);
2663 if (message !=
"") {
2668bool PeerManagerImpl::BlockRequestAllowed(
const CBlockIndex *pindex) {
2674 (m_chainman.m_best_header !=
nullptr) &&
2675 (m_chainman.m_best_header->GetBlockTime() - pindex->
GetBlockTime() <
2678 *m_chainman.m_best_header, *pindex, *m_chainman.m_best_header,
2682std::optional<std::string>
2683PeerManagerImpl::FetchBlock(
const Config &config,
NodeId peer_id,
2686 return "Loading blocks ...";
2692 CNodeState *state = State(peer_id);
2693 if (state ==
nullptr) {
2694 return "Peer does not exist";
2698 RemoveBlockRequest(block_index.
GetBlockHash(), std::nullopt);
2703 if (!BlockRequested(config, peer_id, block_index)) {
2704 return "Already requested from this peer";
2713 this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs);
2716 return "Node not fully connected";
2721 return std::nullopt;
2724std::unique_ptr<PeerManager>
2728 return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman,
2737 : m_rng{opts.deterministic_rng},
2739 m_chainparams(chainman.GetParams()), m_connman(connman),
2740 m_addrman(addrman), m_banman(banman), m_chainman(chainman),
2741 m_mempool(pool), m_avalanche(
avalanche),
2742 m_txdownloadman(
node::TxDownloadOptions{pool, opts.max_orphan_txs,
2743 opts.deterministic_rng}),
2746void PeerManagerImpl::StartScheduledTasks(
CScheduler &scheduler) {
2753 "peer eviction timer should be less than stale tip check timer");
2756 this->CheckForStaleTipAndEvictPeers();
2762 const auto reattemptBroadcastInterval =
2764 scheduler.
scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); },
2765 reattemptBroadcastInterval);
2770 UpdateAvalancheStatistics();
2776 const auto avalanchePeriodicNetworkingInterval =
2778 scheduler.
scheduleFromNow([&] { AvalanchePeriodicNetworking(scheduler); },
2779 avalanchePeriodicNetworkingInterval);
2782void PeerManagerImpl::ActiveTipChange(
const CBlockIndex &new_tip,
bool is_ibd) {
2789 LOCK(m_tx_download_mutex);
2793 m_txdownloadman.ActiveTipChange();
2803void PeerManagerImpl::BlockConnected(
2804 ChainstateRole role,
const std::shared_ptr<const CBlock> &pblock,
2808 m_last_tip_update = GetTime<std::chrono::seconds>();
2812 auto stalling_timeout = m_block_stalling_timeout.load();
2815 const auto new_timeout =
2816 std::max(std::chrono::duration_cast<std::chrono::seconds>(
2817 stalling_timeout * 0.85),
2819 if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout,
2831 LOCK(m_tx_download_mutex);
2832 m_txdownloadman.BlockConnected(pblock);
2835void PeerManagerImpl::BlockDisconnected(
2836 const std::shared_ptr<const CBlock> &block,
const CBlockIndex *pindex) {
2837 LOCK(m_tx_download_mutex);
2838 m_txdownloadman.BlockDisconnected();
2845void PeerManagerImpl::NewPoWValidBlock(
2846 const CBlockIndex *pindex,
const std::shared_ptr<const CBlock> &pblock) {
2847 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock =
2848 std::make_shared<const CBlockHeaderAndShortTxIDs>(
2853 if (pindex->
nHeight <= m_highest_fast_announce) {
2856 m_highest_fast_announce = pindex->
nHeight;
2859 const std::shared_future<CSerializedNetMsg> lazy_ser{
2860 std::async(std::launch::deferred, [&] {
2865 auto most_recent_block_txs =
2866 std::make_unique<std::map<TxId, CTransactionRef>>();
2867 for (
const auto &tx : pblock->vtx) {
2868 most_recent_block_txs->emplace(tx->GetId(), tx);
2871 LOCK(m_most_recent_block_mutex);
2872 m_most_recent_block_hash = hashBlock;
2873 m_most_recent_block = pblock;
2874 m_most_recent_compact_block = pcmpctblock;
2875 m_most_recent_block_txs = std::move(most_recent_block_txs);
2879 [
this, pindex, &lazy_ser, &hashBlock](
CNode *pnode)
2886 ProcessBlockAvailability(pnode->
GetId());
2887 CNodeState &state = *State(pnode->
GetId());
2891 if (state.m_requested_hb_cmpctblocks &&
2892 !PeerHasHeader(&state, pindex) &&
2893 PeerHasHeader(&state, pindex->
pprev)) {
2895 "%s sending header-and-ids %s to peer=%d\n",
2896 "PeerManager::NewPoWValidBlock",
2897 hashBlock.ToString(), pnode->
GetId());
2900 PushMessage(*pnode, ser_cmpctblock.Copy());
2901 state.pindexBestHeaderSent = pindex;
2910void PeerManagerImpl::UpdatedBlockTip(
const CBlockIndex *pindexNew,
2912 bool fInitialDownload) {
2913 SetBestHeight(pindexNew->
nHeight);
2917 if (fInitialDownload) {
2922 std::vector<BlockHash> vHashes;
2924 while (pindexToAnnounce != pindexFork) {
2926 pindexToAnnounce = pindexToAnnounce->
pprev;
2936 for (
auto &it : m_peer_map) {
2937 Peer &peer = *it.second;
2938 LOCK(peer.m_block_inv_mutex);
2940 peer.m_blocks_for_headers_relay.push_back(hash);
2952void PeerManagerImpl::BlockChecked(
const CBlock &block,
2957 std::map<BlockHash, std::pair<NodeId, bool>>::iterator it =
2958 mapBlockSource.find(hash);
2962 if (state.
IsInvalid() && it != mapBlockSource.end() &&
2963 State(it->second.first)) {
2964 MaybePunishNodeForBlock(it->second.first, state,
2965 !it->second.second);
2974 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
2975 if (it != mapBlockSource.end()) {
2976 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
2980 if (it != mapBlockSource.end()) {
2981 mapBlockSource.erase(it);
2990bool PeerManagerImpl::AlreadyHaveBlock(
const BlockHash &block_hash) {
2995 if (!
Assume(m_avalanche)) {
3000 if (localProof && localProof->getId() == proofid) {
3009void PeerManagerImpl::SendPings() {
3011 for (
auto &it : m_peer_map) {
3012 it.second->m_ping_queued =
true;
3016void PeerManagerImpl::RelayTransaction(
const TxId &txid) {
3018 for (
auto &it : m_peer_map) {
3019 Peer &peer = *it.second;
3020 auto tx_relay = peer.GetTxRelay();
3024 LOCK(tx_relay->m_tx_inventory_mutex);
3030 if (tx_relay->m_next_inv_send_time == 0s) {
3034 if (!tx_relay->m_tx_inventory_known_filter.contains(txid) ||
3035 tx_relay->m_avalanche_stalled_txids.count(txid) > 0) {
3036 tx_relay->m_tx_inventory_to_send.insert(txid);
3043 for (
auto &it : m_peer_map) {
3044 Peer &peer = *it.second;
3046 if (!peer.m_proof_relay) {
3049 LOCK(peer.m_proof_relay->m_proof_inventory_mutex);
3050 if (!peer.m_proof_relay->m_proof_inventory_known_filter.contains(
3052 peer.m_proof_relay->m_proof_inventory_to_send.insert(proofid);
3057void PeerManagerImpl::RelayAddress(
NodeId originator,
const CAddress &addr,
3073 const auto current_time{GetTime<std::chrono::seconds>()};
3076 const uint64_t time_addr{
3077 (
static_cast<uint64_t
>(
count_seconds(current_time)) + hash_addr) /
3087 unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
3088 std::array<std::pair<uint64_t, Peer *>, 2> best{
3089 {{0,
nullptr}, {0,
nullptr}}};
3090 assert(nRelayNodes <= best.size());
3094 for (
auto &[
id, peer] : m_peer_map) {
3095 if (peer->m_addr_relay_enabled &&
id != originator &&
3096 IsAddrCompatible(*peer, addr)) {
3098 for (
unsigned int i = 0; i < nRelayNodes; i++) {
3099 if (hashKey > best[i].first) {
3100 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1,
3101 best.begin() + i + 1);
3102 best[i] = std::make_pair(hashKey, peer.get());
3109 for (
unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
3110 PushAddress(*best[i].second, addr);
3114void PeerManagerImpl::ProcessGetBlockData(
const Config &config,
CNode &pfrom,
3115 Peer &peer,
const CInv &inv) {
3120 "filtered block request received when NODE_BLOOM service "
3121 "disabled, disconnecting peer=%d\n",
3129 std::shared_ptr<const CBlock> a_recent_block;
3130 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
3132 LOCK(m_most_recent_block_mutex);
3133 a_recent_block = m_most_recent_block;
3134 a_recent_compact_block = m_most_recent_compact_block;
3137 bool need_activate_chain =
false;
3151 need_activate_chain =
true;
3155 if (need_activate_chain) {
3158 state, a_recent_block, m_avalanche)) {
3166 bool can_direct_fetch{
false};
3174 if (!BlockRequestAllowed(pindex)) {
3176 "%s: ignoring request from peer=%i for old "
3177 "block that isn't in the main chain\n",
3178 __func__, pfrom.
GetId());
3184 (((m_chainman.m_best_header !=
nullptr) &&
3185 (m_chainman.m_best_header->GetBlockTime() -
3193 "historical block serving limit reached, disconnect peer=%d\n",
3206 (tip->nHeight - pindex->
nHeight >
3209 "Ignore block request below NODE_NETWORK_LIMITED "
3210 "threshold, disconnect peer=%d\n",
3220 if (!pindex->nStatus.hasData()) {
3223 can_direct_fetch = CanDirectFetch();
3227 std::shared_ptr<const CBlock> pblock;
3228 auto handle_block_read_error = [&]() {
3230 return m_chainman.
m_blockman.IsBlockPruned(*pindex))) {
3232 "Block was pruned before it could be read, disconnect "
3236 LogError(
"Cannot load block from disk, disconnect peer=%d\n",
3242 if (a_recent_block && a_recent_block->GetHash() == pindex->
GetBlockHash()) {
3243 pblock = a_recent_block;
3248 std::vector<uint8_t> block_data;
3250 handle_block_read_error();
3257 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
3259 handle_block_read_error();
3262 pblock = pblockRead;
3268 bool sendMerkleBlock =
false;
3270 if (
auto tx_relay = peer.GetTxRelay()) {
3271 LOCK(tx_relay->m_bloom_filter_mutex);
3272 if (tx_relay->m_bloom_filter) {
3273 sendMerkleBlock =
true;
3278 if (sendMerkleBlock) {
3289 typedef std::pair<size_t, uint256> PairType;
3290 for (PairType &pair : merkleBlock.vMatchedTxn) {
3292 *pblock->vtx[pair.first]);
3302 if (can_direct_fetch &&
3304 if (a_recent_compact_block &&
3305 a_recent_compact_block->header.GetHash() ==
3308 *a_recent_compact_block);
3322 LOCK(peer.m_block_inv_mutex);
3325 if (hash == peer.m_continuation_block) {
3329 std::vector<CInv> vInv;
3332 peer.m_continuation_block =
BlockHash();
3338PeerManagerImpl::FindTxForGetData(
const Peer &peer,
const TxId &txid,
3339 const std::chrono::seconds mempool_req,
3340 const std::chrono::seconds now) {
3341 auto txinfo = m_mempool.
info(txid);
3346 if ((mempool_req.count() && txinfo.m_time <= mempool_req) ||
3348 return std::move(txinfo.tx);
3357 Assume(peer.GetTxRelay())->m_recently_announced_invs.contains(txid);
3358 if (recent && txinfo.tx) {
3359 return std::move(txinfo.tx);
3364 LOCK(m_most_recent_block_mutex);
3365 if (m_most_recent_block_txs !=
nullptr) {
3366 auto it = m_most_recent_block_txs->find(txid);
3367 if (it != m_most_recent_block_txs->end()) {
3380PeerManagerImpl::FindProofForGetData(
const Peer &peer,
3382 const std::chrono::seconds now) {
3385 bool send_unconditionally =
3411 if (send_unconditionally) {
3416 if (peer.m_proof_relay->m_recently_announced_proofs.contains(proofid)) {
3423void PeerManagerImpl::ProcessGetData(
3425 const std::atomic<bool> &interruptMsgProc) {
3428 auto tx_relay = peer.GetTxRelay();
3430 std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
3431 std::vector<CInv> vNotFound;
3433 const auto now{GetTime<std::chrono::seconds>()};
3435 const auto mempool_req = tx_relay !=
nullptr
3436 ? tx_relay->m_last_mempool_req.load()
3437 : std::chrono::seconds::min();
3442 while (it != peer.m_getdata_requests.end() &&
3443 (it->IsMsgProof() || it->IsMsgTx())) {
3444 if (interruptMsgProc) {
3453 const CInv &inv = *it++;
3457 vNotFound.push_back(inv);
3461 auto proof = FindProofForGetData(peer, proofid, now);
3468 vNotFound.push_back(inv);
3475 if (tx_relay ==
nullptr) {
3489 std::vector<TxId> parent_ids_to_add;
3492 auto tx_iter = m_mempool.
GetIter(tx->GetId());
3494 auto &pentry = *tx_iter;
3496 (*pentry)->GetMemPoolParentsConst();
3497 parent_ids_to_add.reserve(parents.size());
3498 for (
const auto &parent : parents) {
3499 if (parent.get()->GetTime() >
3501 parent_ids_to_add.push_back(
3502 parent.get()->GetTx().GetId());
3507 for (
const TxId &parent_txid : parent_ids_to_add) {
3510 if (
WITH_LOCK(tx_relay->m_tx_inventory_mutex,
3511 return !tx_relay->m_tx_inventory_known_filter
3512 .contains(parent_txid))) {
3513 tx_relay->m_recently_announced_invs.insert(parent_txid);
3517 vNotFound.push_back(inv);
3529 if (it != peer.m_getdata_requests.end() && !pfrom.
fPauseSend) {
3530 const CInv &inv = *it++;
3532 ProcessGetBlockData(config, pfrom, peer, inv);
3538 peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
3540 if (!vNotFound.empty()) {
3557void PeerManagerImpl::SendBlockTransactions(
3561 for (
size_t i = 0; i < req.
indices.size(); i++) {
3563 Misbehaving(peer,
"getblocktxn with out-of-bounds tx indices");
3572bool PeerManagerImpl::CheckHeadersPoW(
const std::vector<CBlockHeader> &headers,
3577 Misbehaving(peer,
"header with invalid proof of work");
3582 if (!CheckHeadersAreContinuous(headers)) {
3583 Misbehaving(peer,
"non-continuous headers sequence");
3596 near_chaintip_work =
3609void PeerManagerImpl::HandleUnconnectingHeaders(
3610 CNode &pfrom, Peer &peer,
const std::vector<CBlockHeader> &headers) {
3614 if (MaybeSendGetHeaders(pfrom,
GetLocator(best_header), peer)) {
3617 "received header %s: missing prev block %s, sending getheaders "
3618 "(%d) to end (peer=%d)\n",
3620 headers[0].hashPrevBlock.ToString(), best_header->nHeight,
3628 UpdateBlockAvailability(pfrom.
GetId(), headers.back().GetHash()));
3631bool PeerManagerImpl::CheckHeadersAreContinuous(
3632 const std::vector<CBlockHeader> &headers)
const {
3635 if (!hashLastBlock.
IsNull() && header.hashPrevBlock != hashLastBlock) {
3638 hashLastBlock = header.GetHash();
3643bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(
3644 Peer &peer,
CNode &pfrom, std::vector<CBlockHeader> &headers) {
3645 if (peer.m_headers_sync) {
3646 auto result = peer.m_headers_sync->ProcessNextHeaders(
3650 if (result.success) {
3651 peer.m_last_getheaders_timestamp = {};
3653 if (result.request_more) {
3654 auto locator = peer.m_headers_sync->NextHeadersRequestLocator();
3657 Assume(!locator.vHave.empty());
3661 if (!locator.vHave.empty()) {
3664 bool sent_getheaders =
3665 MaybeSendGetHeaders(pfrom, locator, peer);
3668 locator.vHave.front().ToString(), pfrom.
GetId());
3673 peer.m_headers_sync.reset(
nullptr);
3678 LOCK(m_headers_presync_mutex);
3679 m_headers_presync_stats.erase(pfrom.
GetId());
3682 HeadersPresyncStats stats;
3683 stats.first = peer.m_headers_sync->GetPresyncWork();
3684 if (peer.m_headers_sync->GetState() ==
3686 stats.second = {peer.m_headers_sync->GetPresyncHeight(),
3687 peer.m_headers_sync->GetPresyncTime()};
3691 LOCK(m_headers_presync_mutex);
3692 m_headers_presync_stats[pfrom.
GetId()] = stats;
3694 m_headers_presync_stats.find(m_headers_presync_bestpeer);
3695 bool best_updated =
false;
3696 if (best_it == m_headers_presync_stats.end()) {
3701 const HeadersPresyncStats *stat_best{
nullptr};
3702 for (
const auto &[_peer, _stat] : m_headers_presync_stats) {
3703 if (!stat_best || _stat > *stat_best) {
3708 m_headers_presync_bestpeer = peer_best;
3709 best_updated = (peer_best == pfrom.
GetId());
3710 }
else if (best_it->first == pfrom.
GetId() ||
3711 stats > best_it->second) {
3714 m_headers_presync_bestpeer = pfrom.
GetId();
3715 best_updated =
true;
3717 if (best_updated && stats.second.has_value()) {
3720 m_headers_presync_should_signal =
true;
3724 if (result.success) {
3727 headers.swap(result.pow_validated_headers);
3730 return result.success;
3738bool PeerManagerImpl::TryLowWorkHeadersSync(
3740 std::vector<CBlockHeader> &headers) {
3747 arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold();
3751 if (total_work < minimum_chain_work) {
3765 LOCK(peer.m_headers_sync_mutex);
3766 peer.m_headers_sync.reset(
3768 chain_start_header, minimum_chain_work));
3773 (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
3776 "Ignoring low-work chain (height=%u) from peer=%d\n",
3777 chain_start_header->
nHeight + headers.size(),
3789bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(
const CBlockIndex *header) {
3790 return header !=
nullptr &&
3791 ((m_chainman.m_best_header !=
nullptr &&
3793 m_chainman.m_best_header->GetAncestor(header->
nHeight)) ||
3797bool PeerManagerImpl::MaybeSendGetHeaders(
CNode &pfrom,
3804 if (current_time - peer.m_last_getheaders_timestamp >
3807 peer.m_last_getheaders_timestamp = current_time;
3819void PeerManagerImpl::HeadersDirectFetchBlocks(
const Config &config,
3823 CNodeState *nodestate = State(pfrom.
GetId());
3827 std::vector<const CBlockIndex *> vToFetch;
3833 if (!pindexWalk->nStatus.hasData() &&
3836 vToFetch.push_back(pindexWalk);
3838 pindexWalk = pindexWalk->
pprev;
3849 std::vector<CInv> vGetData;
3852 if (nodestate->vBlocksInFlight.size() >=
3858 BlockRequested(config, pfrom.
GetId(), *pindex);
3862 if (vGetData.size() > 1) {
3864 "Downloading blocks toward %s (%d) via headers "
3869 if (vGetData.size() > 0) {
3870 if (!m_opts.ignore_incoming_txs &&
3871 nodestate->m_provides_cmpctblocks && vGetData.size() == 1 &&
3872 mapBlocksInFlight.size() == 1 &&
3889void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(
3891 bool received_new_header,
bool may_have_more_headers) {
3894 CNodeState *nodestate = State(pfrom.
GetId());
3902 if (received_new_header &&
3904 nodestate->m_last_block_announcement =
GetTime();
3912 if (nodestate->pindexBestKnownBlock &&
3913 nodestate->pindexBestKnownBlock->nChainWork <
3924 LogPrintf(
"Disconnecting outbound peer %d -- headers "
3925 "chain has insufficient work\n",
3939 nodestate->pindexBestKnownBlock !=
nullptr) {
3940 if (m_outbound_peers_with_protect_from_disconnect <
3942 nodestate->pindexBestKnownBlock->nChainWork >=
3944 !nodestate->m_chain_sync.m_protect) {
3947 nodestate->m_chain_sync.m_protect =
true;
3948 ++m_outbound_peers_with_protect_from_disconnect;
3953void PeerManagerImpl::ProcessHeadersMessage(
const Config &config,
CNode &pfrom,
3955 std::vector<CBlockHeader> &&headers,
3956 bool via_compact_block) {
3957 size_t nCount = headers.size();
3965 LOCK(peer.m_headers_sync_mutex);
3966 if (peer.m_headers_sync) {
3967 peer.m_headers_sync.reset(
nullptr);
3968 LOCK(m_headers_presync_mutex);
3969 m_headers_presync_stats.erase(pfrom.
GetId());
3974 peer.m_last_getheaders_timestamp = {};
3982 if (!CheckHeadersPoW(headers, m_chainparams.
GetConsensus(), peer)) {
3997 bool already_validated_work =
false;
4000 bool have_headers_sync =
false;
4002 LOCK(peer.m_headers_sync_mutex);
4004 already_validated_work =
4005 IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers);
4017 if (headers.empty()) {
4021 have_headers_sync = !!peer.m_headers_sync;
4027 headers[0].hashPrevBlock))};
4028 bool headers_connect_blockindex{chain_start_header !=
nullptr};
4030 if (!headers_connect_blockindex) {
4034 HandleUnconnectingHeaders(pfrom, peer, headers);
4042 peer.m_last_getheaders_timestamp = {};
4051 last_received_header =
4053 if (IsAncestorOfBestHeaderOrTip(last_received_header)) {
4054 already_validated_work =
true;
4062 already_validated_work =
true;
4068 if (!already_validated_work &&
4069 TryLowWorkHeadersSync(peer, pfrom, chain_start_header, headers)) {
4081 bool received_new_header{last_received_header ==
nullptr};
4086 state, &pindexLast)) {
4088 MaybePunishNodeForBlock(pfrom.
GetId(), state, via_compact_block,
4089 "invalid header received");
4095 LogError(
"headers message processed but no pindexLast\n");
4104 if (MaybeSendGetHeaders(pfrom,
GetLocator(pindexLast), peer)) {
4107 "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
4108 pindexLast->
nHeight, pfrom.
GetId(), peer.m_starting_height);
4112 UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast,
4113 received_new_header,
4117 HeadersDirectFetchBlocks(config, pfrom, *pindexLast);
4120std::optional<node::PackageToValidate>
4123 bool first_time_failure) {
4129 PeerRef peer{GetPeerRef(nodeid)};
4131 const TxId &txid = ptx->GetId();
4139 return std::nullopt;
4142 const auto &[add_extra_compact_tx, unique_parents, package_to_validate] =
4143 m_txdownloadman.MempoolRejectedTx(ptx, state, nodeid,
4144 first_time_failure);
4147 AddToCompactExtraTransactions(ptx);
4151 for (
const TxId &parent_txid : unique_parents) {
4153 AddKnownTx(*peer, parent_txid);
4157 MaybePunishNodeForTx(nodeid, state);
4159 return package_to_validate;
4167 m_txdownloadman.MempoolAcceptedTx(tx);
4171 "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4172 nodeid, tx->GetId().ToString(), m_mempool.
size(),
4175 RelayTransaction(tx->GetId());
4178void PeerManagerImpl::ProcessPackageResult(
4185 const auto &
package = package_to_validate.m_txns;
4186 const auto &senders = package_to_validate.
m_senders;
4189 m_txdownloadman.MempoolRejectedPackage(package);
4193 if (!
Assume(package.size() == 2)) {
4199 auto package_iter = package.rbegin();
4200 auto senders_iter = senders.rbegin();
4201 while (package_iter != package.rend()) {
4202 const auto &tx = *package_iter;
4203 const NodeId nodeid = *senders_iter;
4204 const auto it_result{package_result.
m_tx_results.find(tx->GetId())};
4208 const auto &tx_result = it_result->second;
4209 switch (tx_result.m_result_type) {
4211 ProcessValidTx(nodeid, tx);
4221 ProcessInvalidTx(nodeid, tx, tx_result.m_state,
4238bool PeerManagerImpl::ProcessOrphanTx(
const Config &config, Peer &peer) {
4243 m_txdownloadman.GetTxToReconsider(peer.m_id)) {
4247 const TxId &orphanTxId = porphanTx->GetId();
4252 ProcessValidTx(peer.m_id, porphanTx);
4258 " invalid orphan tx %s from peer=%d. %s\n",
4265 ProcessInvalidTx(peer.m_id, porphanTx, state,
4276bool PeerManagerImpl::PrepareBlockFilterRequest(
4278 const BlockHash &stop_hash, uint32_t max_height_diff,
4280 const bool supported_filter_type =
4283 if (!supported_filter_type) {
4285 "peer %d requested unsupported block filter type: %d\n",
4286 node.GetId(),
static_cast<uint8_t
>(filter_type));
4287 node.fDisconnect =
true;
4297 if (!stop_index || !BlockRequestAllowed(stop_index)) {
4300 node.fDisconnect =
true;
4305 uint32_t stop_height = stop_index->
nHeight;
4306 if (start_height > stop_height) {
4309 "peer %d sent invalid getcfilters/getcfheaders with "
4311 "start height %d and stop height %d\n",
4312 node.GetId(), start_height, stop_height);
4313 node.fDisconnect =
true;
4316 if (stop_height - start_height >= max_height_diff) {
4318 "peer %d requested too many cfilters/cfheaders: %d / %d\n",
4319 node.GetId(), stop_height - start_height + 1, max_height_diff);
4320 node.fDisconnect =
true;
4325 if (!filter_index) {
4334void PeerManagerImpl::ProcessGetCFilters(
CNode &
node, Peer &peer,
4336 uint8_t filter_type_ser;
4337 uint32_t start_height;
4340 vRecv >> filter_type_ser >> start_height >> stop_hash;
4347 if (!PrepareBlockFilterRequest(
node, peer, filter_type, start_height,
4353 std::vector<BlockFilter> filters;
4356 "Failed to find block filter in index: filter_type=%s, "
4357 "start_height=%d, stop_hash=%s\n",
4363 for (
const auto &filter : filters) {
4368void PeerManagerImpl::ProcessGetCFHeaders(
CNode &
node, Peer &peer,
4370 uint8_t filter_type_ser;
4371 uint32_t start_height;
4374 vRecv >> filter_type_ser >> start_height >> stop_hash;
4381 if (!PrepareBlockFilterRequest(
node, peer, filter_type, start_height,
4388 if (start_height > 0) {
4390 stop_index->
GetAncestor(
static_cast<int>(start_height - 1));
4393 "Failed to find block filter header in index: "
4394 "filter_type=%s, block_hash=%s\n",
4401 std::vector<uint256> filter_hashes;
4405 "Failed to find block filter hashes in index: filter_type=%s, "
4406 "start_height=%d, stop_hash=%s\n",
4413 stop_index->
GetBlockHash(), prev_header, filter_hashes);
4416void PeerManagerImpl::ProcessGetCFCheckPt(
CNode &
node, Peer &peer,
4418 uint8_t filter_type_ser;
4421 vRecv >> filter_type_ser >> stop_hash;
4428 if (!PrepareBlockFilterRequest(
4429 node, peer, filter_type, 0, stop_hash,
4430 std::numeric_limits<uint32_t>::max(),
4431 stop_index, filter_index)) {
4439 for (
int i = headers.size() - 1; i >= 0; i--) {
4445 "Failed to find block filter header in index: "
4446 "filter_type=%s, block_hash=%s\n",
4469PeerManagerImpl::GetAvalancheVoteForBlock(
const BlockHash &hash)
const {
4480 if (pindex->nStatus.isInvalid()) {
4485 if (pindex->nStatus.isOnParkedChain()) {
4493 if (pindex == pindexFork) {
4498 if (pindexFork != pindexTip) {
4503 if (!pindex->nStatus.hasData()) {
4518 if (m_txdownloadman.RecentConfirmedTransactionsFilter().contains(
id)) {
4525 if (m_txdownloadman.RecentRejectsFilter().contains(
id)) {
4537 if (
auto iter = m_mempool.
GetIter(
id)) {
4538 mempool_tx = (**iter)->GetSharedTx();
4543 return conflicting.HaveTx(id);
4550 return orphanage.HaveTx(id);
4616 const std::shared_ptr<const CBlock> &block,
4617 bool force_processing,
4618 bool min_pow_checked) {
4619 bool new_block{
false};
4621 &new_block, m_avalanche);
4623 node.m_last_block_time = GetTime<std::chrono::seconds>();
4628 RemoveBlockRequest(block->GetHash(), std::nullopt);
4631 mapBlockSource.erase(block->GetHash());
4635void PeerManagerImpl::ProcessCompactBlockTxns(
4638 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4639 bool fBlockRead{
false};
4644 mapBlocksInFlight.equal_range(block_transactions.
blockhash);
4645 size_t already_in_flight =
4646 std::distance(range_flight.first, range_flight.second);
4647 bool requested_block_from_this_peer{
false};
4651 bool first_in_flight =
4652 already_in_flight == 0 ||
4653 (range_flight.first->second.first == pfrom.
GetId());
4655 while (range_flight.first != range_flight.second) {
4656 auto [node_id, block_it] = range_flight.first->second;
4657 if (node_id == pfrom.
GetId() && block_it->partialBlock) {
4658 requested_block_from_this_peer =
true;
4661 range_flight.first++;
4664 if (!requested_block_from_this_peer) {
4666 "Peer %d sent us block transactions for block we weren't "
4673 *range_flight.first->second.second->partialBlock;
4678 "previous compact block reconstruction attempt failed");
4680 "Peer %d sent compact block transactions multiple times\n",
4686 partialBlock.
FillBlock(*pblock, block_transactions.
txn);
4692 peer,
"invalid compact block/non-matching block transactions");
4695 if (first_in_flight) {
4701 std::vector<CInv> invs;
4707 "Peer %d sent us a compact block but it failed to "
4708 "reconstruct, waiting on first download to complete\n",
4724 mapBlockSource.emplace(block_transactions.
blockhash,
4725 std::make_pair(pfrom.
GetId(),
false));
4736 ProcessBlock(config, pfrom, pblock,
true,
4742void PeerManagerImpl::ProcessMessage(
4743 const Config &config,
CNode &pfrom,
const std::string &msg_type,
4744 DataStream &vRecv,
const std::chrono::microseconds time_received,
4745 const std::atomic<bool> &interruptMsgProc) {
4751 PeerRef peer = GetPeerRef(pfrom.
GetId());
4752 if (peer ==
nullptr) {
4758 "Avalanche is not initialized, ignoring %s message\n",
4773 uint64_t nNonce = 1;
4776 std::string cleanSubVer;
4777 int starting_height = -1;
4779 uint64_t nExtraEntropy = 1;
4781 vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
4794 "peer=%d does not offer the expected services "
4795 "(%08x offered, %08x expected); disconnecting\n",
4796 pfrom.
GetId(), nServices,
4806 "peer=%d does not offer the avalanche service; disconnecting\n",
4815 "peer=%d using obsolete version %i; disconnecting\n",
4816 pfrom.
GetId(), nVersion);
4821 if (!vRecv.
empty()) {
4830 if (!vRecv.
empty()) {
4831 std::string strSubVer;
4835 if (!vRecv.
empty()) {
4836 vRecv >> starting_height;
4838 if (!vRecv.
empty()) {
4841 if (!vRecv.
empty()) {
4842 vRecv >> nExtraEntropy;
4846 LogPrintf(
"connected to self at %s, disconnecting\n",
4859 PushNodeVersion(config, pfrom, *peer);
4863 const int greatest_common_version =
4875 peer->m_their_services = nServices;
4879 pfrom.cleanSubVer = cleanSubVer;
4881 peer->m_starting_height = starting_height;
4889 (fRelay || (peer->m_our_services &
NODE_BLOOM))) {
4890 auto *
const tx_relay = peer->SetTxRelay();
4892 LOCK(tx_relay->m_bloom_filter_mutex);
4894 tx_relay->m_relay_txs = fRelay;
4907 CNodeState *state = State(pfrom.
GetId());
4908 state->fPreferredDownload =
4912 m_num_preferred_download_peers += state->fPreferredDownload;
4918 bool send_getaddr{
false};
4920 send_getaddr = SetupAddressRelay(pfrom, *peer);
4931 peer->m_getaddr_sent =
true;
4935 WITH_LOCK(peer->m_addr_token_bucket_mutex,
4936 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
4957 std::string remoteAddr;
4963 "receive version message: [%s] %s: version %d, blocks=%d, "
4964 "us=%s, txrelay=%d, peer=%d%s\n",
4967 pfrom.
GetId(), remoteAddr);
4969 int64_t currentTime =
GetTime();
4970 int64_t nTimeOffset = nTime - currentTime;
4975 Misbehaving(*peer,
"Ignoring invalid timestamp in version message");
4985 "feeler connection completed peer=%d; disconnecting\n",
4994 Misbehaving(*peer,
"non-version message before version handshake");
5001 "ignoring redundant verack message from peer=%d\n",
5007 LogPrintf(
"New outbound peer connected: version: %d, blocks=%d, "
5009 pfrom.
nVersion.load(), peer->m_starting_height,
5030 AddKnownProof(*peer, localProof->getId());
5034 peer->m_proof_relay->m_recently_announced_proofs.insert(
5035 localProof->getId());
5040 if (
auto tx_relay = peer->GetTxRelay()) {
5049 return tx_relay->m_tx_inventory_to_send.empty() &&
5050 tx_relay->m_next_inv_send_time == 0s));
5055 const CNodeState *state = State(pfrom.
GetId());
5056 m_txdownloadman.ConnectedPeer(
5058 .m_preferred = state->fPreferredDownload,
5059 .m_relay_permissions = pfrom.HasPermission(
5060 NetPermissionFlags::Relay),
5070 Misbehaving(*peer,
"non-verack message before version handshake");
5075 const auto ser_params{
5084 std::vector<CAddress> vAddr;
5088 if (!SetupAddressRelay(pfrom, *peer)) {
5094 if (vAddr.size() > m_opts.max_addr_to_send) {
5095 Misbehaving(*peer,
strprintf(
"%s message size = %u", msg_type,
5101 std::vector<CAddress> vAddrOk;
5102 const auto current_a_time{Now<NodeSeconds>()};
5105 const auto current_time = GetTime<std::chrono::microseconds>();
5107 LOCK(peer->m_addr_token_bucket_mutex);
5110 const auto time_diff =
5111 std::max(current_time - peer->m_addr_token_timestamp, 0us);
5112 const double increment =
5114 peer->m_addr_token_bucket =
5115 std::min<double>(peer->m_addr_token_bucket + increment,
5119 peer->m_addr_token_timestamp = current_time;
5121 const bool rate_limited =
5123 uint64_t num_proc = 0;
5124 uint64_t num_rate_limit = 0;
5125 Shuffle(vAddr.begin(), vAddr.end(), m_rng);
5127 if (interruptMsgProc) {
5132 LOCK(peer->m_addr_token_bucket_mutex);
5134 if (peer->m_addr_token_bucket < 1.0) {
5140 peer->m_addr_token_bucket -= 1.0;
5153 addr.
nTime > current_a_time + 10min) {
5154 addr.
nTime = current_a_time - 5 * 24h;
5156 AddAddressKnown(*peer, addr);
5165 if (addr.
nTime > current_a_time - 10min && !peer->m_getaddr_sent &&
5168 RelayAddress(pfrom.
GetId(), addr, fReachable);
5172 vAddrOk.push_back(addr);
5175 peer->m_addr_processed += num_proc;
5176 peer->m_addr_rate_limited += num_rate_limit;
5178 "Received addr: %u addresses (%u processed, %u rate-limited) "
5180 vAddr.size(), num_proc, num_rate_limit, pfrom.
GetId());
5182 m_addrman.
Add(vAddrOk, pfrom.
addr, 2h);
5183 if (vAddr.size() < 1000) {
5184 peer->m_getaddr_sent =
false;
5191 "addrfetch connection completed peer=%d; disconnecting\n",
5199 peer->m_wants_addrv2 =
true;
5204 peer->m_prefers_headers =
true;
5209 bool sendcmpct_hb{
false};
5210 uint64_t sendcmpct_version{0};
5211 vRecv >> sendcmpct_hb >> sendcmpct_version;
5218 CNodeState *nodestate = State(pfrom.
GetId());
5219 nodestate->m_provides_cmpctblocks =
true;
5220 nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb;
5229 std::vector<CInv> vInv;
5232 Misbehaving(*peer,
strprintf(
"inv message size = %u", vInv.size()));
5236 const bool reject_tx_invs{RejectIncomingTxs(pfrom)};
5237 std::unordered_set<TxId, SaltedTxIdHasher> seen_txids{0, m_txid_hasher};
5239 const auto current_time{GetTime<std::chrono::microseconds>()};
5240 std::optional<BlockHash> best_block;
5242 auto logInv = [&](
const CInv &inv,
bool fAlreadyHave) {
5244 fAlreadyHave ?
"have" :
"new", pfrom.GetId());
5247 for (
CInv &inv : vInv) {
5248 if (interruptMsgProc) {
5260 const bool fAlreadyHave = AlreadyHaveBlock(
BlockHash(inv.
hash));
5261 logInv(inv, fAlreadyHave);
5264 UpdateBlockAvailability(pfrom.
GetId(), hash);
5266 !IsBlockRequested(hash)) {
5273 best_block = std::move(hash);
5284 const bool fAlreadyHave = AlreadyHaveProof(proofid);
5285 logInv(inv, fAlreadyHave);
5286 AddKnownProof(*peer, proofid);
5288 if (!fAlreadyHave && m_avalanche &&
5290 const bool preferred = isPreferredDownloadPeer(pfrom);
5292 LOCK(cs_proofrequest);
5293 AddProofAnnouncement(pfrom, proofid, current_time,
5302 AddKnownTx(*peer, txid);
5303 if (reject_tx_invs) {
5305 "transaction (%s) inv sent in violation of "
5306 "protocol, disconnecting peer=%d\n",
5312 if (!seen_txids.insert(txid).second) {
5317 const bool fAlreadyHave{m_txdownloadman.AddTxAnnouncement(
5318 pfrom.
GetId(), txid, current_time)};
5319 logInv(inv, fAlreadyHave);
5326 "Unknown inv type \"%s\" received from peer=%d\n",
5343 if (state.fSyncStarted ||
5344 (!peer->m_inv_triggered_getheaders_before_sync &&
5345 *best_block != m_last_block_inv_triggering_headers_sync)) {
5346 if (MaybeSendGetHeaders(
5347 pfrom,
GetLocator(m_chainman.m_best_header), *peer)) {
5349 m_chainman.m_best_header->nHeight,
5350 best_block->ToString(), pfrom.
GetId());
5352 if (!state.fSyncStarted) {
5353 peer->m_inv_triggered_getheaders_before_sync =
true;
5357 m_last_block_inv_triggering_headers_sync = *best_block;
5366 std::vector<CInv> vInv;
5370 strprintf(
"getdata message size = %u", vInv.size()));
5375 vInv.size(), pfrom.
GetId());
5377 if (vInv.size() > 0) {
5383 LOCK(peer->m_getdata_requests_mutex);
5384 peer->m_getdata_requests.insert(peer->m_getdata_requests.end(),
5385 vInv.begin(), vInv.end());
5386 ProcessGetData(config, pfrom, *peer, interruptMsgProc);
5395 vRecv >> locator >> hashStop;
5399 "getblocks locator size %lld > %d, disconnect peer=%d\n",
5413 std::shared_ptr<const CBlock> a_recent_block;
5415 LOCK(m_most_recent_block_mutex);
5416 a_recent_block = m_most_recent_block;
5420 state, a_recent_block, m_avalanche)) {
5438 (pindex ? pindex->
nHeight : -1),
5439 hashStop.IsNull() ?
"end" : hashStop.
ToString(), nLimit,
5441 for (; pindex; pindex = m_chainman.
ActiveChain().Next(pindex)) {
5450 const int nPrunedBlocksLikelyToHave =
5454 (!pindex->nStatus.hasData() ||
5456 nPrunedBlocksLikelyToHave)) {
5459 " getblocks stopping, pruned or too old block at %d %s\n",
5464 peer->m_block_inv_mutex,
5465 peer->m_blocks_for_inv_relay.push_back(pindex->
GetBlockHash()));
5466 if (--nLimit <= 0) {
5472 peer->m_continuation_block = pindex->GetBlockHash();
5487 "getblocktxn received with no transaction indexes, "
5488 "disconnecting peer=%d\n",
5494 std::shared_ptr<const CBlock> recent_block;
5496 LOCK(m_most_recent_block_mutex);
5497 if (m_most_recent_block_hash == req.
blockhash) {
5498 recent_block = m_most_recent_block;
5503 SendBlockTransactions(pfrom, *peer, *recent_block, req);
5513 if (!pindex || !pindex->nStatus.hasData()) {
5516 "Peer %d sent us a getblocktxn for a block we don't have\n",
5527 if (!block_pos.IsNull()) {
5534 LogError(
"getblocktxn: block read failed for block %s\n",
5540 SendBlockTransactions(pfrom, *peer, block, req);
5552 "Peer %d sent us a getblocktxn for a block > %i deep\n",
5557 WITH_LOCK(peer->m_getdata_requests_mutex,
5558 peer->m_getdata_requests.push_back(inv));
5567 vRecv >> locator >> hashStop;
5571 "getheaders locator size %lld > %d, disconnect peer=%d\n",
5580 "Ignoring getheaders from peer=%d while importing/reindexing\n",
5594 if (m_chainman.
ActiveTip() ==
nullptr ||
5599 "Ignoring getheaders from peer=%d because active chain "
5600 "has too little work; sending empty response\n",
5605 std::vector<CBlock>());
5609 CNodeState *nodestate = State(pfrom.
GetId());
5618 if (!BlockRequestAllowed(pindex)) {
5620 "%s: ignoring request from peer=%i for old block "
5621 "header that isn't in the main chain\n",
5622 __func__, pfrom.
GetId());
5636 std::vector<CBlock> vHeaders;
5639 (pindex ? pindex->
nHeight : -1),
5640 hashStop.IsNull() ?
"end" : hashStop.
ToString(),
5642 for (; pindex; pindex = m_chainman.
ActiveChain().Next(pindex)) {
5644 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) {
5661 nodestate->pindexBestHeaderSent =
5668 if (RejectIncomingTxs(pfrom)) {
5670 "transaction sent in violation of protocol peer=%d\n",
5688 AddKnownTx(*peer, txid);
5693 const auto &[should_validate, reconsiderable_package] =
5694 m_txdownloadman.ReceivedTx(pfrom.
GetId(), ptx);
5695 if (!should_validate) {
5703 "Not relaying non-mempool transaction %s from "
5704 "forcerelay peer=%d\n",
5707 LogPrintf(
"Force relaying tx %s from peer=%d\n",
5709 RelayTransaction(tx.
GetId());
5713 if (reconsiderable_package) {
5716 reconsiderable_package->m_txns,
5719 "package evaluation for %s: %s (%s)\n",
5720 reconsiderable_package->ToString(),
5722 ?
"package accepted"
5723 :
"package rejected",
5724 package_result.m_state.
ToString());
5725 ProcessPackageResult(reconsiderable_package.value(),
5733 Assume(!reconsiderable_package.has_value());
5741 ProcessValidTx(pfrom.
GetId(), ptx);
5745 if (
auto package_to_validate{
5746 ProcessInvalidTx(pfrom.
GetId(), ptx, state,
5750 package_to_validate->
m_txns,
false)};
5752 "package evaluation for %s: %s (%s)\n",
5755 ?
"package accepted"
5756 :
"package rejected",
5757 package_result.m_state.
ToString());
5758 ProcessPackageResult(package_to_validate.value(),
5767 m_txdownloadman.GetTxRequestRef().ForgetInvId(tx.
GetId());
5769 unsigned int nEvicted{0};
5776 m_opts.max_conflicting_txs, m_rng);
5781 "conflicting pool overflow, removed %u tx\n",
5794 "Unexpected cmpctblock message received from peer %d\n",
5801 vRecv >> cmpctblock;
5802 }
catch (std::ios_base::failure &e) {
5804 Misbehaving(*peer,
"cmpctblock-bad-indexes");
5808 bool received_new_header =
false;
5821 MaybeSendGetHeaders(
5822 pfrom,
GetLocator(m_chainman.m_best_header), *peer);
5828 GetAntiDoSWorkThreshold()) {
5832 "Ignoring low-work compact block from peer %d\n",
5838 received_new_header =
true;
5848 MaybePunishNodeForBlock(pfrom.
GetId(), state,
5850 "invalid header via cmpctblock");
5855 if (received_new_header) {
5856 LogInfo(
"Saw new cmpctblock header hash=%s peer=%d\n",
5857 blockhash.ToString(), pfrom.
GetId());
5860 bool fProcessBLOCKTXN =
false;
5865 bool fRevertToHeaderProcessing =
false;
5869 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
5870 bool fBlockReconstructed =
false;
5878 "cmpctblock: header accepted but no pindex for block %s\n",
5879 blockhash.ToString());
5886 CNodeState *nodestate = State(pfrom.
GetId());
5890 if (received_new_header &&
5893 nodestate->m_last_block_announcement =
GetTime();
5896 if (pindex->nStatus.hasData()) {
5903 size_t already_in_flight =
5904 std::distance(range_flight.first, range_flight.second);
5905 bool requested_block_from_this_peer{
false};
5909 bool first_in_flight =
5910 already_in_flight == 0 ||
5911 (range_flight.first->second.first == pfrom.
GetId());
5913 while (range_flight.first != range_flight.second) {
5914 if (range_flight.first->second.first == pfrom.
GetId()) {
5915 requested_block_from_this_peer =
true;
5918 range_flight.first++;
5927 if (requested_block_from_this_peer) {
5931 std::vector<CInv> vInv(1);
5940 if (!already_in_flight && !CanDirectFetch()) {
5948 nodestate->vBlocksInFlight.size() <
5950 requested_block_from_this_peer) {
5951 std::list<QueuedBlock>::iterator *queuedBlockIt =
nullptr;
5952 if (!BlockRequested(config, pfrom.
GetId(), *pindex,
5954 if (!(*queuedBlockIt)->partialBlock) {
5956 ->partialBlock.reset(
5963 "we were already syncing!\n");
5969 *(*queuedBlockIt)->partialBlock;
5971 partialBlock.
InitData(cmpctblock, vExtraTxnForCompact);
5977 Misbehaving(*peer,
"invalid compact block");
5980 if (first_in_flight) {
5983 std::vector<CInv> vInv(1);
5996 for (
size_t i = 0; i < cmpctblock.
BlockTxCount(); i++) {
6002 fProcessBLOCKTXN =
true;
6003 }
else if (first_in_flight) {
6010 IsBlockRequestedFromOutbound(blockhash) ||
6033 tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
6038 std::vector<CTransactionRef> dummy;
6039 status = tempBlock.FillBlock(*pblock, dummy);
6041 fBlockReconstructed =
true;
6045 if (requested_block_from_this_peer) {
6049 std::vector<CInv> vInv(1);
6056 fRevertToHeaderProcessing =
true;
6061 if (fProcessBLOCKTXN) {
6064 return ProcessCompactBlockTxns(config, pfrom, *peer, txn);
6067 if (fRevertToHeaderProcessing) {
6073 return ProcessHeadersMessage(config, pfrom, *peer,
6078 if (fBlockReconstructed) {
6083 mapBlockSource.emplace(pblock->GetHash(),
6084 std::make_pair(pfrom.
GetId(),
false));
6095 ProcessBlock(config, pfrom, pblock,
true,
6104 RemoveBlockRequest(pblock->GetHash(), std::nullopt);
6114 "Unexpected blocktxn message received from peer %d\n",
6122 return ProcessCompactBlockTxns(config, pfrom, *peer, resp);
6129 "Unexpected headers message received from peer %d\n",
6134 std::vector<CBlockHeader> headers;
6141 strprintf(
"too-many-headers: headers message size = %u",
6145 headers.resize(nCount);
6146 for (
unsigned int n = 0; n < nCount; n++) {
6147 vRecv >> headers[n];
6152 ProcessHeadersMessage(config, pfrom, *peer, std::move(headers),
6158 if (m_headers_presync_should_signal.exchange(
false)) {
6159 HeadersPresyncStats stats;
6161 LOCK(m_headers_presync_mutex);
6163 m_headers_presync_stats.find(m_headers_presync_bestpeer);
6164 if (it != m_headers_presync_stats.end()) {
6170 stats.first, stats.second->first, stats.second->second);
6181 "Unexpected block message received from peer %d\n",
6186 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
6190 pblock->GetHash().ToString(), pfrom.
GetId());
6195 pblock->hashPrevBlock))};
6199 "Received mutated block from peer=%d\n", peer->m_id);
6200 Misbehaving(*peer,
"mutated block");
6202 RemoveBlockRequest(pblock->GetHash(), peer->m_id));
6212 const BlockHash hash = pblock->GetHash();
6213 bool min_pow_checked =
false;
6218 forceProcessing = IsBlockRequested(hash);
6219 RemoveBlockRequest(hash, pfrom.
GetId());
6223 mapBlockSource.emplace(hash, std::make_pair(pfrom.
GetId(),
true));
6228 {pblock->GetBlockHeader()}) >=
6229 GetAntiDoSWorkThreshold()) {
6230 min_pow_checked =
true;
6233 ProcessBlock(config, pfrom, pblock, forceProcessing, min_pow_checked);
6243 if (pfrom.m_avalanche_pubkey.has_value()) {
6246 "Ignoring avahello from peer %d: already in our node set\n",
6252 vRecv >> delegation;
6259 if (!delegation.
verify(state, pubkey)) {
6260 Misbehaving(*peer,
"invalid-delegation");
6263 pfrom.m_avalanche_pubkey = std::move(pubkey);
6266 sighasher << delegation.
getId();
6274 if (!(*pfrom.m_avalanche_pubkey)
6275 .VerifySchnorr(sighasher.GetHash(),
sig)) {
6276 Misbehaving(*peer,
"invalid-avahello-signature");
6283 if (!AlreadyHaveProof(proofid)) {
6284 const bool preferred = isPreferredDownloadPeer(pfrom);
6285 LOCK(cs_proofrequest);
6286 AddProofAnnouncement(pfrom, proofid,
6287 GetTime<std::chrono::microseconds>(),
6295 vRecv >> max_elements;
6299 Misbehaving(*peer,
"avahello-max-elements-too-low");
6304 max_elements = std::min(
6310 return pm.
addNode(pfrom.
GetId(), proofid, max_elements);
6321 WITH_LOCK(peer->m_addr_token_bucket_mutex,
6322 peer->m_addr_token_bucket += m_opts.max_addr_to_send);
6326 peer->m_proof_relay->compactproofs_requested =
true;
6337 const auto now = Now<SteadyMilliseconds>();
6343 last_poll + std::chrono::milliseconds(m_opts.avalanche_cooldown)) {
6345 "Ignoring repeated avapoll from peer %d: cooldown not "
6360 strprintf(
"too-many-ava-poll: poll message size = %u", nCount));
6364 std::vector<avalanche::Vote> votes;
6365 votes.reserve(nCount);
6367 bool fPreconsensus{
false};
6368 bool fStakingPreconsensus{
false};
6373 fStakingPreconsensus =
6377 for (
unsigned int n = 0; n < nCount; n++) {
6385 if (!quorum_established) {
6386 votes.emplace_back(vote, inv.
hash);
6393 if (fPreconsensus) {
6395 return GetAvalancheVoteForTx(
6408 if (fStakingPreconsensus) {
6415 "poll inv type %d unknown from peer=%d\n",
6420 votes.emplace_back(vote, inv.
hash);
6446 if (!pfrom.m_avalanche_pubkey.has_value() ||
6447 !(*pfrom.m_avalanche_pubkey)
6448 .VerifySchnorr(verifier.GetHash(),
sig)) {
6449 Misbehaving(*peer,
"invalid-ava-response-signature");
6454 auto now = GetTime<std::chrono::seconds>();
6456 std::vector<avalanche::VoteItemUpdate> updates;
6457 bool disconnect{
false};
6460 disconnect, error)) {
6462 Misbehaving(*peer, error);
6480 "Repeated failure to register votes from peer %d: %s\n",
6481 pfrom.
GetId(), error);
6484 Misbehaving(*peer, error);
6497 auto logVoteUpdate = [](
const auto &voteUpdate,
6498 const std::string &voteItemTypeStr,
6499 const auto &voteItemId) {
6500 std::string voteOutcome;
6501 bool alwaysPrint =
false;
6502 switch (voteUpdate.getStatus()) {
6504 voteOutcome =
"invalidated";
6508 voteOutcome =
"rejected";
6511 voteOutcome =
"accepted";
6514 voteOutcome =
"finalized";
6517 alwaysPrint = voteItemTypeStr !=
"tx";
6520 voteOutcome =
"stalled";
6529 alwaysPrint &= (voteItemTypeStr !=
"contender");
6532 LogPrintf(
"Avalanche %s %s %s\n", voteOutcome, voteItemTypeStr,
6533 voteItemId.ToString());
6537 voteItemTypeStr, voteItemId.ToString());
6541 bool shouldActivateBestChain =
false;
6543 bool fPreconsensus{
false};
6544 bool fStakingPreconsensus{
false};
6549 fStakingPreconsensus =
6553 for (
const auto &u : updates) {
6558 if (
auto pitem = std::get_if<const avalanche::ProofRef>(&item)) {
6562 logVoteUpdate(u,
"proof", proofid);
6564 auto rejectionMode =
6566 auto nextCooldownTimePoint = GetTime<std::chrono::seconds>();
6567 switch (u.getStatus()) {
6583 return pm.rejectProof(proofid,
6587 "ERROR: Failed to reject proof: %s\n",
6593 nextCooldownTimePoint += std::chrono::seconds(
6594 m_opts.avalanche_peer_replacement_cooldown);
6600 avalanche::PeerManager::
6601 RegistrationMode::FORCE_ACCEPT);
6604 [&](const avalanche::Peer &peer) {
6605 pm.updateNextPossibleConflictTime(
6607 nextCooldownTimePoint);
6608 if (u.getStatus() ==
6609 avalanche::VoteStatus::
6611 pm.setFinalized(peer.peerid);
6619 "ERROR: Failed to accept proof: %s\n",
6626 auto getBlockFromIndex = [
this](
const CBlockIndex *pindex)
6627 -> std::shared_ptr<const CBlock> {
6630 std::shared_ptr<const CBlock> pblock =
WITH_LOCK(
6631 m_most_recent_block_mutex,
return m_most_recent_block);
6633 if (!pblock || pblock->GetHash() != pindex->
GetBlockHash()) {
6634 std::shared_ptr<CBlock> pblockRead =
6635 std::make_shared<CBlock>();
6638 LogError(
"getBlockFromIndex: cannot load block from "
6643 pblock = pblockRead;
6648 if (
auto pitem = std::get_if<const CBlockIndex *>(&item)) {
6651 shouldActivateBestChain =
true;
6655 switch (u.getStatus()) {
6660 LogPrintf(
"ERROR: Database error: %s\n",
6669 LogPrintf(
"ERROR: Database error: %s\n",
6674 auto pblock = getBlockFromIndex(pindex);
6676 LogError(
"avaresponse: failed to get invalidated "
6677 "block from index\n");
6696 std::unique_ptr<node::CBlockTemplate> blockTemplate;
6700 chainstate.UnparkBlock(pindex);
6702 const bool newlyFinalized =
6703 !chainstate.IsBlockAvalancheFinalized(pindex) &&
6704 chainstate.AvalancheFinalizeBlock(pindex,
6709 if (fPreconsensus && newlyFinalized) {
6719 std::unordered_set<TxId, SaltedTxIdHasher>
6720 confirmedTxIdsInNonFinalizedBlocks;
6721 bool missing_block =
false;
6723 block !=
nullptr && block != pindex;
6724 block = block->pprev) {
6726 getBlockFromIndex(block);
6727 if (!currentBlock) {
6729 "avaresponse: failed to get "
6730 "finalized block descendant from "
6733 missing_block =
true;
6736 for (
const auto &tx : currentBlock->vtx) {
6737 confirmedTxIdsInNonFinalizedBlocks
6738 .insert(tx->
GetId());
6742 if (missing_block) {
6754 confirmedTxIdsInNonFinalizedBlocks);
6766 config, chainstate, &m_mempool,
6768 blockAssembler.pblocktemplate.reset(
6771 if (blockAssembler.pblocktemplate) {
6772 blockAssembler.addTxs(m_mempool);
6773 blockTemplate = std::move(
6774 blockAssembler.pblocktemplate);
6779 if (blockTemplate) {
6784 for (
const auto &templateEntry :
6798 if (fStakingPreconsensus) {
6800 std::get_if<const avalanche::StakeContenderId>(&item)) {
6802 logVoteUpdate(u,
"contender", contenderId);
6804 switch (u.getStatus()) {
6825 if (!fPreconsensus) {
6829 if (
auto pitem = std::get_if<const CTransactionRef>(&item)) {
6833 const TxId &txid = tx->GetId();
6834 const auto status{u.getStatus()};
6839 logVoteUpdate(u,
"tx", txid);
6852 std::shared_ptr<const std::vector<Coin>> spentCoins;
6864 _spentCoins.has_value()
6865 ? std::make_shared<const std::vector<Coin>>(
6866 std::move(*_spentCoins))
6870 if (m_mempool.
exists(txid)) {
6874 std::vector<CTransactionRef> conflictingTxs =
6880 if (conflictingTxs.size() > 0) {
6888 "Attempting to pull a now invalid "
6889 "conflicting tx %s to mempool\n",
6890 conflictingTxs[0]->GetId().
ToString());
6897 for (
const auto &conflictingTx :
6900 conflictingTx->GetId());
6919 m_txdownloadman.RecentRejectsFilter().insert(txid);
6921 AddToCompactExtraTransactions(tx);
6939 return conflicting.HaveTx(txid);
6942 std::vector<CTransactionRef>
6943 mempool_conflicting_txs;
6944 for (
const auto &txin : tx->vin) {
6949 mempool_conflicting_txs.push_back(
6950 std::move(conflict));
6957 LogError(
"accepted tx %s failed mempool "
6965 [&txid, &mempool_conflicting_txs](
6970 if (mempool_conflicting_txs.size() >
6973 mempool_conflicting_txs[0],
6983 auto it = m_mempool.
GetIter(txid);
6984 if (!it.has_value()) {
6987 "Error: finalized tx (%s) is not in the "
6993 std::vector<TxId> finalizedTxIds;
6994 m_mempool.setAvalancheFinalized(
6999 for (
const auto &finalized_txid : finalizedTxIds) {
7004 logVoteUpdate(u,
"tx", finalized_txid);
7013 std::vector<CTransactionRef>
7016 for (
const auto &conflictingTx :
7019 .RecentRejectsFilter()
7020 .insert(conflictingTx->GetId());
7022 conflictingTx->GetId());
7030 LOCK(m_tx_download_mutex);
7048 m_txdownloadman.GetTxRequestRef().ForgetInvId(txid);
7054 for (
auto &it : m_peer_map) {
7055 auto tx_relay = (*it.second).GetTxRelay();
7060 LOCK(tx_relay->m_tx_inventory_mutex);
7067 auto &stalled_by_time =
7068 tx_relay->m_avalanche_stalled_txids
7070 if (stalled_by_time.size() >=
7072 stalled_by_time.erase(
7073 stalled_by_time.begin()->timeAdded);
7076 tx_relay->m_avalanche_stalled_txids.insert(
7081 AddToCompactExtraTransactions(tx);
7089 if (shouldActivateBestChain) {
7092 state,
nullptr, m_avalanche)) {
7107 ReceivedAvalancheProof(pfrom, *peer, proof);
7116 if (peer->m_proof_relay ==
nullptr) {
7120 auto now = GetTime<std::chrono::seconds>();
7121 if (now < peer->m_next_getavaproofs) {
7130 peer->m_proof_relay->lastSharedProofsUpdate = now;
7132 peer->m_proof_relay->sharedProofs =
7138 peer->m_proof_relay->sharedProofs);
7148 if (peer->m_proof_relay ==
nullptr) {
7153 if (!peer->m_proof_relay->compactproofs_requested) {
7157 peer->m_proof_relay->compactproofs_requested =
false;
7161 vRecv >> compactProofs;
7162 }
catch (std::ios_base::failure &e) {
7164 Misbehaving(*peer,
"avaproofs-bad-indexes");
7169 for (
const auto &prefilledProof : compactProofs.getPrefilledProofs()) {
7170 if (!ReceivedAvalancheProof(pfrom, *peer, prefilledProof.proof)) {
7200 auto shortIdProcessor =
7204 if (shortIdProcessor.hasOutOfBoundIndex()) {
7207 Misbehaving(*peer,
"avaproofs-bad-indexes");
7210 if (!shortIdProcessor.isEvenlyDistributed()) {
7215 std::vector<std::pair<avalanche::ProofId, bool>> remoteProofsStatus;
7219 uint64_t shortid = compactProofs.
getShortID(proofid);
7221 int added = shortIdProcessor.matchKnownItem(shortid, proof);
7233 remoteProofsStatus.emplace_back(proofid, added > 0);
7238 matchKnownProof(peer.
proof);
7247 matchKnownProof(proof);
7252 for (
size_t i = 0; i < compactProofs.
size(); i++) {
7253 if (shortIdProcessor.getItem(i) ==
nullptr) {
7269 return pfrom.m_avalanche_pubkey.has_value())) {
7274 for (
const auto &[proofid, present] : remoteProofsStatus) {
7284 if (peer->m_proof_relay ==
nullptr) {
7291 auto requestedIndiceIt = proofreq.
indices.begin();
7292 uint32_t treeIndice = 0;
7293 peer->m_proof_relay->sharedProofs.forEachLeaf([&](
const auto &proof) {
7294 if (requestedIndiceIt == proofreq.
indices.end()) {
7299 if (treeIndice++ == *requestedIndiceIt) {
7301 requestedIndiceIt++;
7307 peer->m_proof_relay->sharedProofs = {};
7320 "Ignoring \"getaddr\" from %s connection. peer=%d\n",
7327 Assume(SetupAddressRelay(pfrom, *peer));
7331 if (peer->m_getaddr_recvd) {
7336 peer->m_getaddr_recvd =
true;
7338 peer->m_addrs_to_send.clear();
7339 std::vector<CAddress> vAddr;
7340 const size_t maxAddrToSend = m_opts.max_addr_to_send;
7348 for (
const CAddress &addr : vAddr) {
7349 PushAddress(*peer, addr);
7355 auto now = GetTime<std::chrono::seconds>();
7356 if (now < peer->m_next_getavaaddr) {
7365 if (!SetupAddressRelay(pfrom, *peer)) {
7367 "Ignoring getavaaddr message from %s peer=%d\n",
7372 using AvaNodeInfo = std::tuple<CAddress, NodeId, double>;
7373 auto availabilityScoreComparator = [](
const AvaNodeInfo &lhs,
7374 const AvaNodeInfo &rhs) {
7375 double scoreLhs = std::get<double>(lhs);
7376 double scoreRhs = std::get<double>(rhs);
7378 if (scoreLhs != scoreRhs) {
7379 return scoreLhs > scoreRhs;
7382 return std::get<NodeId>(lhs) < std::get<NodeId>(rhs);
7388 std::set<AvaNodeInfo,
decltype(availabilityScoreComparator)> avaNodes(
7389 availabilityScoreComparator);
7396 avaNodes.insert(AvaNodeInfo{pnode->
addr, pnode->
GetId(), score});
7397 if (avaNodes.size() > m_opts.max_addr_to_send) {
7398 avaNodes.erase(std::prev(avaNodes.end()));
7402 peer->m_addrs_to_send.clear();
7403 for (
const auto &nodeInfo : avaNodes) {
7404 PushAddress(*peer, std::get<CAddress>(nodeInfo));
7415 "mempool request with bloom filters disabled, "
7416 "disconnect peer=%d\n",
7427 "mempool request with bandwidth limit reached, "
7428 "disconnect peer=%d\n",
7435 if (
auto tx_relay = peer->GetTxRelay()) {
7436 LOCK(tx_relay->m_tx_inventory_mutex);
7437 tx_relay->m_send_mempool =
true;
7463 const auto ping_end = time_received;
7466 bool bPingFinished =
false;
7467 std::string sProblem;
7469 if (nAvail >=
sizeof(nonce)) {
7474 if (peer->m_ping_nonce_sent != 0) {
7475 if (nonce == peer->m_ping_nonce_sent) {
7478 bPingFinished =
true;
7479 const auto ping_time = ping_end - peer->m_ping_start.load();
7480 if (ping_time.count() >= 0) {
7485 sProblem =
"Timing mishap";
7489 sProblem =
"Nonce mismatch";
7493 bPingFinished =
true;
7494 sProblem =
"Nonce zero";
7498 sProblem =
"Unsolicited pong without ping";
7503 bPingFinished =
true;
7504 sProblem =
"Short payload";
7507 if (!(sProblem.empty())) {
7509 "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
7510 pfrom.
GetId(), sProblem, peer->m_ping_nonce_sent, nonce,
7513 if (bPingFinished) {
7514 peer->m_ping_nonce_sent = 0;
7522 "filterload received despite not offering bloom services "
7523 "from peer=%d; disconnecting\n",
7533 Misbehaving(*peer,
"too-large bloom filter");
7534 }
else if (
auto tx_relay = peer->GetTxRelay()) {
7536 LOCK(tx_relay->m_bloom_filter_mutex);
7537 tx_relay->m_bloom_filter.reset(
new CBloomFilter(filter));
7538 tx_relay->m_relay_txs =
true;
7548 "filteradd received despite not offering bloom services "
7549 "from peer=%d; disconnecting\n",
7554 std::vector<uint8_t> vData;
7563 }
else if (
auto tx_relay = peer->GetTxRelay()) {
7564 LOCK(tx_relay->m_bloom_filter_mutex);
7565 if (tx_relay->m_bloom_filter) {
7566 tx_relay->m_bloom_filter->insert(vData);
7574 Misbehaving(*peer,
"bad filteradd message");
7582 "filterclear received despite not offering bloom services "
7583 "from peer=%d; disconnecting\n",
7588 auto tx_relay = peer->GetTxRelay();
7594 LOCK(tx_relay->m_bloom_filter_mutex);
7595 tx_relay->m_bloom_filter =
nullptr;
7596 tx_relay->m_relay_txs =
true;
7605 vRecv >> newFeeFilter;
7607 if (
auto tx_relay = peer->GetTxRelay()) {
7608 tx_relay->m_fee_filter_received = newFeeFilter;
7617 ProcessGetCFilters(pfrom, *peer, vRecv);
7622 ProcessGetCFHeaders(pfrom, *peer, vRecv);
7627 ProcessGetCFCheckPt(pfrom, *peer, vRecv);
7632 std::vector<CInv> vInv;
7634 std::vector<TxId> tx_invs;
7639 for (
CInv &inv : vInv) {
7641 tx_invs.emplace_back(inv.
hash);
7648 LOCK(cs_proofrequest);
7649 m_proofrequest.ReceivedResponse(
7654 LOCK(m_tx_download_mutex);
7655 m_txdownloadman.ReceivedNotFound(pfrom.
GetId(), tx_invs);
7665bool PeerManagerImpl::MaybeDiscourageAndDisconnect(
CNode &pnode, Peer &peer) {
7667 LOCK(peer.m_misbehavior_mutex);
7670 if (!peer.m_should_discourage) {
7674 peer.m_should_discourage =
false;
7680 LogPrintf(
"Warning: not punishing noban peer %d!\n", peer.m_id);
7686 LogPrintf(
"Warning: not punishing manually connected peer %d!\n",
7695 "Warning: disconnecting but not discouraging %s peer %d!\n",
7712bool PeerManagerImpl::ProcessMessages(
const Config &config,
CNode *pfrom,
7713 std::atomic<bool> &interruptMsgProc) {
7717 PeerRef peer = GetPeerRef(pfrom->
GetId());
7718 if (peer ==
nullptr) {
7723 LOCK(peer->m_getdata_requests_mutex);
7724 if (!peer->m_getdata_requests.empty()) {
7725 ProcessGetData(config, *pfrom, *peer, interruptMsgProc);
7729 const bool processed_orphan = ProcessOrphanTx(config, *peer);
7735 if (processed_orphan) {
7742 LOCK(peer->m_getdata_requests_mutex);
7743 if (!peer->m_getdata_requests.empty()) {
7760 bool fMoreWork = poll_result->second;
7764 msg.m_recv.size(),
msg.m_recv.data());
7766 if (m_opts.capture_messages) {
7772 ProcessMessage(config, *pfrom,
msg.m_type,
msg.m_recv,
msg.m_time,
7774 if (interruptMsgProc) {
7779 LOCK(peer->m_getdata_requests_mutex);
7780 if (!peer->m_getdata_requests.empty()) {
7788 LOCK(m_tx_download_mutex);
7789 if (m_txdownloadman.HaveMoreWork(peer->m_id)) {
7792 }
catch (
const std::exception &e) {
7795 e.what(),
typeid(e).name());
7804void PeerManagerImpl::ConsiderEviction(
CNode &pto, Peer &peer,
7805 std::chrono::seconds time_in_seconds) {
7808 CNodeState &state = *State(pto.
GetId());
7811 state.fSyncStarted) {
7818 if (state.pindexBestKnownBlock !=
nullptr &&
7819 state.pindexBestKnownBlock->nChainWork >=
7821 if (state.m_chain_sync.m_timeout != 0s) {
7822 state.m_chain_sync.m_timeout = 0s;
7823 state.m_chain_sync.m_work_header =
nullptr;
7824 state.m_chain_sync.m_sent_getheaders =
false;
7826 }
else if (state.m_chain_sync.m_timeout == 0s ||
7827 (state.m_chain_sync.m_work_header !=
nullptr &&
7828 state.pindexBestKnownBlock !=
nullptr &&
7829 state.pindexBestKnownBlock->nChainWork >=
7830 state.m_chain_sync.m_work_header->nChainWork)) {
7836 state.m_chain_sync.m_work_header = m_chainman.
ActiveChain().
Tip();
7837 state.m_chain_sync.m_sent_getheaders =
false;
7838 }
else if (state.m_chain_sync.m_timeout > 0s &&
7839 time_in_seconds > state.m_chain_sync.m_timeout) {
7844 if (state.m_chain_sync.m_sent_getheaders) {
7847 "Disconnecting outbound peer %d for old chain, best known "
7850 state.pindexBestKnownBlock !=
nullptr
7851 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7855 assert(state.m_chain_sync.m_work_header);
7860 MaybeSendGetHeaders(
7861 pto,
GetLocator(state.m_chain_sync.m_work_header->pprev),
7865 "sending getheaders to outbound peer=%d to verify chain "
7866 "work (current best known block:%s, benchmark blockhash: "
7869 state.pindexBestKnownBlock !=
nullptr
7870 ? state.pindexBestKnownBlock->GetBlockHash().ToString()
7872 state.m_chain_sync.m_work_header->GetBlockHash()
7874 state.m_chain_sync.m_sent_getheaders =
true;
7881 state.m_chain_sync.m_timeout =
7888void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) {
7897 std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0},
7898 next_youngest_peer{-1, 0};
7904 if (pnode->
GetId() > youngest_peer.first) {
7905 next_youngest_peer = youngest_peer;
7906 youngest_peer.first = pnode->GetId();
7907 youngest_peer.second = pnode->m_last_block_time;
7911 NodeId to_disconnect = youngest_peer.first;
7912 if (youngest_peer.second > next_youngest_peer.second) {
7915 to_disconnect = next_youngest_peer.first;
7927 CNodeState *node_state = State(pnode->
GetId());
7928 if (node_state ==
nullptr ||
7930 node_state->vBlocksInFlight.empty())) {
7933 "disconnecting extra block-relay-only peer=%d "
7934 "(last block received at time %d)\n",
7941 "keeping block-relay-only peer=%d chosen for eviction "
7942 "(connect time: %d, blocks_in_flight: %d)\n",
7944 node_state->vBlocksInFlight.size());
7960 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
7971 CNodeState *state = State(pnode->
GetId());
7972 if (state ==
nullptr) {
7977 if (state->m_chain_sync.m_protect) {
7980 if (state->m_last_block_announcement < oldest_block_announcement ||
7981 (state->m_last_block_announcement == oldest_block_announcement &&
7982 pnode->
GetId() > worst_peer)) {
7983 worst_peer = pnode->
GetId();
7984 oldest_block_announcement = state->m_last_block_announcement;
7988 if (worst_peer == -1) {
7992 bool disconnected = m_connman.
ForNode(
8000 CNodeState &state = *State(pnode->
GetId());
8002 state.vBlocksInFlight.empty()) {
8004 "disconnecting extra outbound peer=%d (last block "
8005 "announcement received at time %d)\n",
8006 pnode->
GetId(), oldest_block_announcement);
8011 "keeping outbound peer=%d chosen for eviction "
8012 "(connect time: %d, blocks_in_flight: %d)\n",
8014 state.vBlocksInFlight.size());
8029void PeerManagerImpl::CheckForStaleTipAndEvictPeers() {
8032 auto now{GetTime<std::chrono::seconds>()};
8034 EvictExtraOutboundPeers(now);
8036 if (now > m_stale_tip_check_time) {
8042 LogPrintf(
"Potential stale tip detected, will try using extra "
8043 "outbound peer (last tip update: %d seconds ago)\n",
8052 if (!m_initial_sync_finished && CanDirectFetch()) {
8054 m_initial_sync_finished =
true;
8058void PeerManagerImpl::MaybeSendPing(
CNode &node_to, Peer &peer,
8059 std::chrono::microseconds now) {
8061 node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) &&
8062 peer.m_ping_nonce_sent &&
8073 bool pingSend =
false;
8075 if (peer.m_ping_queued) {
8080 if (peer.m_ping_nonce_sent == 0 &&
8090 }
while (nonce == 0);
8091 peer.m_ping_queued =
false;
8092 peer.m_ping_start = now;
8093 peer.m_ping_nonce_sent = nonce;
8098void PeerManagerImpl::MaybeSendAddr(
CNode &
node, Peer &peer,
8099 std::chrono::microseconds current_time) {
8101 if (!peer.m_addr_relay_enabled) {
8105 LOCK(peer.m_addr_send_times_mutex);
8107 peer.m_next_local_addr_send < current_time) {
8114 if (peer.m_next_local_addr_send != 0us) {
8115 peer.m_addr_known->reset();
8118 CAddress local_addr{*local_service, peer.m_our_services,
8119 Now<NodeSeconds>()};
8120 PushAddress(peer, local_addr);
8122 peer.m_next_local_addr_send =
8128 if (current_time <= peer.m_next_addr_send) {
8132 peer.m_next_addr_send =
8135 const size_t max_addr_to_send = m_opts.max_addr_to_send;
8136 if (!
Assume(peer.m_addrs_to_send.size() <= max_addr_to_send)) {
8139 peer.m_addrs_to_send.resize(max_addr_to_send);
8144 auto addr_already_known =
8147 bool ret = peer.m_addr_known->contains(addr.
GetKey());
8149 peer.m_addr_known->insert(addr.
GetKey());
8153 peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(),
8154 peer.m_addrs_to_send.end(),
8155 addr_already_known),
8156 peer.m_addrs_to_send.end());
8159 if (peer.m_addrs_to_send.empty()) {
8163 const char *msg_type;
8165 if (peer.m_wants_addrv2) {
8175 peer.m_addrs_to_send));
8176 peer.m_addrs_to_send.clear();
8179 if (peer.m_addrs_to_send.capacity() > 40) {
8180 peer.m_addrs_to_send.shrink_to_fit();
8184void PeerManagerImpl::MaybeSendSendHeaders(
CNode &
node, Peer &peer) {
8189 if (!peer.m_sent_sendheaders) {
8191 CNodeState &state = *State(
node.GetId());
8192 if (state.pindexBestKnownBlock !=
nullptr &&
8193 state.pindexBestKnownBlock->nChainWork >
8200 peer.m_sent_sendheaders =
true;
8205void PeerManagerImpl::MaybeSendFeefilter(
8206 CNode &pto, Peer &peer, std::chrono::microseconds current_time) {
8207 if (m_opts.ignore_incoming_txs) {
8228 static const Amount MAX_FILTER{m_fee_filter_rounder.round(
MAX_MONEY)};
8229 if (peer.m_fee_filter_sent == MAX_FILTER) {
8232 peer.m_next_send_feefilter = 0us;
8235 if (current_time > peer.m_next_send_feefilter) {
8236 Amount filterToSend = m_fee_filter_rounder.round(currentFilter);
8238 filterToSend = std::max(
8240 if (filterToSend != peer.m_fee_filter_sent) {
8242 peer.m_fee_filter_sent = filterToSend;
8244 peer.m_next_send_feefilter =
8252 peer.m_next_send_feefilter &&
8253 (currentFilter < 3 * peer.m_fee_filter_sent / 4 ||
8254 currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
8255 peer.m_next_send_feefilter =
8263class CompareInvMempoolOrder {
8267 explicit CompareInvMempoolOrder(
CTxMemPool *_mempool) : mp(_mempool) {}
8269 bool operator()(std::set<TxId>::iterator a, std::set<TxId>::iterator b) {
8279bool PeerManagerImpl::RejectIncomingTxs(
const CNode &peer)
const {
8288 if (m_opts.ignore_incoming_txs &&
8295bool PeerManagerImpl::SetupAddressRelay(
const CNode &
node, Peer &peer) {
8299 if (
node.IsBlockOnlyConn()) {
8303 if (!peer.m_addr_relay_enabled.exchange(
true)) {
8307 peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
8313bool PeerManagerImpl::SendMessages(
const Config &config,
CNode *pto) {
8317 PeerRef peer = GetPeerRef(pto->
GetId());
8326 if (MaybeDiscourageAndDisconnect(*pto, *peer)) {
8335 const auto current_time{GetTime<std::chrono::microseconds>()};
8340 "addrfetch connection timeout; disconnecting peer=%d\n",
8346 MaybeSendPing(*pto, *peer, current_time);
8353 bool sync_blocks_and_headers_from_peer =
false;
8355 MaybeSendAddr(*pto, *peer, current_time);
8357 MaybeSendSendHeaders(*pto, *peer);
8362 CNodeState &state = *State(pto->
GetId());
8365 if (m_chainman.m_best_header ==
nullptr) {
8372 if (state.fPreferredDownload) {
8373 sync_blocks_and_headers_from_peer =
true;
8384 if (m_num_preferred_download_peers == 0 ||
8385 mapBlocksInFlight.empty()) {
8386 sync_blocks_and_headers_from_peer =
true;
8390 if (!state.fSyncStarted && CanServeBlocks(*peer) &&
8394 if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) ||
8396 const CBlockIndex *pindexStart = m_chainman.m_best_header;
8405 if (pindexStart->
pprev) {
8406 pindexStart = pindexStart->
pprev;
8408 if (MaybeSendGetHeaders(*pto,
GetLocator(pindexStart), *peer)) {
8411 "initial getheaders (%d) to peer=%d (startheight:%d)\n",
8413 peer->m_starting_height);
8415 state.fSyncStarted =
true;
8416 peer->m_headers_sync_timeout =
8421 std::chrono::microseconds{
8423 Ticks<std::chrono::seconds>(
8425 m_chainman.m_best_header->Time()) /
8442 LOCK(peer->m_block_inv_mutex);
8443 std::vector<CBlock> vHeaders;
8445 ((!peer->m_prefers_headers &&
8446 (!state.m_requested_hb_cmpctblocks ||
8447 peer->m_blocks_for_headers_relay.size() > 1)) ||
8448 peer->m_blocks_for_headers_relay.size() >
8453 ProcessBlockAvailability(pto->
GetId());
8455 if (!fRevertToInv) {
8456 bool fFoundStartingHeader =
false;
8460 for (
const BlockHash &hash : peer->m_blocks_for_headers_relay) {
8466 fRevertToInv =
true;
8469 if (pBestIndex !=
nullptr && pindex->
pprev != pBestIndex) {
8480 fRevertToInv =
true;
8483 pBestIndex = pindex;
8484 if (fFoundStartingHeader) {
8487 }
else if (PeerHasHeader(&state, pindex)) {
8490 }
else if (pindex->
pprev ==
nullptr ||
8491 PeerHasHeader(&state, pindex->
pprev)) {
8494 fFoundStartingHeader =
true;
8499 fRevertToInv =
true;
8504 if (!fRevertToInv && !vHeaders.empty()) {
8505 if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) {
8510 "%s sending header-and-ids %s to peer=%d\n",
8511 __func__, vHeaders.front().GetHash().ToString(),
8514 std::optional<CSerializedNetMsg> cached_cmpctblock_msg;
8516 LOCK(m_most_recent_block_mutex);
8517 if (m_most_recent_block_hash ==
8519 cached_cmpctblock_msg =
8521 *m_most_recent_compact_block);
8524 if (cached_cmpctblock_msg.has_value()) {
8526 std::move(cached_cmpctblock_msg.value()));
8530 block, *pBestIndex)};
8537 state.pindexBestHeaderSent = pBestIndex;
8538 }
else if (peer->m_prefers_headers) {
8539 if (vHeaders.size() > 1) {
8541 "%s: %u headers, range (%s, %s), to peer=%d\n",
8542 __func__, vHeaders.size(),
8543 vHeaders.front().GetHash().ToString(),
8544 vHeaders.back().GetHash().ToString(),
8548 "%s: sending header %s to peer=%d\n", __func__,
8549 vHeaders.front().GetHash().ToString(),
8553 state.pindexBestHeaderSent = pBestIndex;
8555 fRevertToInv =
true;
8562 if (!peer->m_blocks_for_headers_relay.empty()) {
8564 peer->m_blocks_for_headers_relay.back();
8575 "Announcing block %s not on main chain (tip=%s)\n",
8584 if (!PeerHasHeader(&state, pindex)) {
8585 peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
8587 "%s: sending inv peer=%d hash=%s\n", __func__,
8592 peer->m_blocks_for_headers_relay.clear();
8599 std::vector<CInv> vInv;
8600 auto addInvAndMaybeFlush = [&](uint32_t type,
const uint256 &hash) {
8601 vInv.emplace_back(type, hash);
8612 LOCK(peer->m_block_inv_mutex);
8614 vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(),
8620 for (
const BlockHash &hash : peer->m_blocks_for_inv_relay) {
8623 peer->m_blocks_for_inv_relay.clear();
8626 auto computeNextInvSendTime =
8627 [&](std::chrono::microseconds &next)
8631 if (next < current_time) {
8632 fSendTrickle =
true;
8634 next = NextInvToInbounds(
8639 next = current_time;
8643 return fSendTrickle;
8647 if (peer->m_proof_relay !=
nullptr) {
8648 LOCK(peer->m_proof_relay->m_proof_inventory_mutex);
8650 if (computeNextInvSendTime(
8651 peer->m_proof_relay->m_next_inv_send_time)) {
8653 peer->m_proof_relay->m_proof_inventory_to_send.begin();
8655 peer->m_proof_relay->m_proof_inventory_to_send.end()) {
8658 it = peer->m_proof_relay->m_proof_inventory_to_send.erase(
8661 if (peer->m_proof_relay->m_proof_inventory_known_filter
8662 .contains(proofid)) {
8666 peer->m_proof_relay->m_proof_inventory_known_filter.insert(
8669 peer->m_proof_relay->m_recently_announced_proofs.insert(
8675 if (
auto tx_relay = peer->GetTxRelay()) {
8676 LOCK(tx_relay->m_tx_inventory_mutex);
8678 const bool fSendTrickle =
8679 computeNextInvSendTime(tx_relay->m_next_inv_send_time);
8684 LOCK(tx_relay->m_bloom_filter_mutex);
8685 if (!tx_relay->m_relay_txs) {
8686 tx_relay->m_tx_inventory_to_send.clear();
8691 if (fSendTrickle && tx_relay->m_send_mempool) {
8692 auto vtxinfo = m_mempool.
infoAll();
8693 tx_relay->m_send_mempool =
false;
8695 tx_relay->m_fee_filter_received.load()};
8697 LOCK(tx_relay->m_bloom_filter_mutex);
8699 for (
const auto &txinfo : vtxinfo) {
8700 const TxId &txid = txinfo.tx->GetId();
8701 tx_relay->m_tx_inventory_to_send.erase(txid);
8704 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8707 if (tx_relay->m_bloom_filter &&
8708 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8712 tx_relay->m_tx_inventory_known_filter.insert(txid);
8715 addInvAndMaybeFlush(
MSG_TX, txid);
8717 tx_relay->m_last_mempool_req =
8718 std::chrono::duration_cast<std::chrono::seconds>(
8725 std::vector<std::set<TxId>::iterator> vInvTx;
8726 vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
8727 for (std::set<TxId>::iterator it =
8728 tx_relay->m_tx_inventory_to_send.begin();
8729 it != tx_relay->m_tx_inventory_to_send.end(); it++) {
8730 vInvTx.push_back(it);
8733 tx_relay->m_fee_filter_received.load()};
8738 CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool);
8739 std::make_heap(vInvTx.begin(), vInvTx.end(),
8740 compareInvMempoolOrder);
8744 unsigned int nRelayedTransactions = 0;
8745 LOCK(tx_relay->m_bloom_filter_mutex);
8746 while (!vInvTx.empty() &&
8751 std::pop_heap(vInvTx.begin(), vInvTx.end(),
8752 compareInvMempoolOrder);
8753 std::set<TxId>::iterator it = vInvTx.back();
8755 const TxId txid = *it;
8757 tx_relay->m_tx_inventory_to_send.erase(it);
8759 if (tx_relay->m_tx_inventory_known_filter.contains(txid) &&
8760 tx_relay->m_avalanche_stalled_txids.count(txid) == 0) {
8764 auto txinfo = m_mempool.
info(txid);
8770 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
8773 if (tx_relay->m_bloom_filter &&
8774 !tx_relay->m_bloom_filter->IsRelevantAndUpdate(
8779 tx_relay->m_recently_announced_invs.insert(txid);
8780 addInvAndMaybeFlush(
MSG_TX, txid);
8781 nRelayedTransactions++;
8782 tx_relay->m_tx_inventory_known_filter.insert(txid);
8783 tx_relay->m_avalanche_stalled_txids.erase(txid);
8789 if (!vInv.empty()) {
8796 CNodeState &state = *State(pto->
GetId());
8799 auto stalling_timeout = m_block_stalling_timeout.load();
8800 if (state.m_stalling_since.count() &&
8801 state.m_stalling_since < current_time - stalling_timeout) {
8806 LogPrintf(
"Peer=%d is stalling block download, disconnecting\n",
8811 const auto new_timeout =
8813 if (stalling_timeout != new_timeout &&
8814 m_block_stalling_timeout.compare_exchange_strong(
8815 stalling_timeout, new_timeout)) {
8818 "Increased stalling timeout temporarily to %d seconds\n",
8830 if (state.vBlocksInFlight.size() > 0) {
8831 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
8832 int nOtherPeersWithValidatedDownloads =
8833 m_peers_downloading_from - 1;
8835 state.m_downloading_since +
8836 std::chrono::seconds{consensusParams.nPowTargetSpacing} *
8839 nOtherPeersWithValidatedDownloads)) {
8840 LogPrintf(
"Timeout downloading block %s from peer=%d, "
8842 queuedBlock.pindex->GetBlockHash().ToString(),
8850 if (state.fSyncStarted &&
8851 peer->m_headers_sync_timeout < std::chrono::microseconds::max()) {
8854 if (current_time > peer->m_headers_sync_timeout &&
8855 nSyncStarted == 1 &&
8856 (m_num_preferred_download_peers -
8857 state.fPreferredDownload >=
8866 LogPrintf(
"Timeout downloading headers from peer=%d, "
8872 LogPrintf(
"Timeout downloading headers from noban "
8873 "peer=%d, not disconnecting\n",
8879 state.fSyncStarted =
false;
8881 peer->m_headers_sync_timeout = 0us;
8887 peer->m_headers_sync_timeout = std::chrono::microseconds::max();
8893 ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>());
8896 std::vector<CInv> vGetData;
8904 CNodeState &state = *State(pto->
GetId());
8906 if (CanServeBlocks(*peer) &&
8907 ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) ||
8910 std::vector<const CBlockIndex *> vToDownload;
8912 auto get_inflight_budget = [&state]() {
8915 static_cast<int>(state.vBlocksInFlight.size()));
8921 FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload,
8924 !IsLimitedPeer(*peer)) {
8930 m_chainman.GetSnapshotBaseBlock());
8932 TryDownloadingHistoricalBlocks(
8933 *peer, get_inflight_budget(), vToDownload, from_tip,
8934 Assert(m_chainman.GetSnapshotBaseBlock()));
8938 BlockRequested(config, pto->
GetId(), *pindex);
8943 if (state.vBlocksInFlight.empty() && staller != -1) {
8944 if (State(staller)->m_stalling_since == 0us) {
8945 State(staller)->m_stalling_since = current_time;
8952 auto addGetDataAndMaybeFlush = [&](uint32_t type,
const uint256 &hash) {
8953 CInv inv(type, hash);
8956 vGetData.push_back(std::move(inv));
8967 LOCK(cs_proofrequest);
8968 std::vector<std::pair<NodeId, avalanche::ProofId>> expired;
8970 m_proofrequest.GetRequestable(pto->
GetId(), current_time, &expired);
8971 for (
const auto &entry : expired) {
8973 "timeout of inflight proof %s from peer=%d\n",
8974 entry.second.ToString(), entry.first);
8976 for (
const auto &proofid : requestable) {
8977 if (!AlreadyHaveProof(proofid)) {
8979 m_proofrequest.RequestedData(
8980 pto->
GetId(), proofid,
8987 m_proofrequest.ForgetInvId(proofid);
8998 LOCK(m_tx_download_mutex);
8999 for (
const TxId &txid : m_txdownloadman.GetRequestsToSend(
9000 pto->GetId(), current_time)) {
9001 addGetDataAndMaybeFlush(
MSG_TX, txid);
9004 if (!vGetData.empty()) {
9009 MaybeSendFeefilter(*pto, *peer, current_time);
9013bool PeerManagerImpl::ReceivedAvalancheProof(
CNode &
node, Peer &peer,
9018 LogError(
"ReceivedAvalancheProof: proof is null\n");
9024 AddKnownProof(peer, proofid);
9036 return node.m_avalanche_pubkey.has_value());
9037 auto saveProofIfStaker = [
this, isStaker](
const CNode &
node,
9039 const NodeId nodeid) ->
bool {
9051 LOCK(cs_proofrequest);
9052 m_proofrequest.ReceivedResponse(nodeid, proofid);
9054 if (AlreadyHaveProof(proofid)) {
9055 m_proofrequest.ForgetInvId(proofid);
9056 saveProofIfStaker(
node, proofid, nodeid);
9064 const auto now{GetTime<std::chrono::seconds>()};
9068 return pm.registerProof(proof, state);
9070 WITH_LOCK(cs_proofrequest, m_proofrequest.ForgetInvId(proofid));
9071 RelayProof(proofid);
9073 node.m_last_proof_time = now;
9076 nodeid, proofid.ToString());
9092 auto × = peer.m_invalid_avaproof_times;
9096 std::find_if(times.begin(), times.end(), [now](
const auto &t) {
9097 return t > now - AVALANCHE_INVALID_AVAPROOFS_INTERVAL;
9099 times.push_back(now);
9101 Misbehaving(peer,
"too-many-invalid-avaproofs");
9112 "Not polling the avalanche proof (%s): peer=%d, proofid %s\n",
9113 state.
IsValid() ?
"not-worth-polling"
9114 : state.GetRejectReason(),
9118 saveProofIfStaker(
node, proofid, nodeid);
bool MoneyRange(const Amount nValue)
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
enum ReadStatus_t ReadStatus
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
@ CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params ¶ms)
Return the time it would take to redo the work difference between from and to, assuming the current h...
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the identity function.
Stochastic address manager.
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
void Good(const CService &addr, bool test_before_evict=true, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as accessible, possibly moving it from "new" to "tried".
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
void Discourage(const CNetAddr &net_addr)
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
bool LookupFilterHashRange(int start_height, const CBlockIndex *stop_index, std::vector< uint256 > &hashes_out) const
Get a range of filter hashes between two heights on a chain.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
std::vector< CTransactionRef > txn
std::vector< uint32_t > indices
A CService with information about it as peer.
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
static constexpr SerParams V1_NETWORK
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
static constexpr SerParams V2_NETWORK
size_t BlockTxCount() const
std::string ToString() const
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockHeader GetBlockHeader() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
int64_t GetBlockTime() const
unsigned int nTx
Number of transactions in this block.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
int Height() const
Return the maximal height in the chain.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
const Consensus::Params & GetConsensus() const
CCoinsView that adds a memory cache for transactions to another CCoinsView.
CCoinsView that brings transactions from a mempool into view.
void ForEachNode(const NodeFn &func)
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
bool GetNetworkActive() const
bool GetTryNewOutboundPeer() const
void SetTryNewOutboundPeer(bool flag)
int GetExtraBlockRelayCount() const
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
void StartExtraBlockRelayPeers()
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
int GetExtraFullOutboundCount() const
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
bool CheckIncomingNonce(uint64_t nonce)
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
bool GetUseAddrmanOutgoing() const
Fee rate in satoshis per virtualbyte: Amount / vB the feerate is represented internally as FeeFrac.
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Inv(ventory) message data.
bool IsMsgCmpctBlk() const
std::string ToString() const
bool IsMsgStakeContender() const
bool IsMsgFilteredBlk() const
Used to create a Merkle proof (usually from a subset of transactions), which consists of a block head...
bool IsRelayable() const
Whether this address should be relayed to other peers even if we can't reach it ourselves.
static constexpr SerParams V1
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Transport protocol agnostic message container.
Information about a peer.
Mutex cs_avalanche_pubkey
bool IsFeelerConn() const
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
bool ExpectServicesFromConn() const
std::atomic< int > nVersion
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
bool IsInboundConn() const
bool HasPermission(NetPermissionFlags permission) const
bool IsOutboundOrBlockRelayConn() const
bool IsManualConn() const
std::atomic< int64_t > nTimeOffset
const std::string m_addr_name
std::string ConnectionTypeAsString() const
void SetCommonVersion(int greatest_common_version)
std::atomic< bool > m_bip152_highbandwidth_to
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
std::atomic< bool > m_bip152_highbandwidth_from
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
std::atomic_bool fSuccessfullyConnected
bool IsAddrFetchConn() const
uint64_t GetLocalNonce() const
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
bool IsBlockOnlyConn() const
int GetCommonVersion() const
bool IsFullOutboundConn() const
uint64_t nRemoteHostNonce
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
std::atomic_bool fPauseSend
uint64_t nRemoteExtraEntropy
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
uint64_t GetLocalExtraEntropy() const
SteadyMilliseconds m_last_poll
double getAvailabilityScore() const
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
std::atomic< std::chrono::seconds > m_avalanche_last_message_fault
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
std::atomic< int > m_avalanche_message_fault_counter
How much faulty messages did this node accumulate.
std::atomic< bool > m_avalanche_enabled
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
std::atomic_bool fDisconnect
std::atomic< int > m_avalanche_message_fault_score
This score is incremented for every new faulty message received when m_avalanche_message_fault_counte...
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
void invsVoted(uint32_t count)
The node voted for count invs.
bool IsAvalancheOutboundConnection() const
An encapsulated public key.
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Simple class for background tasks that should be run periodically or once "after a while".
void scheduleEvery(Predicate p, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat p until it return false.
void scheduleFromNow(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Call f once after the delta has passed.
A combination of a network address (CNetAddr) and a (TCP) port.
std::vector< uint8_t > GetKey() const
std::string ToStringAddrPort() const
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
The basic transaction that is broadcasted on the network and contained in blocks.
std::set< std::reference_wrapper< const CTxMemPoolEntryRef >, CompareIteratorById > Parents
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
bool setAvalancheFinalized(const CTxMemPoolEntryRef &tx, const Consensus::Params ¶ms, const CBlockIndex &active_chain_tip, Chainstate &active_chainstate, std::vector< TxId > &finalizedTxIds) EXCLUSIVE_LOCKS_REQUIRED(bool isAvalancheFinalizedPreConsensus(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool CompareTopologically(const TxId &txida, const TxId &txidb) const
TxMempoolInfo info(const TxId &txid) const
size_t DynamicMemoryUsage() const
std::vector< TxMempoolInfo > infoAll() const
CTransactionRef GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
bool exists(const TxId &txid) const
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
auto withOrphanage(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_orphanage)
auto withConflicting(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_conflicting)
void removeForFinalizedBlock(const std::unordered_set< TxId, SaltedTxIdHasher > &confirmedTxIdsInNonFinalizedBlocks) EXCLUSIVE_LOCKS_REQUIRED(cs)
unsigned long size() const
std::optional< txiter > GetIter(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given txid, if found.
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
Notifies listeners that a block which builds directly on our current tip has been received and connec...
virtual void BlockConnected(ChainstateRole role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void ActiveTipChange(const CBlockIndex &new_tip, bool is_ibd)
Notifies listeners any time the block chain tip changes, synchronously.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const arith_uint256 & MinimumChainWork() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void ReportHeadersPresync(const arith_uint256 &work, int64_t height, int64_t timestamp)
Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
virtual uint64_t GetMaxBlockSize() const =0
Double ended buffer combining vector and stream-like interfaces.
void ignore(size_t num_ignore)
uint64_t rand64() noexcept
Generate a random 64-bit integer.
Reads data from an underlying stream, while hashing the read data.
A writer stream (for serialization) that computes a 256-bit hash.
Interface for message handling.
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
virtual bool ProcessMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool SendMessages(const Config &config, CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void InitializeNode(const Config &config, CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
virtual void FinalizeNode(const Config &config, const CNode &node)=0
Handle removal of a peer (clear state)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< CTransactionRef > &extra_txn)
bool IsTxAvailable(size_t index) const
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
virtual std::optional< std::string > FetchBlock(const Config &config, NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
virtual std::vector< TxOrphanage::PoolTx > GetOrphanTransactions()=0
virtual void SendPings()=0
Send ping message to all peers.
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, avalanche::Processor *const avalanche, Options opts)
virtual void StartScheduledTasks(CScheduler &scheduler)=0
Begin running background tasks, should only be called once.
virtual void ProcessMessage(const Config &config, CNode &pfrom, const std::string &msg_type, DataStream &vRecv, const std::chrono::microseconds time_received, const std::atomic< bool > &interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process a single message from a peer.
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
virtual void UnitTestMisbehaving(const NodeId peer_id)=0
Public for unit testing.
virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)=0
This function is used for testing the stale tip eviction logic, see denialofservice_tests....
virtual void CheckForStaleTipAndEvictPeers()=0
Evict extra outbound peers.
static RCUPtr make(Args &&...args)
Construct a new object that is owned by the pointer.
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
A Span is an object that can refer to a contiguous sequence of objects.
bool AddTx(const CTransactionRef &tx, NodeId peer)
Add a new transaction to the pool.
std::vector< CTransactionRef > GetConflictTxs(const CTransactionRef &tx) const
unsigned int LimitTxs(unsigned int max_txs, FastRandomContext &rng)
Limit the txs to the given maximum.
int EraseTx(const TxId &txid)
Erase a tx by txid.
void BlockInvalidated(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
void TransactionInvalidated(const CTransactionRef &tx, std::shared_ptr< const std::vector< Coin > > spent_coins)
std::string GetRejectReason() const
std::string ToString() const
256-bit unsigned big integer.
const std::vector< PrefilledProof > & getPrefilledProofs() const
uint64_t getShortID(const ProofId &proofid) const
const std::vector< uint64_t > & getShortIDs() const
ProofId getProofId() const
bool verify(DelegationState &state, CPubKey &auth) const
const DelegationId & getId() const
const LimitedProofId & getLimitedProofId() const
bool addNode(NodeId nodeid, const ProofId &proofid, size_t max_elements)
Node API.
bool shouldRequestMoreNodes()
Returns true if we encountered a lack of node since the last call.
bool exists(const ProofId &proofid) const
Return true if the (valid) proof exists, but only for non-dangling proofs.
bool forPeer(const ProofId &proofid, Callable &&func) const
void clearRemoteProofs(NodeId nodeid)
void removeUnbroadcastProof(const ProofId &proofid)
const ProofRadixTree & getShareableProofsSnapshot() const
bool isBoundToPeer(const ProofId &proofid) const
bool saveRemoteProof(const ProofId &proofid, const NodeId nodeid, const bool present)
void forEachPeer(Callable &&func) const
void setInvalid(const ProofId &proofid)
bool isInvalid(const ProofId &proofid) const
bool isImmature(const ProofId &proofid) const
const ProofPool & getDanglingProofPool() const
auto getUnbroadcastProofs() const
bool isInConflictingPool(const ProofId &proofid) const
void sendResponse(CNode *pfrom, Response response) const
bool addToReconcile(const AnyVoteItem &item) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
bool isStakingPreconsensusActivated(const CBlockIndex *pprev) const
int64_t getAvaproofsNodeCounter() const
bool isPreconsensusActivated(const CBlockIndex *pprev) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizationTip)
bool sendHello(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Send a avahello message.
void setRecentlyFinalized(const uint256 &itemId) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
size_t getMaxElementPoll() const
bool isQuorumEstablished() LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
void cleanupStakingRewards(const int minHeight) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
ProofRef getLocalProof() const
void acceptStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
bool reconcileOrFinalize(const ProofRef &proof) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Wrapper around the addToReconcile for proofs that adds back the finalization flag to the peer if it i...
int getStakeContenderStatus(const StakeContenderId &contenderId) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Track votes on stake contenders.
void sendDelayedAvahello() EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
void finalizeStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
auto withPeerManager(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
bool registerVotes(NodeId nodeid, const Response &response, std::vector< VoteItemUpdate > &updates, bool &disconnect, std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
void rejectStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
void avaproofsSent(NodeId nodeid) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
void forEachProof(Callable &&func) const
std::vector< uint32_t > indices
constexpr bool IsNull() const
std::string ToString() const
std::string GetHex() const
Generate a new block, without valid proof-of-work.
bool ReadRawBlock(std::vector< uint8_t > &block, const FlatFilePos &pos) const
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool LoadingBlocks() const
bool IsPruneMode() const
Whether running in -prune mode.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
Class responsible for deciding what transactions to request and, once downloaded, whether and how to ...
static const uint256 ZERO
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ BLOCK_RESULT_UNSET
initial value. Block has not yet been rejected
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_CHILD_BEFORE_PARENT
This tx outputs are already spent in the mempool.
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/etc limits
@ TX_PACKAGE_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
@ TX_UNKNOWN
transaction was not validated because package failed
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_DUPLICATE
Tx already in mempool or in the chain.
@ TX_INPUTS_NOT_STANDARD
inputs failed policy rules
@ TX_CONFLICT
Tx conflicts with a finalized tx, i.e.
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_AVALANCHE_RECONSIDERABLE
fails some policy, but might be reconsidered by avalanche voting
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_RESULT_UNSET
initial value. Tx has not yet been rejected
@ TX_CONSENSUS
invalid by consensus rules
static size_t RecursiveDynamicUsage(const CScript &script)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::chrono::microseconds ComputeRequestTime(const InvRequestTracker< InvId > &requestTracker, NodeId nodeid, const DataRequestParameters &requestParams, std::chrono::microseconds current_time, bool preferred, bool bypass_limits)
Compute the request time for this announcement, current time plus delays for:
bool TooManyAnnouncements(const InvRequestTracker< InvId > &requestTracker, NodeId nodeid, const DataRequestParameters &requestParams, bool bypass_limits)
Whether the peer already has too many announcements tracked to accept a new one.
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
std::array< uint8_t, CPubKey::SCHNORR_SIZE > SchnorrSig
a Schnorr signature
#define LogPrintLevel(category, level,...)
#define LogDebug(category,...)
CSerializedNetMsg Make(std::string msg_type, Args &&...args)
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
const char * AVAPROOFSREQ
Request for missing avalanche proofs after an avaproofs message has been processed.
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
const char * BLOCK
The block message transmits a single serialized block.
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
const char * AVAPROOFS
The avaproofs message the proof short ids of all the valid proofs that we know.
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
const char * GETAVAPROOFS
The getavaproofs message requests an avaproofs message that provides the proof short ids of all the v...
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
const char * GETAVAADDR
The getavaaddr message requests an addr message from the receiving node, containing IP addresses of t...
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
const char * TX
The tx message transmits a single transaction.
const char * AVAHELLO
Contains a delegation and a signature.
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
const char * AVARESPONSE
Contains an avalanche::Response.
const char * GETDATA
The getdata message requests one or more data objects from another node.
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
const char * BLOCKTXN
Contains a BlockTransactions.
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
const char * AVAPOLL
Contains an avalanche::Poll.
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
const char * AVAPROOF
Contains an avalanche::Proof.
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
ShortIdProcessor< PrefilledProof, ShortIdProcessorPrefilledProofAdapter, ProofRefCompare > ProofShortIdProcessor
std::variant< const ProofRef, const CBlockIndex *, const StakeContenderId, const CTransactionRef > AnyVoteItem
RCUPtr< const Proof > ProofRef
static constexpr DataRequestParameters TX_REQUEST_PARAMS
Parameters for the tx requests, see DataRequestParameters.
Implement std::hash so RCUPtr can be used as a key for maps or sets.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
std::string userAgent(const Config &config)
bool IsReachable(enum Network net)
bool SeenLocal(const CService &addr)
vote for a local address
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
@ BypassProofRequestLimits
static constexpr auto HEADERS_RESPONSE_TIME
How long to wait for a peer to respond to a getheaders request.
static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET
The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND based inc...
static constexpr size_t MAX_AVALANCHE_STALLED_TXIDS_PER_PEER
Maximum number of stalled avalanche txids to store per peer.
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT
Default time during which a peer must stall block download progress before being disconnected.
static constexpr auto GETAVAADDR_INTERVAL
Minimum time between 2 successives getavaaddr messages from the same peer.
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL
Verify that INVENTORY_MAX_RECENT_RELAY is enough to cache everything typically relayed before uncondi...
static constexpr unsigned int INVENTORY_BROADCAST_MAX_PER_MB
Maximum number of inventory items to send per transmission.
static constexpr auto EXTRA_PEER_CHECK_INTERVAL
How frequently to check for extra outbound peers and disconnect.
static const unsigned int BLOCK_DOWNLOAD_WINDOW
Size of the "block download window": how far ahead of our current height do we fetch?...
static uint32_t getAvalancheVoteForProof(const avalanche::Processor &avalanche, const avalanche::ProofId &id)
Decide a response for an Avalanche poll about the given proof.
static constexpr int STALE_RELAY_AGE_LIMIT
Age after which a stale block will no longer be served if requested as protection against fingerprint...
static constexpr int HISTORICAL_BLOCK_AGE
Age after which a block is considered historical for purposes of rate limiting block relay.
static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL
Delay between rotating the peers we relay a particular address to.
static constexpr auto AVALANCHE_INVALID_AVAPROOFS_INTERVAL
Interval to look back for bad avaproofs.
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict.
static constexpr auto CHAIN_SYNC_TIMEOUT
Timeout for (unprotected) outbound peers to sync to our chainwork.
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS
Minimum blocks required to signal NODE_NETWORK_LIMITED.
static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
Average delay between local address broadcasts.
static const int MAX_BLOCKTXN_DEPTH
Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for.
static constexpr uint64_t CMPCTBLOCKS_VERSION
The compactblocks version we support.
bool IsAvalancheMessageType(const std::string &msg_type)
static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT
Protect at least this many outbound peers from disconnection due to slow/behind headers chain.
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for inbound peers.
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY
Maximum feefilter broadcast delay after significant change.
static constexpr uint32_t MAX_GETCFILTERS_SIZE
Maximum number of compact filters that may be requested with one getcfilters.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE
Headers download timeout.
static const unsigned int MAX_GETDATA_SZ
Limit to avoid sending big packets.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in multiples of the block interval (i.e.
static constexpr auto AVALANCHE_AVAPROOFS_TIMEOUT
If no proof was requested from a compact proof message after this timeout expired,...
static constexpr auto STALE_CHECK_INTERVAL
How frequently to check for stale tips.
static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY
The number of most recently announced transactions a peer can request.
static constexpr auto UNCONDITIONAL_RELAY_DELAY
How long a transaction has to be in the mempool before it can unconditionally be relayed.
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL
Average delay between peer address broadcasts.
static constexpr auto GETAVAPROOFS_INTERVAL
Minimum time between 2 successive getavaproofs messages from the same peer.
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
Additional block download timeout per parallel downloading peer (i.e.
static constexpr double MAX_ADDR_RATE_PER_SECOND
The maximum rate of address records we're willing to process on average.
static constexpr auto PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive.
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested.
static constexpr DataRequestParameters PROOF_REQUEST_PARAMS
static constexpr size_t AVALANCHE_MAX_INVALID_AVAPROOFS
Maximum number of failed avaproof registrations (e.g.
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
static constexpr uint32_t MAX_GETCFHEADERS_SIZE
Maximum number of cf hashes that may be requested with one getcfheaders.
static constexpr auto BLOCK_STALLING_TIMEOUT_MAX
Maximum timeout for stalling block download.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY
SHA256("main address relay")[0:8].
static constexpr size_t MAX_PCT_ADDR_TO_SEND
the maximum percentage of addresses from our addrman to return in response to a getaddr message.
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND
Maximum rate of inventory items to send per second.
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of address records permitted in an ADDR message.
static const unsigned int MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK
Maximum number of outstanding CMPCTBLOCK requests for the same block.
static const unsigned int MAX_HEADERS_RESULTS
Number of headers sent in one getheaders result.
bool IsProxy(const CNetAddr &addr)
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
static constexpr Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
std::shared_ptr< const CTransaction > CTransactionRef
static constexpr size_t AVALANCHE_MAX_ELEMENT_POLL_LEGACY
Legacy maximum element poll.
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
@ MSG_AVA_STAKE_CONTENDER
@ MSG_CMPCT_BLOCK
Defined in BIP152.
ServiceFlags
nServices flags.
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
static const int PROTOCOL_VERSION
network protocol versioning
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
static const int AVALANCHE_MAX_ELEMENT_BUMP_VERSION
Avalanche can poll up to 1024 items per message starting with this version.
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
reverse_range< T > reverse_iterate(T &x)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
void Unserialize(Stream &, V)=delete
#define LIMITED_STRING(obj, n)
static auto WithParams(const Params ¶ms, T &&t)
Return a wrapper around t that (de)serializes it with specified parameter params.
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
static const double AVALANCHE_STATISTICS_DECAY_FACTOR
Pre-computed decay factor for the avalanche statistics computation.
static constexpr std::chrono::minutes AVALANCHE_STATISTICS_REFRESH_PERIOD
Refresh period for the avalanche statistics computation.
static constexpr Amount zero() noexcept
A BlockHash is a unqiue identifier for a block.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< BlockHash > vHave
std::chrono::microseconds m_ping_wait
Amount m_fee_filter_received
std::vector< int > vHeightInFlight
bool m_addr_relay_enabled
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
ServiceFlags their_services
Parameters that influence chain consensus.
int64_t nPowTargetSpacing
std::chrono::seconds PowTargetSpacing() const
const size_t max_peer_announcements
Maximum number of inventories to consider for requesting, per peer.
const NetPermissionFlags bypass_request_limits_permissions
Permission flags a peer requires to bypass the request limits tracking limits and delay penalty.
const std::chrono::microseconds getdata_interval
How long to wait (in microseconds) before a data request from an additional peer.
const size_t max_peer_request_in_flight
Maximum number of in-flight data requests from a peer.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
const ResultType m_result_type
Result type.
const TxValidationState m_state
Contains information about why the transaction failed.
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static time_point now() noexcept
Return current system time or mocked time, if set.
std::chrono::time_point< NodeClock > time_point
Validation result for package mempool acceptance.
PackageValidationState m_state
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
This is a radix tree storing values identified by a unique key.
A TxId is the identifier of a transaction.
std::chrono::seconds registration_time
StakeContenderIds are unique for each block to ensure that the peer polling for their acceptance has ...
ValidationSignals * signals
ValidationSignals * signals
CFeeRate min_relay_feerate
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
std::vector< NodeId > m_senders
std::string ToString() const
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
#define ACQUIRED_BEFORE(...)
#define NO_THREAD_SAFETY_ANALYSIS
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
constexpr int64_t count_microseconds(std::chrono::microseconds t)
constexpr int64_t count_seconds(std::chrono::seconds t)
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
NodeClock::time_point GetAdjustedTime()
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
#define TRACE6(context, event, a, b, c, d, e, f)
@ AVALANCHE
Removed by avalanche vote.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
bool IsBlockMutated(const CBlock &block)
Check if a block has been mutated (with respect to its merkle root).
std::optional< std::vector< Coin > > GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view)
Get the coins spent by ptx from the coins_view.
arith_uint256 CalculateClaimedHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the claimed work on a given set of headers.
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...