48 uint256 hash = pindex->GetBlockHash();
66 if (!proof.
verify(stakeUtxoDustThreshold, proof_state)) {
69 error =
_(
"The avalanche proof has no stake.");
72 error =
_(
"The avalanche proof stake is too low.");
75 error =
_(
"The avalanche proof has duplicated stake.");
78 error =
_(
"The avalanche proof has invalid stake signatures.");
82 _(
"The avalanche proof has too many utxos (max: %u)."),
86 error =
_(
"The avalanche proof is invalid.");
100 if (!dg.
verify(dg_state, auth)) {
103 error =
_(
"The avalanche delegation has invalid signatures.");
107 "The avalanche delegation has too many delegation levels.");
110 error =
_(
"The avalanche delegation is invalid.");
115 if (auth != expectedPubKey) {
117 "The avalanche delegation does not match the expected public key.");
142 uint64_t mempool_sequence)
override {
150 std::unique_ptr<PeerData> peerDataIn,
CKey sessionKeyIn,
151 uint32_t minQuorumTotalScoreIn,
152 double minQuorumConnectedScoreRatioIn,
153 int64_t minAvaproofsNodeCountIn,
154 uint32_t staleVoteThresholdIn, uint32_t staleVoteFactorIn,
155 Amount stakeUtxoDustThreshold,
bool preConsensus,
156 bool stakingPreConsensus,
size_t maxElementPoll)
157 : avaconfig(
std::move(avaconfigIn)), connman(connmanIn),
158 chainman(chainmanIn), mempool(mempoolIn), round(0),
160 stakeUtxoDustThreshold, chainman, stakingPreConsensus,
161 peerDataIn ? peerDataIn->proof :
ProofRef())),
162 peerData(
std::move(peerDataIn)), sessionKey(
std::move(sessionKeyIn)),
163 minQuorumScore(minQuorumTotalScoreIn),
164 minQuorumConnectedScoreRatio(minQuorumConnectedScoreRatioIn),
165 minAvaproofsNodeCount(minAvaproofsNodeCountIn),
166 staleVoteThreshold(staleVoteThresholdIn),
167 staleVoteFactor(staleVoteFactorIn), m_preConsensus(preConsensus),
168 m_stakingPreConsensus(stakingPreConsensus),
169 m_maxElementPoll(maxElementPoll) {
176 std::unordered_set<ProofRef, SaltedProofHasher> registeredProofs;
178 peerManager->cleanupDanglingProofs(registeredProofs));
179 for (
const auto &proof : registeredProofs) {
181 "Promoting previously dangling proof %s\n",
182 proof->getId().ToString());
193 std::unordered_set<ProofRef, SaltedProofHasher> registeredProofs;
198 dumpPath, registeredProofs));
203 for (
const auto &proof : registeredProofs) {
208 registeredProofs.size(), PathToString(dumpPath));
225std::unique_ptr<Processor>
235 if (argsman.
IsArgSet(
"-avaproofstakeutxodustthreshold") &&
237 stakeUtxoDustThreshold)) {
238 error =
_(
"The avalanche stake utxo dust threshold amount is invalid.");
242 if (argsman.
IsArgSet(
"-avasessionkey")) {
245 error =
_(
"The avalanche session key is invalid.");
253 if (argsman.
IsArgSet(
"-avaproof")) {
254 if (!argsman.
IsArgSet(
"-avamasterkey")) {
256 "The avalanche master key is missing for the avalanche proof.");
262 error =
_(
"The avalanche master key is invalid.");
272 peerData = std::make_unique<PeerData>();
279 std::unique_ptr<DelegationBuilder> dgb;
282 if (argsman.
IsArgSet(
"-avadelegation")) {
291 error =
_(
"The delegation does not match the proof.");
297 "The master key does not match the delegation public key.");
301 dgb = std::make_unique<DelegationBuilder>(dg);
303 if (masterPubKey !=
peerData->proof->getMaster()) {
305 _(
"The master key does not match the proof public key.");
309 dgb = std::make_unique<DelegationBuilder>(*
peerData->proof);
314 if (sessionPubKey != masterPubKey) {
315 if (!dgb->addLevel(masterKey, sessionPubKey)) {
316 error =
_(
"Failed to generate a delegation for this session.");
320 peerData->delegation = dgb->build();
328 const auto queryTimeoutDuration =
329 std::chrono::milliseconds(argsman.
GetIntArg(
334 if (argsman.
IsArgSet(
"-avaminquorumstake") &&
336 error =
_(
"The avalanche min quorum stake amount is invalid.");
341 error =
_(
"The avalanche min quorum stake amount is out of range.");
345 double minQuorumConnectedStakeRatio =
347 if (argsman.
IsArgSet(
"-avaminquorumconnectedstakeratio")) {
349 int64_t megaMinRatio;
351 argsman.
GetArg(
"-avaminquorumconnectedstakeratio",
""), 6,
354 _(
"The avalanche min quorum connected stake ratio is invalid.");
357 minQuorumConnectedStakeRatio = double(megaMinRatio) / 1000000;
360 if (minQuorumConnectedStakeRatio < 0 || minQuorumConnectedStakeRatio > 1) {
362 "The avalanche min quorum connected stake ratio is out of range.");
367 argsman.
GetIntArg(
"-avaminavaproofsnodecount",
370 error =
_(
"The minimum number of node that sent avaproofs message "
371 "should be non-negative");
379 error =
strprintf(
_(
"The avalanche stale vote threshold must be "
380 "greater than or equal to %d"),
385 error =
strprintf(
_(
"The avalanche stale vote threshold must be less "
386 "than or equal to %d"),
387 std::numeric_limits<uint32_t>::max());
394 error =
_(
"The avalanche stale vote factor must be greater than 0");
398 error =
strprintf(
_(
"The avalanche stale vote factor must be less than "
400 std::numeric_limits<uint32_t>::max());
406 int64_t maxElementPoll = argsman.
GetIntArg(
409 maxElementPoll > std::numeric_limits<uint32_t>::max()) {
411 _(
"The -avamaxelementpoll value must be between %d and %d"),
413 std::numeric_limits<uint32_t>::max());
418 return std::unique_ptr<Processor>(
new Processor(
423 stakeUtxoDustThreshold,
426 argsman.
GetBoolArg(
"-avalanchestakingpreconsensus",
429 static_cast<size_t>(maxElementPoll)));
433 return item.valueless_by_exception() ||
438 [](
const auto &item) {
return item ==
nullptr; },
457 ->insert(std::make_pair(
471 if (peerManager->forPeer(proof->getId(), [&](
const Peer &peer) {
472 peerid = peer.peerid;
475 return peerManager->setFinalized(peerid);
488 auto it = r->find(item);
493 return it->second.isAccepted();
502 auto it = r->find(item);
507 return it->second.getConfidence();
516 auto it = r->find(item);
517 return it != r.
end();
530 finalizedItems.reset();
543 TCPResponse(Response responseIn,
const CKey &key)
547 const uint256 hash = hasher.GetHash();
569 std::vector<VoteItemUpdate> &updates,
570 bool &disconnect, std::string &error) {
576 peerManager->updateNextRequestTimeForResponse(nodeid,
response));
578 std::vector<CInv> invs;
586 auto it = w->find(std::make_tuple(nodeid,
response.getRound()));
588 error =
"unexpected-ava-response";
592 invs = std::move(it->invs);
597 const std::vector<Vote> &votes =
response.GetVotes();
598 size_t size = invs.size();
599 if (votes.size() != size) {
601 error =
"invalid-ava-response-size";
606 for (
size_t i = 0; i < size; i++) {
607 if (invs[i].hash != votes[i].GetHash()) {
609 error =
"invalid-ava-response-content";
615 std::map<AnyVoteItem, Vote, VoteMapComparator> responseItems;
619 for (
size_t i = 0; i < size; i++) {
632 responseItems.insert(std::make_pair(std::move(item), votes[i]));
638 for (
const auto &p : responseItems) {
640 const Vote &v = p.second;
642 auto it = voteRecordsWriteView->find(item);
643 if (it == voteRecordsWriteView.end()) {
648 auto &vr = it->second;
649 if (!vr.registerVote(nodeid, v.
GetError())) {
655 voteRecordsWriteView->erase(it);
661 if (!vr.hasFinalized()) {
664 updates.emplace_back(std::move(item), vr.isAccepted()
672 updates.emplace_back(std::move(item), vr.isAccepted()
675 voteRecordsWriteView->erase(it);
680 for (
const auto &update : updates) {
686 const auto &item = update.getVoteItem();
688 if (!std::holds_alternative<const CBlockIndex *>(item)) {
704 const CBlockIndex *pindex = std::get<const CBlockIndex *>(item);
706 if (finalizationTip &&
707 finalizationTip->GetAncestor(pindex->
nHeight) == pindex) {
711 finalizationTip = pindex;
727 if (!delayedAvahelloNodeIds.emplace(pfrom->
GetId()).second) {
737 hasher << delegation.
getId();
764 auto it = delayedAvahelloNodeIds.begin();
765 while (it != delayedAvahelloNodeIds.end()) {
771 it = delayedAvahelloNodeIds.erase(it);
795 if (peerManager->isInConflictingPool(proofid)) {
797 "conflicting-utxos");
801 if (peerManager->isInvalid(proofid)) {
805 "avalanche-invalidated");
834 if (peerManager->latchAvaproofsSent(nodeid)) {
848 if (peerManager->getNodeCount() < 8) {
881 uint32_t totalPeersScore;
882 uint32_t connectedPeersScore;
885 totalPeersScore = peerManager->getTotalPeersScore();
886 connectedPeersScore = peerManager->getConnectedPeersScore();
891 peerManager->forPeer(localProof->getId(), [](
const Peer &peer) {
892 return peer.node_count == 0;
894 connectedPeersScore += localProof->getScore();
904 uint32_t minConnectedScore =
906 if (connectedPeersScore < minConnectedScore) {
915 bool computedRewards =
false;
964 bool rewardsInserted =
false;
966 pindex, _stakingRewards.
winners))) {
971 .emplace(pindex->
GetBlockHash(), std::move(_stakingRewards))
980 return rewardsInserted;
985 return stakingRewards.erase(prevBlockHash) > 0;
997 for (
auto it = stakingRewards.begin(); it != stakingRewards.end();) {
998 if (it->second.blockheight < minHeight) {
999 it = stakingRewards.erase(it);
1007 return peerManager->cleanupStakeContenders(minHeight));
1012 std::vector<std::pair<ProofId, CScript>> &winners)
const {
1014 auto it = stakingRewards.find(prevBlockHash);
1015 if (it == stakingRewards.end()) {
1019 winners = it->second.winners;
1024 std::vector<CScript> &payouts)
const {
1025 std::vector<std::pair<ProofId, CScript>> winners;
1031 payouts.reserve(winners.size());
1032 for (
auto &winner : winners) {
1033 payouts.push_back(std::move(winner.second));
1040 const std::vector<CScript> &payouts) {
1046 stakingReward.
winners.reserve(payouts.size());
1047 for (
const CScript &payout : payouts) {
1053 peerManager->setStakeContenderWinners(pprev, payouts);
1057 return stakingRewards.insert_or_assign(pprev->
GetBlockHash(), stakingReward)
1063 const std::vector<std::pair<ProofId, CScript>> &winners) {
1068 stakingReward.
winners = winners;
1071 return stakingRewards.insert_or_assign(pprev->
GetBlockHash(), stakingReward)
1091 contenderId, prevblockhash));
1094 std::vector<std::pair<ProofId, CScript>> winners;
1096 if (winners.size() == 0) {
1108 peerManager->acceptStakeContender(contenderId);
1115 std::vector<std::pair<ProofId, CScript>> winners;
1118 peerManager->finalizeStakeContender(contenderId, prevblockhash,
1123 if (winners.size() > 0) {
1139 std::optional<StakeContenderCacheInfo> info;
1142 info = peerManager->getStakeContenderInfo(contenderId);
1143 peerManager->rejectStakeContender(contenderId);
1149 const BlockHash &prevblockhash = info->prevblockhash;
1150 const ProofId &rejectedProofid = info->proofid;
1154 bool rejectedIsPrimaryWinner =
false;
1157 auto it = stakingRewards.find(prevblockhash);
1158 if (it == stakingRewards.end()) {
1161 if (std::none_of(it->second.winners.begin(), it->second.winners.end(),
1162 [&](
const auto &winner) {
1163 return winner.first == rejectedProofid;
1167 rejectedIsPrimaryWinner =
1168 it->second.winners[0].first == rejectedProofid;
1173 if (!rejectedIsPrimaryWinner) {
1183 std::vector<std::pair<ProofId, CScript>> newWinners;
1186 if (peerManager->hasAcceptedStakeWinner(prevblockhash)) {
1189 if (!peerManager->getStakeContenderWinners(prevblockhash,
1196 peerManager->addRejectedContender(rejectedProofid, prevblockhash);
1197 if (!peerManager->selectStakingRewardWinner(pprev, newWinners)) {
1217 peerManager->promoteStakeContendersToBlock(pprev);
1222 std::vector<StakeContenderId> pollableContenders;
1232 std::vector<StakeContenderId> &pollableContenders) {
1234 std::vector<std::pair<ProofId, CScript>> winners;
1238 return peerManager->setContenderStatusForLocalWinners(
1244 auto registerProofs = [&]() {
1247 auto registeredProofs = peerManager->updatedBlockTip();
1251 if (peerManager->registerProof(
peerData->proof, localProofState)) {
1252 registeredProofs.insert(
peerData->proof);
1263 if (peerManager->isImmature(localProofId)) {
1267 if (peerManager->isInConflictingPool(localProofId)) {
1270 "conflicting-utxos");
1272 if (peerManager->isBoundToPeer(localProofId)) {
1278 peerData->proofState = std::move(localProofState));
1281 return registeredProofs;
1284 auto registeredProofs = registerProofs();
1285 for (
const auto &proof : registeredProofs) {
1317 std::vector<CInv> invs;
1324 auto voteRecordsReadView =
1332 nodeid = peerManager->selectNode();
1338 peerManager->forNode(nodeid, [&max_elements](
const Node &
node) {
1339 max_elements =
node.maxElements;
1349 voteRecordsReadView.reset();
1360 uint64_t current_round =
round++;
1364 auto timeout = Now<SteadyMilliseconds>() +
1368 {pnode->
GetId(), current_round, timeout, invs});
1370 peerManager->updateNextRequestTimeForPoll(
1371 pnode->
GetId(), timeout, current_round);
1380 Poll(current_round, std::move(invs))));
1390 peerManager->removeNode(nodeid);
1402 for (
auto it = w->begin(); it != w->end();) {
1412 auto now = Now<SteadyMilliseconds>();
1413 std::map<CInv, uint8_t> timedout_items{};
1419 while (it != w->get<
query_timeout>().end() && it->timeout < now) {
1420 for (
const auto &i : it->invs) {
1421 timedout_items[i]++;
1432 std::map<CInv, uint8_t> counts;
1433 for (
const CInv &inv : invs) {
1440 const std::map<CInv, uint8_t> &inflightRequests) {
1441 if (inflightRequests.empty()) {
1446 for (
const auto &inflightRequest : inflightRequests) {
1453 auto it = voteRecordsReadView->find(item);
1454 if (it == voteRecordsReadView.end()) {
1458 it->second.clearInflightRequest(inflightRequest.second);
1464 bool forPoll)
const {
1465 std::vector<CInv> invs;
1480 for (
const auto &[item, voteRecord] : voteRecordsReadView) {
1481 if (invs.size() >= max_elements) {
1487 const bool shouldPoll =
1488 forPoll ? voteRecord.registerPoll() : voteRecord.shouldPoll();
1494 invs.emplace_back(std::visit(buildInvFromVoteItem, item));
1522 return conflicting.GetTx(TxId(inv.hash));
1536 if (pindex->nStatus.isInvalid()) {
1544 pindex->
nHeight) == pindex)) {
1551 return processor.invalidatedBlocks.contains(
1565 const ProofId &proofid = proof->getId();
1567 LOCK(processor.cs_peerManager);
1570 return processor.peerManager->isBoundToPeer(proofid) ||
1571 processor.peerManager->isInConflictingPool(proofid);
1580 return processor.getStakeContenderStatus(contenderId) != -1;
1584 if (!processor.mempool) {
1590 return processor.mempool->isWorthPolling(tx));
1603 return processor.chainman.ActiveChain().Contains(pindex));
1610 processor.cs_peerManager,
1611 return processor.peerManager->isBoundToPeer(proof->getId()));
1619 return processor.getStakeContenderStatus(contenderId) == 0;
1624 if (!processor.mempool) {
1631 return processor.mempool->exists(tx->GetId()));
bool MoneyRange(const Amount nValue)
static constexpr bool DEFAULT_PERSIST_AVAPEERS
Default for -persistavapeers.
static constexpr double AVALANCHE_DEFAULT_MIN_QUORUM_CONNECTED_STAKE_RATIO
Default minimum percentage of stake-weighted peers we must have a node for to constitute a usable quo...
static constexpr bool DEFAULT_AVALANCHE_STAKING_PRECONSENSUS
Default for -avalanchestakingpreconsensus.
static constexpr double AVALANCHE_DEFAULT_MIN_AVAPROOFS_NODE_COUNT
Default minimum number of nodes that sent us an avaproofs message before we can consider our quorum s...
static constexpr bool DEFAULT_AVALANCHE_PRECONSENSUS
Default for -avalanchepreconsensus.
static constexpr Amount AVALANCHE_DEFAULT_MIN_QUORUM_STAKE
Default minimum cumulative stake of all known peers that constitutes a usable quorum.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
The block chain is a tree shaped structure starting with the genesis block at the root,...
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
size_t GetNodeCount(ConnectionDirection) const
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Inv(ventory) message data.
bool IsMsgStakeContender() const
An encapsulated secp256k1 private key.
bool IsValid() const
Check whether this private key is valid.
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
CPubKey GetPubKey() const
Compute the public key from a private key.
bool SignSchnorr(const uint256 &hash, SchnorrSig &sig, uint32_t test_case=0) const
Create a Schnorr signature.
Information about a peer.
uint64_t GetLocalNonce() const
uint64_t nRemoteHostNonce
uint64_t nRemoteExtraEntropy
uint64_t GetLocalExtraEntropy() const
void invsPolled(uint32_t count)
The node was polled for count invs.
An encapsulated public key.
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.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
CTransactionRef get(const TxId &txid) const
auto withConflicting(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_conflicting)
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const Consensus::Params & GetConsensus() const
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
A writer stream (for serialization) that computes a 256-bit hash.
static RCUPtr make(Args &&...args)
Construct a new object that is owned by the pointer.
ReadView getReadView() const
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
ProofId getProofId() const
static bool FromHex(Delegation &dg, const std::string &dgHex, bilingual_str &errorOut)
bool verify(DelegationState &state, CPubKey &auth) const
const DelegationId & getId() const
const CPubKey & getDelegatedPubkey() const
const LimitedProofId & getLimitedProofId() const
void updatedBlockTip() override
NotificationsHandler(Processor *p)
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
void sendResponse(CNode *pfrom, Response response) const
const uint32_t staleVoteThreshold
Voting parameters.
std::atomic< bool > quorumIsEstablished
AnyVoteItem getVoteItemFromInv(const CInv &inv) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Mutex cs_finalizedItems
Rolling bloom filter to track recently finalized inventory items of any type.
bool sendHelloInternal(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_delayedAvahelloNodeIds)
int getConfidence(const AnyVoteItem &item) const
bool addToReconcile(const AnyVoteItem &item) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Processor(Config avaconfig, interfaces::Chain &chain, CConnman *connmanIn, ChainstateManager &chainman, CTxMemPool *mempoolIn, CScheduler &scheduler, std::unique_ptr< PeerData > peerDataIn, CKey sessionKeyIn, uint32_t minQuorumTotalScoreIn, double minQuorumConnectedScoreRatioIn, int64_t minAvaproofsNodeCountIn, uint32_t staleVoteThresholdIn, uint32_t staleVoteFactorIn, Amount stakeUtxoDustThresholdIn, bool preConsensus, bool stakingPreConsensus, size_t maxElementPoll)
bool isStakingPreconsensusActivated(const CBlockIndex *pprev) const
RWCollection< QuerySet > queries
bool hasFinalizedTip() const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizationTip)
Whether there is a finalized tip.
bool isPreconsensusActivated(const CBlockIndex *pprev) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizationTip)
ProofRegistrationState getLocalProofRegistrationState() const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
bool setContenderStatusForLocalWinners(const CBlockIndex *pindex, std::vector< StakeContenderId > &pollableContenders) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Helper to set the vote status for local winners in the contender cache.
bool sendHello(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Send a avahello message.
bool isRecentlyFinalized(const uint256 &itemId) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
void setRecentlyFinalized(const uint256 &itemId) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
bool startEventLoop(CScheduler &scheduler)
bool isQuorumEstablished() LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
std::atomic< uint64_t > round
Keep track of peers and queries sent.
bool canShareLocalProof()
static std::unique_ptr< Processor > MakeProcessor(const ArgsManager &argsman, interfaces::Chain &chain, CConnman *connman, ChainstateManager &chainman, CTxMemPool *mempoolIn, CScheduler &scheduler, bilingual_str &error)
EventLoop eventLoop
Event loop machinery.
int64_t minAvaproofsNodeCount
const bool m_preConsensus
bool isPolled(const AnyVoteItem &item) const
Mutex cs_delayedAvahelloNodeIds
bool setStakingRewardWinners(const CBlockIndex *pprev, const std::vector< CScript > &payouts) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
void runEventLoop() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Mutex cs_invalidatedBlocks
We don't need many blocks but a low false positive rate.
void updatedBlockTip() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
RWCollection< VoteMap > voteRecords
Items to run avalanche on.
std::unique_ptr< interfaces::Handler > chainNotificationsHandler
uint32_t minQuorumScore
Quorum management.
void FinalizeNode(const ::Config &config, const CNode &node) override LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Handle removal of a node.
bool getStakingRewardWinners(const BlockHash &prevBlockHash, std::vector< std::pair< ProofId, CScript > > &winners) const EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
std::atomic< bool > m_canShareLocalProof
void cleanupStakingRewards(const int minHeight) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
bool isAccepted(const AnyVoteItem &item) const
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.
const uint32_t staleVoteFactor
void promoteAndPollStakeContenders(const CBlockIndex *pprev) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
Promote stake contender cache entries to a given block and then poll.
void sendDelayedAvahello() EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
void finalizeStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
std::unique_ptr< PeerData > peerData
const size_t m_maxElementPoll
bool eraseStakingRewardWinner(const BlockHash &prevBlockHash) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
std::vector< CInv > getInvsForNextPoll(RWCollection< VoteMap >::ReadView &voteRecordsReadView, size_t max_elements, bool forPoll=true) const
bool isWorthPolling(const AnyVoteItem &item) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
CPubKey getSessionPubKey() const
void clearInflightRequests(const std::vector< CInv > &invs) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Decrement VoteRecord::inflight for each inventory.
ChainstateManager & chainman
std::atomic< int64_t > avaproofsNodeCounter
std::optional< uint32_t > m_voteRecordSeed
std::atomic_bool m_stakingPreConsensus
bool computeStakingReward(const CBlockIndex *pindex) 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 clearTimedoutRequests() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
void transactionAddedToMempool(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems
Mutex cs_peerManager
Keep track of the peers and associated infos.
bool getLocalAcceptance(const AnyVoteItem &item) const
void clearInvsNotWorthPolling() 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)
double minQuorumConnectedScoreRatio
void clearFinalizedItems() EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
static bool FromHex(Proof &proof, const std::string &hexProof, bilingual_str &errorOut)
bool verify(const Amount &stakeUtxoDustThreshold, ProofValidationState &state) const
static uint32_t amountToScore(Amount amount)
uint32_t GetError() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static const uint256 ZERO
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::array< uint8_t, CPubKey::SCHNORR_SIZE > SchnorrSig
a Schnorr signature
CKey DecodeSecret(const std::string &str)
#define LogDebug(category,...)
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
CSerializedNetMsg Make(std::string msg_type, Args &&...args)
const char * AVAHELLO
Contains a delegation and a signature.
const char * AVARESPONSE
Contains an avalanche::Response.
const char * AVAPOLL
Contains an avalanche::Poll.
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
std::variant< const ProofRef, const CBlockIndex *, const StakeContenderId, const CTransactionRef > AnyVoteItem
@ INVALID_STAKE_SIGNATURE
static bool VerifyDelegation(const Delegation &dg, const CPubKey &expectedPubKey, bilingual_str &error)
static bool isNull(const AnyVoteItem &item)
static bool VerifyProof(const Amount &stakeUtxoDustThreshold, const Proof &proof, bilingual_str &error)
static uint256 GetVoteItemId(const AnyVoteItem &item)
RCUPtr< const Proof > ProofRef
Implement std::hash so RCUPtr can be used as a key for maps or sets.
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
std::shared_ptr< const CTransaction > CTransactionRef
static const std::string AVAPEERS_FILE_NAME
static constexpr std::chrono::milliseconds AVALANCHE_TIME_STEP
Run the avalanche event loop every 10ms.
static constexpr size_t DEFAULT_AVALANCHE_MAX_ELEMENT_POLL
Maximum item that can be polled at once.
static constexpr size_t AVALANCHE_CONTENDER_MAX_POLLABLE
Maximum number of stake contenders to poll for, leaving room for polling blocks and proofs in the sam...
static constexpr std::chrono::milliseconds AVALANCHE_DEFAULT_QUERY_TIMEOUT
How long before we consider that a query timed out.
static constexpr size_t AVALANCHE_MAX_ELEMENT_POLL_LEGACY
Legacy maximum element poll.
static constexpr int AVALANCHE_MAX_PROOF_STAKES
How many UTXOs can be used for a single proof.
@ MSG_AVA_STAKE_CONTENDER
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
bool IsStakingRewardsActivated(const Consensus::Params ¶ms, const CBlockIndex *pprev)
A BlockHash is a unqiue identifier for a block.
bool stopEventLoop() EXCLUSIVE_LOCKS_REQUIRED(!cs_running)
bool startEventLoop(CScheduler &scheduler, std::function< void()> runEventLoop, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!cs_running)
A TxId is the identifier of a transaction.
const std::chrono::milliseconds queryTimeoutDuration
bool operator()(const CBlockIndex *pindex) const LOCKS_EXCLUDED(cs_main)
const Processor & processor
bool operator()(const CBlockIndex *pindex) const LOCKS_EXCLUDED(cs_main)
ProofRegistrationState proofState GUARDED_BY(cs_proofState)
std::vector< std::pair< ProofId, CScript > > winners
StakeContenderIds are unique for each block to ensure that the peer polling for their acceptance has ...
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bilingual_str _(const char *psz)
Translation function.
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
static constexpr uint32_t AVALANCHE_VOTE_STALE_FACTOR
Scaling factor applied to confidence to determine staleness threshold.
static constexpr uint32_t AVALANCHE_VOTE_STALE_MIN_THRESHOLD
Lowest configurable staleness threshold (finalization score + necessary votes to increase confidence ...
static constexpr uint32_t AVALANCHE_VOTE_STALE_THRESHOLD
Number of votes before a record may be considered as stale.