Bitcoin ABC 0.32.6
P2P Digital Currency
processor.cpp
Go to the documentation of this file.
1// Copyright (c) 2018-2019 The Bitcoin developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
6
13#include <chain.h>
14#include <common/args.h>
16#include <key_io.h> // For DecodeSecret
17#include <net.h>
18#include <netbase.h>
19#include <netmessagemaker.h>
21#include <scheduler.h>
22#include <util/bitmanip.h>
23#include <util/moneystr.h>
24#include <util/time.h>
25#include <util/translation.h>
26#include <validation.h>
27
28#include <chrono>
29#include <limits>
30#include <tuple>
31
35static constexpr std::chrono::milliseconds AVALANCHE_TIME_STEP{10};
36
37static const std::string AVAPEERS_FILE_NAME{"avapeers.dat"};
38
39namespace avalanche {
40static uint256 GetVoteItemId(const AnyVoteItem &item) {
41 return std::visit(variant::overloaded{
42 [](const ProofRef &proof) {
43 uint256 id = proof->getId();
44 return id;
45 },
46 [](const CBlockIndex *pindex) {
47 uint256 hash = pindex->GetBlockHash();
48 return hash;
49 },
50 [](const StakeContenderId &contenderId) {
51 return uint256(contenderId);
52 },
53 [](const CTransactionRef &tx) {
54 uint256 id = tx->GetId();
55 return id;
56 },
57 },
58 item);
59}
60
61static bool VerifyProof(const Amount &stakeUtxoDustThreshold,
62 const Proof &proof, bilingual_str &error) {
63 ProofValidationState proof_state;
64
65 if (!proof.verify(stakeUtxoDustThreshold, proof_state)) {
66 switch (proof_state.GetResult()) {
68 error = _("The avalanche proof has no stake.");
69 return false;
71 error = _("The avalanche proof stake is too low.");
72 return false;
74 error = _("The avalanche proof has duplicated stake.");
75 return false;
77 error = _("The avalanche proof has invalid stake signatures.");
78 return false;
80 error = strprintf(
81 _("The avalanche proof has too many utxos (max: %u)."),
83 return false;
84 default:
85 error = _("The avalanche proof is invalid.");
86 return false;
87 }
88 }
89
90 return true;
91}
92
93static bool VerifyDelegation(const Delegation &dg,
94 const CPubKey &expectedPubKey,
95 bilingual_str &error) {
96 DelegationState dg_state;
97
98 CPubKey auth;
99 if (!dg.verify(dg_state, auth)) {
100 switch (dg_state.GetResult()) {
102 error = _("The avalanche delegation has invalid signatures.");
103 return false;
105 error = _(
106 "The avalanche delegation has too many delegation levels.");
107 return false;
108 default:
109 error = _("The avalanche delegation is invalid.");
110 return false;
111 }
112 }
113
114 if (auth != expectedPubKey) {
115 error = _(
116 "The avalanche delegation does not match the expected public key.");
117 return false;
118 }
119
120 return true;
121}
122
126
129};
130
134
135public:
137
139
141 uint64_t mempool_sequence) override {
143 }
144};
145
147 CConnman *connmanIn, ChainstateManager &chainmanIn,
148 CTxMemPool *mempoolIn, CScheduler &scheduler,
149 std::unique_ptr<PeerData> peerDataIn, CKey sessionKeyIn,
150 uint32_t minQuorumTotalScoreIn,
151 double minQuorumConnectedScoreRatioIn,
152 int64_t minAvaproofsNodeCountIn,
153 uint32_t staleVoteThresholdIn, uint32_t staleVoteFactorIn,
154 Amount stakeUtxoDustThreshold, bool preConsensus,
155 bool stakingPreConsensus)
156 : avaconfig(std::move(avaconfigIn)), connman(connmanIn),
157 chainman(chainmanIn), mempool(mempoolIn), round(0),
158 peerManager(std::make_unique<PeerManager>(
159 stakeUtxoDustThreshold, chainman, stakingPreConsensus,
160 peerDataIn ? peerDataIn->proof : ProofRef())),
161 peerData(std::move(peerDataIn)), sessionKey(std::move(sessionKeyIn)),
162 minQuorumScore(minQuorumTotalScoreIn),
163 minQuorumConnectedScoreRatio(minQuorumConnectedScoreRatioIn),
164 minAvaproofsNodeCount(minAvaproofsNodeCountIn),
165 staleVoteThreshold(staleVoteThresholdIn),
166 staleVoteFactor(staleVoteFactorIn), m_preConsensus(preConsensus),
167 m_stakingPreConsensus(stakingPreConsensus) {
168 // Make sure we get notified of chain state changes.
170 chain.handleNotifications(std::make_shared<NotificationsHandler>(this));
171
172 scheduler.scheduleEvery(
173 [this]() -> bool {
174 std::unordered_set<ProofRef, SaltedProofHasher> registeredProofs;
176 peerManager->cleanupDanglingProofs(registeredProofs));
177 for (const auto &proof : registeredProofs) {
179 "Promoting previously dangling proof %s\n",
180 proof->getId().ToString());
181 reconcileOrFinalize(proof);
182 }
183 return true;
184 },
185 5min);
186
187 if (!gArgs.GetBoolArg("-persistavapeers", DEFAULT_PERSIST_AVAPEERS)) {
188 return;
189 }
190
191 std::unordered_set<ProofRef, SaltedProofHasher> registeredProofs;
192
193 // Attempt to load the peer file if it exists.
194 const fs::path dumpPath = gArgs.GetDataDirNet() / AVAPEERS_FILE_NAME;
195 WITH_LOCK(cs_peerManager, return peerManager->loadPeersFromFile(
196 dumpPath, registeredProofs));
197
198 // We just loaded the previous finalization status, but make sure to trigger
199 // another round of vote for these proofs to avoid issue if the network
200 // status changed since the peers file was dumped.
201 for (const auto &proof : registeredProofs) {
202 addToReconcile(proof);
203 }
204
205 LogPrint(BCLog::AVALANCHE, "Loaded %d peers from the %s file\n",
206 registeredProofs.size(), PathToString(dumpPath));
207}
208
210 chainNotificationsHandler->disconnect();
213
214 if (!gArgs.GetBoolArg("-persistavapeers", DEFAULT_PERSIST_AVAPEERS)) {
215 return;
216 }
217
219 // Discard the status output: if it fails we want to continue normally.
220 peerManager->dumpPeersToFile(gArgs.GetDataDirNet() / AVAPEERS_FILE_NAME);
221}
222
223std::unique_ptr<Processor>
225 CConnman *connman, ChainstateManager &chainman,
226 CTxMemPool *mempool, CScheduler &scheduler,
227 bilingual_str &error) {
228 std::unique_ptr<PeerData> peerData;
229 CKey masterKey;
231
232 Amount stakeUtxoDustThreshold = PROOF_DUST_THRESHOLD;
233 if (argsman.IsArgSet("-avaproofstakeutxodustthreshold") &&
234 !ParseMoney(argsman.GetArg("-avaproofstakeutxodustthreshold", ""),
235 stakeUtxoDustThreshold)) {
236 error = _("The avalanche stake utxo dust threshold amount is invalid.");
237 return nullptr;
238 }
239
240 if (argsman.IsArgSet("-avasessionkey")) {
241 sessionKey = DecodeSecret(argsman.GetArg("-avasessionkey", ""));
242 if (!sessionKey.IsValid()) {
243 error = _("The avalanche session key is invalid.");
244 return nullptr;
245 }
246 } else {
247 // Pick a random key for the session.
249 }
250
251 if (argsman.IsArgSet("-avaproof")) {
252 if (!argsman.IsArgSet("-avamasterkey")) {
253 error = _(
254 "The avalanche master key is missing for the avalanche proof.");
255 return nullptr;
256 }
257
258 masterKey = DecodeSecret(argsman.GetArg("-avamasterkey", ""));
259 if (!masterKey.IsValid()) {
260 error = _("The avalanche master key is invalid.");
261 return nullptr;
262 }
263
264 auto proof = RCUPtr<Proof>::make();
265 if (!Proof::FromHex(*proof, argsman.GetArg("-avaproof", ""), error)) {
266 // error is set by FromHex
267 return nullptr;
268 }
269
270 peerData = std::make_unique<PeerData>();
271 peerData->proof = proof;
272 if (!VerifyProof(stakeUtxoDustThreshold, *peerData->proof, error)) {
273 // error is set by VerifyProof
274 return nullptr;
275 }
276
277 std::unique_ptr<DelegationBuilder> dgb;
278 const CPubKey &masterPubKey = masterKey.GetPubKey();
279
280 if (argsman.IsArgSet("-avadelegation")) {
281 Delegation dg;
282 if (!Delegation::FromHex(dg, argsman.GetArg("-avadelegation", ""),
283 error)) {
284 // error is set by FromHex()
285 return nullptr;
286 }
287
288 if (dg.getProofId() != peerData->proof->getId()) {
289 error = _("The delegation does not match the proof.");
290 return nullptr;
291 }
292
293 if (masterPubKey != dg.getDelegatedPubkey()) {
294 error = _(
295 "The master key does not match the delegation public key.");
296 return nullptr;
297 }
298
299 dgb = std::make_unique<DelegationBuilder>(dg);
300 } else {
301 if (masterPubKey != peerData->proof->getMaster()) {
302 error =
303 _("The master key does not match the proof public key.");
304 return nullptr;
305 }
306
307 dgb = std::make_unique<DelegationBuilder>(*peerData->proof);
308 }
309
310 // Generate the delegation to the session key.
311 const CPubKey sessionPubKey = sessionKey.GetPubKey();
312 if (sessionPubKey != masterPubKey) {
313 if (!dgb->addLevel(masterKey, sessionPubKey)) {
314 error = _("Failed to generate a delegation for this session.");
315 return nullptr;
316 }
317 }
318 peerData->delegation = dgb->build();
319
320 if (!VerifyDelegation(peerData->delegation, sessionPubKey, error)) {
321 // error is set by VerifyDelegation
322 return nullptr;
323 }
324 }
325
326 const auto queryTimeoutDuration =
327 std::chrono::milliseconds(argsman.GetIntArg(
328 "-avatimeout", AVALANCHE_DEFAULT_QUERY_TIMEOUT.count()));
329
330 // Determine quorum parameters
332 if (argsman.IsArgSet("-avaminquorumstake") &&
333 !ParseMoney(argsman.GetArg("-avaminquorumstake", ""), minQuorumStake)) {
334 error = _("The avalanche min quorum stake amount is invalid.");
335 return nullptr;
336 }
337
338 if (!MoneyRange(minQuorumStake)) {
339 error = _("The avalanche min quorum stake amount is out of range.");
340 return nullptr;
341 }
342
343 double minQuorumConnectedStakeRatio =
345 if (argsman.IsArgSet("-avaminquorumconnectedstakeratio")) {
346 // Parse the parameter with a precision of 0.000001.
347 int64_t megaMinRatio;
348 if (!ParseFixedPoint(
349 argsman.GetArg("-avaminquorumconnectedstakeratio", ""), 6,
350 &megaMinRatio)) {
351 error =
352 _("The avalanche min quorum connected stake ratio is invalid.");
353 return nullptr;
354 }
355 minQuorumConnectedStakeRatio = double(megaMinRatio) / 1000000;
356 }
357
358 if (minQuorumConnectedStakeRatio < 0 || minQuorumConnectedStakeRatio > 1) {
359 error = _(
360 "The avalanche min quorum connected stake ratio is out of range.");
361 return nullptr;
362 }
363
364 int64_t minAvaproofsNodeCount =
365 argsman.GetIntArg("-avaminavaproofsnodecount",
367 if (minAvaproofsNodeCount < 0) {
368 error = _("The minimum number of node that sent avaproofs message "
369 "should be non-negative");
370 return nullptr;
371 }
372
373 // Determine voting parameters
374 int64_t staleVoteThreshold = argsman.GetIntArg(
375 "-avastalevotethreshold", AVALANCHE_VOTE_STALE_THRESHOLD);
377 error = strprintf(_("The avalanche stale vote threshold must be "
378 "greater than or equal to %d"),
380 return nullptr;
381 }
382 if (staleVoteThreshold > std::numeric_limits<uint32_t>::max()) {
383 error = strprintf(_("The avalanche stale vote threshold must be less "
384 "than or equal to %d"),
385 std::numeric_limits<uint32_t>::max());
386 return nullptr;
387 }
388
389 int64_t staleVoteFactor =
390 argsman.GetIntArg("-avastalevotefactor", AVALANCHE_VOTE_STALE_FACTOR);
391 if (staleVoteFactor <= 0) {
392 error = _("The avalanche stale vote factor must be greater than 0");
393 return nullptr;
394 }
395 if (staleVoteFactor > std::numeric_limits<uint32_t>::max()) {
396 error = strprintf(_("The avalanche stale vote factor must be less than "
397 "or equal to %d"),
398 std::numeric_limits<uint32_t>::max());
399 return nullptr;
400 }
401
402 Config avaconfig(queryTimeoutDuration);
403
404 // We can't use std::make_unique with a private constructor
405 return std::unique_ptr<Processor>(new Processor(
406 std::move(avaconfig), chain, connman, chainman, mempool, scheduler,
407 std::move(peerData), std::move(sessionKey),
408 Proof::amountToScore(minQuorumStake), minQuorumConnectedStakeRatio,
410 stakeUtxoDustThreshold,
411 argsman.GetBoolArg("-avalanchepreconsensus",
413 argsman.GetBoolArg("-avalanchestakingpreconsensus",
415}
416
417static bool isNull(const AnyVoteItem &item) {
418 return item.valueless_by_exception() ||
419 std::visit(variant::overloaded{
420 [](const StakeContenderId &contenderId) {
421 return contenderId == uint256::ZERO;
422 },
423 [](const auto &item) { return item == nullptr; },
424 },
425 item);
426};
427
429 if (isNull(item)) {
430 return false;
431 }
432
433 if (!isWorthPolling(item)) {
434 return false;
435 }
436
437 // getLocalAcceptance() takes the voteRecords read lock, so we can't inline
438 // the calls or we get a deadlock.
439 const bool accepted = getLocalAcceptance(item);
440
442 ->insert(std::make_pair(item, VoteRecord(accepted)))
443 .second;
444}
445
447 if (!proof) {
448 return false;
449 }
450
451 if (isRecentlyFinalized(proof->getId())) {
452 PeerId peerid;
454 if (peerManager->forPeer(proof->getId(), [&](const Peer &peer) {
455 peerid = peer.peerid;
456 return true;
457 })) {
458 return peerManager->setFinalized(peerid);
459 }
460 }
461
462 return addToReconcile(proof);
463}
464
465bool Processor::isAccepted(const AnyVoteItem &item) const {
466 if (isNull(item)) {
467 return false;
468 }
469
470 auto r = voteRecords.getReadView();
471 auto it = r->find(item);
472 if (it == r.end()) {
473 return false;
474 }
475
476 return it->second.isAccepted();
477}
478
479int Processor::getConfidence(const AnyVoteItem &item) const {
480 if (isNull(item)) {
481 return -1;
482 }
483
484 auto r = voteRecords.getReadView();
485 auto it = r->find(item);
486 if (it == r.end()) {
487 return -1;
488 }
489
490 return it->second.getConfidence();
491}
492
493bool Processor::isPolled(const AnyVoteItem &item) const {
494 if (isNull(item)) {
495 return false;
496 }
497
498 auto r = voteRecords.getReadView();
499 auto it = r->find(item);
500 return it != r.end();
501}
502
503bool Processor::isRecentlyFinalized(const uint256 &itemId) const {
504 return WITH_LOCK(cs_finalizedItems, return finalizedItems.contains(itemId));
505}
506
508 WITH_LOCK(cs_finalizedItems, finalizedItems.insert(itemId));
509}
510
513 finalizedItems.reset();
514}
515
516namespace {
521 class TCPResponse {
522 Response response;
524
525 public:
526 TCPResponse(Response responseIn, const CKey &key)
527 : response(std::move(responseIn)) {
528 HashWriter hasher{};
529 hasher << response;
530 const uint256 hash = hasher.GetHash();
531
532 // Now let's sign!
533 if (!key.SignSchnorr(hash, sig)) {
534 sig.fill(0);
535 }
536 }
537
538 // serialization support
539 SERIALIZE_METHODS(TCPResponse, obj) {
540 READWRITE(obj.response, obj.sig);
541 }
542 };
543} // namespace
544
548 TCPResponse(std::move(response), sessionKey)));
549}
550
552 std::vector<VoteItemUpdate> &updates,
553 bool &disconnect, std::string &error) {
554 disconnect = false;
555 updates.clear();
556 {
557 // Save the time at which we can query again.
559
560 // FIXME: This will override the time even when we received an old stale
561 // message. This should check that the message is indeed the most up to
562 // date one before updating the time.
563 peerManager->updateNextRequestTime(
564 nodeid, Now<SteadyMilliseconds>() +
565 std::chrono::milliseconds(response.getCooldown()));
566 }
567
568 std::vector<CInv> invs;
569
570 {
571 // Check that the query exists. There is a possibility that it has been
572 // deleted if the query timed out, so we don't disconnect for poor
573 // networking over time.
574 // Disconnecting has to be handled at callsite to avoid DoS.
575 auto w = queries.getWriteView();
576 auto it = w->find(std::make_tuple(nodeid, response.getRound()));
577 if (it == w.end()) {
578 error = "unexpected-ava-response";
579 return false;
580 }
581
582 invs = std::move(it->invs);
583 w->erase(it);
584 }
585
586 // Verify that the request and the vote are consistent.
587 const std::vector<Vote> &votes = response.GetVotes();
588 size_t size = invs.size();
589 if (votes.size() != size) {
590 disconnect = true;
591 error = "invalid-ava-response-size";
592 return false;
593 }
594
595 for (size_t i = 0; i < size; i++) {
596 if (invs[i].hash != votes[i].GetHash()) {
597 disconnect = true;
598 error = "invalid-ava-response-content";
599 return false;
600 }
601 }
602
603 std::map<AnyVoteItem, Vote, VoteMapComparator> responseItems;
604
605 // At this stage we are certain that invs[i] matches votes[i], so we can use
606 // the inv type to retrieve what is being voted on.
607 for (size_t i = 0; i < size; i++) {
608 auto item = getVoteItemFromInv(invs[i]);
609
610 if (isNull(item)) {
611 // This should not happen, but just in case...
612 continue;
613 }
614
615 if (!isWorthPolling(item)) {
616 // There is no point polling this item.
617 continue;
618 }
619
620 responseItems.insert(std::make_pair(std::move(item), votes[i]));
621 }
622
623 auto voteRecordsWriteView = voteRecords.getWriteView();
624
625 // Register votes.
626 for (const auto &p : responseItems) {
627 auto item = p.first;
628 const Vote &v = p.second;
629
630 auto it = voteRecordsWriteView->find(item);
631 if (it == voteRecordsWriteView.end()) {
632 // We are not voting on that item anymore.
633 continue;
634 }
635
636 auto &vr = it->second;
637 if (!vr.registerVote(nodeid, v.GetError())) {
638 if (vr.isStale(staleVoteThreshold, staleVoteFactor)) {
639 updates.emplace_back(std::move(item), VoteStatus::Stale);
640
641 // Just drop stale votes. If we see this item again, we'll
642 // do a new vote.
643 voteRecordsWriteView->erase(it);
644 }
645 // This vote did not provide any extra information, move on.
646 continue;
647 }
648
649 if (!vr.hasFinalized()) {
650 // This item has not been finalized, so we have nothing more to
651 // do.
652 updates.emplace_back(std::move(item), vr.isAccepted()
655 continue;
656 }
657
658 // We just finalized a vote. If it is valid, then let the caller
659 // know. Either way, remove the item from the map.
660 updates.emplace_back(std::move(item), vr.isAccepted()
663 voteRecordsWriteView->erase(it);
664 }
665
666 // FIXME This doesn't belong here as it has nothing to do with vote
667 // registration.
668 for (const auto &update : updates) {
669 if (update.getStatus() != VoteStatus::Finalized &&
670 update.getStatus() != VoteStatus::Invalid) {
671 continue;
672 }
673
674 const auto &item = update.getVoteItem();
675
676 if (!std::holds_alternative<const CBlockIndex *>(item)) {
677 continue;
678 }
679
680 if (update.getStatus() == VoteStatus::Invalid) {
681 // Track invalidated blocks. Other invalidated types are not
682 // tracked because they may be rejected for transient reasons
683 // (ex: immature proofs or orphaned txs) With blocks this is not
684 // the case. A rejected block will not be mined on. To prevent
685 // reorgs, invalidated blocks should never be polled again.
687 invalidatedBlocks.insert(GetVoteItemId(item));
688 continue;
689 }
690
691 // At this point the block index can only be finalized
692 const CBlockIndex *pindex = std::get<const CBlockIndex *>(item);
694 if (finalizationTip &&
695 finalizationTip->GetAncestor(pindex->nHeight) == pindex) {
696 continue;
697 }
698
699 finalizationTip = pindex;
700 }
701
702 return true;
703}
704
706 return sessionKey.GetPubKey();
707}
708
711
712 Delegation delegation;
713 if (peerData) {
714 if (!canShareLocalProof()) {
715 if (!delayedAvahelloNodeIds.emplace(pfrom->GetId()).second) {
716 // Nothing to do
717 return false;
718 }
719 } else {
720 delegation = peerData->delegation;
721 }
722 }
723
724 HashWriter hasher{};
725 hasher << delegation.getId();
726 hasher << pfrom->GetLocalNonce();
727 hasher << pfrom->nRemoteHostNonce;
728 hasher << pfrom->GetLocalExtraEntropy();
729 hasher << pfrom->nRemoteExtraEntropy;
730
731 // Now let's sign!
733 if (!sessionKey.SignSchnorr(hasher.GetHash(), sig)) {
734 return false;
735 }
736
738 pfrom, NetMsg::Make(NetMsgType::AVAHELLO, Hello(delegation, sig)));
739
740 return delegation.getLimitedProofId() != uint256::ZERO;
741}
742
745 return sendHelloInternal(pfrom));
746}
747
750
751 auto it = delayedAvahelloNodeIds.begin();
752 while (it != delayedAvahelloNodeIds.end()) {
753 if (connman->ForNode(*it, [&](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(
755 return sendHelloInternal(pnode);
756 })) {
757 // Our proof has been announced to this node
758 it = delayedAvahelloNodeIds.erase(it);
759 } else {
760 ++it;
761 }
762 }
763}
764
766 return peerData ? peerData->proof : ProofRef();
767}
768
771
773 if (!peerData) {
774 return state;
775 }
776
777 if (peerData->proof) {
779
780 const ProofId &proofid = peerData->proof->getId();
781
782 if (peerManager->isInConflictingPool(proofid)) {
784 "conflicting-utxos");
785 return state;
786 }
787
788 if (peerManager->isInvalid(proofid)) {
789 // If proof is invalid but verifies valid, it's been rejected by
790 // avalanche
792 "avalanche-invalidated");
793 return state;
794 }
795 }
796
797 return WITH_LOCK(peerData->cs_proofState, return peerData->proofState);
798}
799
802 scheduler, [this]() { this->runEventLoop(); }, AVALANCHE_TIME_STEP);
803}
804
806 return eventLoop.stopEventLoop();
807}
808
811
813 // Before IBD is complete there is no way to make sure a proof is valid
814 // or not, e.g. it can be spent in a block we don't know yet. In order
815 // to increase confidence that our proof set is similar to other nodes
816 // on the network, the messages received during IBD are not accounted.
817 return;
818 }
819
821 if (peerManager->latchAvaproofsSent(nodeid)) {
823 }
824}
825
826/*
827 * Returns a bool indicating whether we have a usable Avalanche quorum enabling
828 * us to take decisions based on polls.
829 */
832
833 {
835 if (peerManager->getNodeCount() < 8) {
836 // There is no point polling if we know the vote cannot converge
837 return false;
838 }
839 }
840
841 /*
842 * The following parameters can naturally go temporarly below the threshold
843 * under normal circumstances, like during a proof replacement with a lower
844 * stake amount, or the discovery of a new proofs for which we don't have a
845 * node yet.
846 * In order to prevent our node from starting and stopping the polls
847 * spuriously on such event, the quorum establishement is latched. The only
848 * parameters that should not latched is the minimum node count, as this
849 * would cause the poll to be inconclusive anyway and should not happen
850 * under normal circumstances.
851 */
853 return true;
854 }
855
856 // Don't do Avalanche while node is IBD'ing
858 return false;
859 }
860
862 return false;
863 }
864
865 auto localProof = getLocalProof();
866
867 // Get the registered proof score and registered score we have nodes for
868 uint32_t totalPeersScore;
869 uint32_t connectedPeersScore;
870 {
872 totalPeersScore = peerManager->getTotalPeersScore();
873 connectedPeersScore = peerManager->getConnectedPeersScore();
874
875 // Consider that we are always connected to our proof, even if we are
876 // the single node using that proof.
877 if (localProof &&
878 peerManager->forPeer(localProof->getId(), [](const Peer &peer) {
879 return peer.node_count == 0;
880 })) {
881 connectedPeersScore += localProof->getScore();
882 }
883 }
884
885 // Ensure enough is being staked overall
886 if (totalPeersScore < minQuorumScore) {
887 return false;
888 }
889
890 // Ensure we have connected score for enough of the overall score
891 uint32_t minConnectedScore =
892 std::round(double(totalPeersScore) * minQuorumConnectedScoreRatio);
893 if (connectedPeersScore < minConnectedScore) {
894 return false;
895 }
896
897 quorumIsEstablished = true;
898
899 // Attempt to compute the staking rewards winner now so we don't have to
900 // wait for a block if we already have all the prerequisites.
901 const CBlockIndex *pprev = WITH_LOCK(cs_main, return chainman.ActiveTip());
902 bool computedRewards = false;
903 if (pprev && IsStakingRewardsActivated(chainman.GetConsensus(), pprev)) {
904 computedRewards = computeStakingReward(pprev);
905 }
906 if (pprev && isStakingPreconsensusActivated(pprev) && !computedRewards) {
907 // It's possible to have quorum shortly after startup if peers were
908 // loaded from disk, but staking rewards may not be ready yet. In this
909 // case, we can still promote and poll for contenders.
911 }
912
913 return true;
914}
915
917 // The flag is latched
919 return true;
920 }
921
922 // Don't share our proof if we don't have any inbound connection.
923 // This is a best effort measure to prevent advertising a proof if we have
924 // limited network connectivity.
926
928}
929
931 if (!pindex) {
932 return false;
933 }
934
935 // If the quorum is not established there is no point picking a winner that
936 // will be rejected.
937 if (!isQuorumEstablished()) {
938 return false;
939 }
940
941 {
943 if (stakingRewards.count(pindex->GetBlockHash()) > 0) {
944 return true;
945 }
946 }
947
948 StakingReward _stakingRewards;
949 _stakingRewards.blockheight = pindex->nHeight;
950
951 bool rewardsInserted = false;
952 if (WITH_LOCK(cs_peerManager, return peerManager->selectStakingRewardWinner(
953 pindex, _stakingRewards.winners))) {
954 {
956 rewardsInserted =
957 stakingRewards
958 .emplace(pindex->GetBlockHash(), std::move(_stakingRewards))
959 .second;
960 }
961
962 if (isStakingPreconsensusActivated(pindex)) {
964 }
965 }
966
967 return rewardsInserted;
968}
969
972 return stakingRewards.erase(prevBlockHash) > 0;
973}
974
975void Processor::cleanupStakingRewards(const int minHeight) {
976 // Avoid cs_main => cs_peerManager reverse order locking
980
981 {
983 // std::erase_if is only defined since C++20
984 for (auto it = stakingRewards.begin(); it != stakingRewards.end();) {
985 if (it->second.blockheight < minHeight) {
986 it = stakingRewards.erase(it);
987 } else {
988 ++it;
989 }
990 }
991 }
992
994 return peerManager->cleanupStakeContenders(minHeight));
995}
996
998 const BlockHash &prevBlockHash,
999 std::vector<std::pair<ProofId, CScript>> &winners) const {
1001 auto it = stakingRewards.find(prevBlockHash);
1002 if (it == stakingRewards.end()) {
1003 return false;
1004 }
1005
1006 winners = it->second.winners;
1007 return true;
1008}
1009
1011 std::vector<CScript> &payouts) const {
1012 std::vector<std::pair<ProofId, CScript>> winners;
1013 if (!getStakingRewardWinners(prevBlockHash, winners)) {
1014 return false;
1015 }
1016
1017 payouts.clear();
1018 payouts.reserve(winners.size());
1019 for (auto &winner : winners) {
1020 payouts.push_back(std::move(winner.second));
1021 }
1022
1023 return true;
1024}
1025
1027 const std::vector<CScript> &payouts) {
1028 assert(pprev);
1029
1030 StakingReward stakingReward;
1031 stakingReward.blockheight = pprev->nHeight;
1032
1033 stakingReward.winners.reserve(payouts.size());
1034 for (const CScript &payout : payouts) {
1035 stakingReward.winners.push_back({ProofId(), payout});
1036 }
1037
1038 if (isStakingPreconsensusActivated(pprev)) {
1040 peerManager->setStakeContenderWinners(pprev, payouts);
1041 }
1042
1044 return stakingRewards.insert_or_assign(pprev->GetBlockHash(), stakingReward)
1045 .second;
1046}
1047
1049 const CBlockIndex *pprev,
1050 const std::vector<std::pair<ProofId, CScript>> &winners) {
1051 assert(pprev);
1052
1053 StakingReward stakingReward;
1054 stakingReward.blockheight = pprev->nHeight;
1055 stakingReward.winners = winners;
1056
1058 return stakingRewards.insert_or_assign(pprev->GetBlockHash(), stakingReward)
1059 .second;
1060}
1061
1062void Processor::FinalizeNode(const ::Config &config, const CNode &node) {
1064
1065 const NodeId nodeid = node.GetId();
1066 WITH_LOCK(cs_peerManager, peerManager->removeNode(nodeid));
1067 WITH_LOCK(cs_delayedAvahelloNodeIds, delayedAvahelloNodeIds.erase(nodeid));
1068}
1069
1071 const StakeContenderId &contenderId) const {
1074
1075 BlockHash prevblockhash;
1076 int status =
1077 WITH_LOCK(cs_peerManager, return peerManager->getStakeContenderStatus(
1078 contenderId, prevblockhash));
1079
1080 if (status != -1) {
1081 std::vector<std::pair<ProofId, CScript>> winners;
1082 getStakingRewardWinners(prevblockhash, winners);
1083 if (winners.size() == 0) {
1084 // If we have not selected a local staking rewards winner yet,
1085 // indicate this contender is pending to avoid convergence issues.
1086 return -2;
1087 }
1088 }
1089
1090 return status;
1091}
1092
1095 peerManager->acceptStakeContender(contenderId);
1096}
1097
1100
1101 BlockHash prevblockhash;
1102 std::vector<std::pair<ProofId, CScript>> winners;
1103 {
1105 peerManager->finalizeStakeContender(contenderId, prevblockhash,
1106 winners);
1107 }
1108
1109 // Set staking rewards to include newly finalized contender
1110 if (winners.size() > 0) {
1111 const CBlockIndex *block = WITH_LOCK(
1112 cs_main,
1113 return chainman.m_blockman.LookupBlockIndex(prevblockhash));
1114 if (block) {
1115 setStakingRewardWinners(block, winners);
1116 }
1117 }
1118}
1119
1122 peerManager->rejectStakeContender(contenderId);
1123}
1124
1126 assert(pprev);
1127
1128 if (!isQuorumEstablished()) {
1129 // Avoid growing the contender cache before it's possible to clean it up
1130 // (by finalizing blocks).
1131 return;
1132 }
1133
1134 {
1136 peerManager->promoteStakeContendersToBlock(pprev);
1137 }
1138
1139 // If staking rewards have not been computed yet, we will try again when
1140 // they have been.
1141 std::vector<StakeContenderId> pollableContenders;
1142 if (setContenderStatusForLocalWinners(pprev, pollableContenders)) {
1143 for (const StakeContenderId &contender : pollableContenders) {
1144 addToReconcile(contender);
1145 }
1146 }
1147}
1148
1150 const CBlockIndex *pindex,
1151 std::vector<StakeContenderId> &pollableContenders) {
1152 const BlockHash prevblockhash = pindex->GetBlockHash();
1153 std::vector<std::pair<ProofId, CScript>> winners;
1154 getStakingRewardWinners(prevblockhash, winners);
1155
1157 return peerManager->setContenderStatusForLocalWinners(
1158 pindex, winners, AVALANCHE_CONTENDER_MAX_POLLABLE, pollableContenders);
1159}
1160
1162 const bool registerLocalProof = canShareLocalProof();
1163 auto registerProofs = [&]() {
1165
1166 auto registeredProofs = peerManager->updatedBlockTip();
1167
1168 ProofRegistrationState localProofState;
1169 if (peerData && peerData->proof && registerLocalProof) {
1170 if (peerManager->registerProof(peerData->proof, localProofState)) {
1171 registeredProofs.insert(peerData->proof);
1172 }
1173
1174 if (localProofState.GetResult() ==
1176 // If our proof already exists, that's fine but we don't want to
1177 // erase the state with a duplicated proof status, so let's
1178 // retrieve the proper state. It also means we are able to
1179 // update the status should the proof move from one pool to the
1180 // other.
1181 const ProofId &localProofId = peerData->proof->getId();
1182 if (peerManager->isImmature(localProofId)) {
1184 "immature-proof");
1185 }
1186 if (peerManager->isInConflictingPool(localProofId)) {
1187 localProofState.Invalid(
1189 "conflicting-utxos");
1190 }
1191 if (peerManager->isBoundToPeer(localProofId)) {
1192 localProofState = ProofRegistrationState();
1193 }
1194 }
1195
1196 WITH_LOCK(peerData->cs_proofState,
1197 peerData->proofState = std::move(localProofState));
1198 }
1199
1200 return registeredProofs;
1201 };
1202
1203 auto registeredProofs = registerProofs();
1204 for (const auto &proof : registeredProofs) {
1205 reconcileOrFinalize(proof);
1206 }
1207
1208 const CBlockIndex *activeTip =
1210 if (activeTip && isStakingPreconsensusActivated(activeTip)) {
1212 }
1213}
1214
1217 WITH_LOCK(cs_main, return chainman.ActiveTip()))) {
1218 addToReconcile(tx);
1219 }
1220}
1221
1223 // Don't poll if quorum hasn't been established yet
1224 if (!isQuorumEstablished()) {
1225 return;
1226 }
1227
1228 // First things first, check if we have requests that timed out and clear
1229 // them.
1231
1232 // Make sure there is at least one suitable node to query before gathering
1233 // invs.
1234 NodeId nodeid = WITH_LOCK(cs_peerManager, return peerManager->selectNode());
1235 if (nodeid == NO_NODE) {
1236 return;
1237 }
1238 std::vector<CInv> invs = getInvsForNextPoll();
1239 if (invs.empty()) {
1240 return;
1241 }
1242
1244
1245 do {
1251 bool hasSent = connman->ForNode(
1252 nodeid, [this, &invs](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(
1254 uint64_t current_round = round++;
1255
1256 {
1257 // Compute the time at which this requests times out.
1258 auto timeout = Now<SteadyMilliseconds>() +
1260 // Register the query.
1261 queries.getWriteView()->insert(
1262 {pnode->GetId(), current_round, timeout, invs});
1263 // Set the timeout.
1264 peerManager->updateNextRequestTime(pnode->GetId(), timeout);
1265 }
1266
1267 pnode->invsPolled(invs.size());
1268
1269 // Send the query to the node.
1272 Poll(current_round, std::move(invs))));
1273 return true;
1274 });
1275
1276 // Success!
1277 if (hasSent) {
1278 return;
1279 }
1280
1281 // This node is obsolete, delete it.
1282 peerManager->removeNode(nodeid);
1283
1284 // Get next suitable node to try again
1285 nodeid = peerManager->selectNode();
1286 } while (nodeid != NO_NODE);
1287}
1288
1290 auto now = Now<SteadyMilliseconds>();
1291 std::map<CInv, uint8_t> timedout_items{};
1292
1293 {
1294 // Clear expired requests.
1295 auto w = queries.getWriteView();
1296 auto it = w->get<query_timeout>().begin();
1297 while (it != w->get<query_timeout>().end() && it->timeout < now) {
1298 for (const auto &i : it->invs) {
1299 timedout_items[i]++;
1300 }
1301
1302 w->get<query_timeout>().erase(it++);
1303 }
1304 }
1305
1306 if (timedout_items.empty()) {
1307 return;
1308 }
1309
1310 // In flight request accounting.
1311 auto voteRecordsWriteView = voteRecords.getWriteView();
1312 for (const auto &p : timedout_items) {
1313 auto item = getVoteItemFromInv(p.first);
1314
1315 if (isNull(item)) {
1316 continue;
1317 }
1318
1319 auto it = voteRecordsWriteView->find(item);
1320 if (it == voteRecordsWriteView.end()) {
1321 continue;
1322 }
1323
1324 it->second.clearInflightRequest(p.second);
1325 }
1326}
1327
1328std::vector<CInv> Processor::getInvsForNextPoll(bool forPoll) {
1329 std::vector<CInv> invs;
1330
1331 {
1332 // First remove all items that are not worth polling.
1333 auto w = voteRecords.getWriteView();
1334 for (auto it = w->begin(); it != w->end();) {
1335 if (!isWorthPolling(it->first)) {
1336 it = w->erase(it);
1337 } else {
1338 ++it;
1339 }
1340 }
1341 }
1342
1343 auto buildInvFromVoteItem = variant::overloaded{
1344 [](const ProofRef &proof) {
1345 return CInv(MSG_AVA_PROOF, proof->getId());
1346 },
1347 [](const CBlockIndex *pindex) {
1348 return CInv(MSG_BLOCK, pindex->GetBlockHash());
1349 },
1350 [](const StakeContenderId &contenderId) {
1351 return CInv(MSG_AVA_STAKE_CONTENDER, contenderId);
1352 },
1353 [](const CTransactionRef &tx) { return CInv(MSG_TX, tx->GetHash()); },
1354 };
1355
1356 auto r = voteRecords.getReadView();
1357 for (const auto &[item, voteRecord] : r) {
1358 if (invs.size() >= AVALANCHE_MAX_ELEMENT_POLL) {
1359 // Make sure we do not produce more invs than specified by the
1360 // protocol.
1361 return invs;
1362 }
1363
1364 const bool shouldPoll =
1365 forPoll ? voteRecord.registerPoll() : voteRecord.shouldPoll();
1366
1367 if (!shouldPoll) {
1368 continue;
1369 }
1370
1371 invs.emplace_back(std::visit(buildInvFromVoteItem, item));
1372 }
1373
1374 return invs;
1375}
1376
1378 if (inv.IsMsgBlk()) {
1380 BlockHash(inv.hash)));
1381 }
1382
1383 if (inv.IsMsgProof()) {
1385 return peerManager->getProof(ProofId(inv.hash)));
1386 }
1387
1388 if (inv.IsMsgStakeContender()) {
1389 return StakeContenderId(inv.hash);
1390 }
1391
1392 if (mempool && inv.IsMsgTx()) {
1393 LOCK(mempool->cs);
1394 if (CTransactionRef tx = mempool->get(TxId(inv.hash))) {
1395 return tx;
1396 }
1398 [&inv](const TxConflicting &conflicting) {
1399 return conflicting.GetTx(TxId(inv.hash));
1400 })) {
1401 return tx;
1402 }
1403 }
1404
1405 return {nullptr};
1406}
1407
1410
1411 LOCK(cs_main);
1412
1413 if (pindex->nStatus.isInvalid()) {
1414 // No point polling invalid blocks.
1415 return false;
1416 }
1417
1419 return processor.finalizationTip &&
1420 processor.finalizationTip->GetAncestor(
1421 pindex->nHeight) == pindex)) {
1422 // There is no point polling blocks that are ancestor of a block that
1423 // has been accepted by the network.
1424 return false;
1425 }
1426
1428 return processor.invalidatedBlocks.contains(
1429 pindex->GetBlockHash()))) {
1430 // Blocks invalidated by Avalanche should not be polled twice.
1431 return false;
1432 }
1433
1434 return true;
1435}
1436
1438 // Avoid lock order issues cs_main -> cs_peerManager
1440 AssertLockNotHeld(processor.cs_peerManager);
1441
1442 const ProofId &proofid = proof->getId();
1443
1444 LOCK(processor.cs_peerManager);
1445
1446 // No point polling immature or discarded proofs
1447 return processor.peerManager->isBoundToPeer(proofid) ||
1448 processor.peerManager->isInConflictingPool(proofid);
1449}
1450
1452 const StakeContenderId &contenderId) const {
1453 AssertLockNotHeld(processor.cs_peerManager);
1454 AssertLockNotHeld(processor.cs_stakingRewards);
1455
1456 // Only worth polling for contenders that we know about
1457 return processor.getStakeContenderStatus(contenderId) != -1;
1458}
1459
1461 if (!processor.mempool) {
1462 return false;
1463 }
1464
1465 AssertLockNotHeld(processor.mempool->cs);
1466 return WITH_LOCK(processor.mempool->cs,
1467 return processor.mempool->isWorthPolling(tx));
1468}
1469
1471 return !isRecentlyFinalized(GetVoteItemId(item)) &&
1472 std::visit(IsWorthPolling(*this), item);
1473}
1474
1476 const CBlockIndex *pindex) const {
1478
1479 return WITH_LOCK(cs_main,
1480 return processor.chainman.ActiveChain().Contains(pindex));
1481}
1482
1484 AssertLockNotHeld(processor.cs_peerManager);
1485
1486 return WITH_LOCK(
1487 processor.cs_peerManager,
1488 return processor.peerManager->isBoundToPeer(proof->getId()));
1489}
1490
1492 const StakeContenderId &contenderId) const {
1493 AssertLockNotHeld(processor.cs_peerManager);
1494 AssertLockNotHeld(processor.cs_stakingRewards);
1495
1496 return processor.getStakeContenderStatus(contenderId) == 0;
1497}
1498
1500 const CTransactionRef &tx) const {
1501 if (!processor.mempool) {
1502 return false;
1503 }
1504
1505 AssertLockNotHeld(processor.mempool->cs);
1506
1507 return WITH_LOCK(processor.mempool->cs,
1508 return processor.mempool->exists(tx->GetId()));
1509}
1510
1512 return m_preConsensus;
1513}
1514
1516 return m_stakingPreConsensus;
1517}
1518
1519} // namespace avalanche
bool MoneyRange(const Amount nValue)
Definition: amount.h:171
ArgsManager gArgs
Definition: args.cpp:40
uint32_t PeerId
Definition: node.h:15
static constexpr bool DEFAULT_PERSIST_AVAPEERS
Default for -persistavapeers.
Definition: avalanche.h:63
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...
Definition: avalanche.h:53
static constexpr bool DEFAULT_AVALANCHE_STAKING_PRECONSENSUS
Default for -avalanchestakingpreconsensus.
Definition: avalanche.h:69
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...
Definition: avalanche.h:60
static constexpr bool DEFAULT_AVALANCHE_PRECONSENSUS
Default for -avalanchepreconsensus.
Definition: avalanche.h:66
static constexpr Amount AVALANCHE_DEFAULT_MIN_QUORUM_STAKE
Default minimum cumulative stake of all known peers that constitutes a usable quorum.
Definition: avalanche.h:46
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:239
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:372
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:495
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:463
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:525
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
Definition: net.h:815
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3088
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2762
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3042
Inv(ventory) message data.
Definition: protocol.h:590
bool IsMsgBlk() const
Definition: protocol.h:621
bool IsMsgTx() const
Definition: protocol.h:609
bool IsMsgStakeContender() const
Definition: protocol.h:617
uint256 hash
Definition: protocol.h:593
bool IsMsgProof() const
Definition: protocol.h:613
An encapsulated secp256k1 private key.
Definition: key.h:28
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:97
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
bool SignSchnorr(const uint256 &hash, SchnorrSig &sig, uint32_t test_case=0) const
Create a Schnorr signature.
Definition: key.cpp:288
Information about a peer.
Definition: net.h:386
NodeId GetId() const
Definition: net.h:678
uint64_t GetLocalNonce() const
Definition: net.h:680
uint64_t nRemoteHostNonce
Definition: net.h:432
uint64_t nRemoteExtraEntropy
Definition: net.h:434
uint64_t GetLocalExtraEntropy() const
Definition: net.h:681
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:2941
An encapsulated public key.
Definition: pubkey.h:31
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
void scheduleEvery(Predicate p, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat p until it return false.
Definition: scheduler.cpp:114
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:221
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:317
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:676
auto withConflicting(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_conflicting)
Definition: txmempool.h:598
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1443
const Consensus::Params & GetConsensus() const
Definition: validation.h:1281
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1326
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:99
static RCUPtr make(Args &&...args)
Construct a new object that is owned by the pointer.
Definition: rcu.h:112
ReadView getReadView() const
Definition: rwcollection.h:76
WriteView getWriteView()
Definition: rwcollection.h:82
iterator end()
Definition: rwcollection.h:42
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition: validation.h:101
Result GetResult() const
Definition: validation.h:122
ProofId getProofId() const
Definition: delegation.cpp:56
static bool FromHex(Delegation &dg, const std::string &dgHex, bilingual_str &errorOut)
Definition: delegation.cpp:16
bool verify(DelegationState &state, CPubKey &auth) const
Definition: delegation.cpp:73
const DelegationId & getId() const
Definition: delegation.h:60
const CPubKey & getDelegatedPubkey() const
Definition: delegation.cpp:60
const LimitedProofId & getLimitedProofId() const
Definition: delegation.h:61
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
Definition: processor.cpp:140
void sendResponse(CNode *pfrom, Response response) const
Definition: processor.cpp:545
const uint32_t staleVoteThreshold
Voting parameters.
Definition: processor.h:230
std::atomic< bool > quorumIsEstablished
Definition: processor.h:224
AnyVoteItem getVoteItemFromInv(const CInv &inv) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1377
Mutex cs_finalizedItems
Rolling bloom filter to track recently finalized inventory items of any type.
Definition: processor.h:456
bool sendHelloInternal(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_delayedAvahelloNodeIds)
Definition: processor.cpp:709
int getConfidence(const AnyVoteItem &item) const
Definition: processor.cpp:479
bool addToReconcile(const AnyVoteItem &item) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:428
std::vector< CInv > getInvsForNextPoll(bool forPoll=true) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1328
bool isStakingPreconsensusActivated(const CBlockIndex *pprev) const
Definition: processor.cpp:1515
RWCollection< QuerySet > queries
Definition: processor.h:209
ProofRegistrationState getLocalProofRegistrationState() const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:769
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.
Definition: processor.cpp:1149
void transactionAddedToMempool(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:1215
bool sendHello(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Send a avahello message.
Definition: processor.cpp:743
bool isRecentlyFinalized(const uint256 &itemId) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:503
void setRecentlyFinalized(const uint256 &itemId) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:507
bool startEventLoop(CScheduler &scheduler)
Definition: processor.cpp:800
bool isQuorumEstablished() LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:830
std::atomic< uint64_t > round
Keep track of peers and queries sent.
Definition: processor.h:173
static std::unique_ptr< Processor > MakeProcessor(const ArgsManager &argsman, interfaces::Chain &chain, CConnman *connman, ChainstateManager &chainman, CTxMemPool *mempoolIn, CScheduler &scheduler, bilingual_str &error)
Definition: processor.cpp:224
EventLoop eventLoop
Event loop machinery.
Definition: processor.h:217
CTxMemPool * mempool
Definition: processor.h:163
int64_t minAvaproofsNodeCount
Definition: processor.h:226
const bool m_preConsensus
Definition: processor.h:267
bool isPolled(const AnyVoteItem &item) const
Definition: processor.cpp:493
Mutex cs_delayedAvahelloNodeIds
Definition: processor.h:240
bool setStakingRewardWinners(const CBlockIndex *pprev, const std::vector< CScript > &payouts) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
Definition: processor.cpp:1026
void runEventLoop() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1222
Mutex cs_invalidatedBlocks
We don't need many blocks but a low false positive rate.
Definition: processor.h:443
void updatedBlockTip() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1161
RWCollection< VoteMap > voteRecords
Items to run avalanche on.
Definition: processor.h:168
std::unique_ptr< interfaces::Handler > chainNotificationsHandler
Definition: processor.h:235
uint32_t minQuorumScore
Quorum management.
Definition: processor.h:222
void FinalizeNode(const ::Config &config, const CNode &node) override LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Handle removal of a node.
Definition: processor.cpp:1062
bool getStakingRewardWinners(const BlockHash &prevBlockHash, std::vector< std::pair< ProofId, CScript > > &winners) const EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
Definition: processor.cpp:997
std::atomic< bool > m_canShareLocalProof
Definition: processor.h:225
void cleanupStakingRewards(const int minHeight) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
Definition: processor.cpp:975
bool isAccepted(const AnyVoteItem &item) const
Definition: processor.cpp:465
ProofRef getLocalProof() const
Definition: processor.cpp:765
void acceptStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1093
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...
Definition: processor.cpp:446
int getStakeContenderStatus(const StakeContenderId &contenderId) const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Track votes on stake contenders.
Definition: processor.cpp:1070
const uint32_t staleVoteFactor
Definition: processor.h:231
void promoteAndPollStakeContenders(const CBlockIndex *pprev) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
Promote stake contender cache entries to a given block and then poll.
Definition: processor.cpp:1125
void sendDelayedAvahello() EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Definition: processor.cpp:748
void finalizeStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1098
std::unique_ptr< PeerData > peerData
Definition: processor.h:213
bool eraseStakingRewardWinner(const BlockHash &prevBlockHash) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
Definition: processor.cpp:970
bool isPreconsensusActivated(const CBlockIndex *pprev) const
Definition: processor.cpp:1511
CConnman * connman
Definition: processor.h:161
bool isWorthPolling(const AnyVoteItem &item) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:1470
CPubKey getSessionPubKey() const
Definition: processor.cpp:705
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)
Definition: processor.cpp:146
ChainstateManager & chainman
Definition: processor.h:162
std::atomic< int64_t > avaproofsNodeCounter
Definition: processor.h:227
std::atomic_bool m_stakingPreConsensus
Definition: processor.h:269
bool computeStakingReward(const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:930
bool registerVotes(NodeId nodeid, const Response &response, std::vector< VoteItemUpdate > &updates, bool &disconnect, std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:551
void clearTimedoutRequests() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1289
Mutex cs_peerManager
Keep track of the peers and associated infos.
Definition: processor.h:178
bool getLocalAcceptance(const AnyVoteItem &item) const
Definition: processor.h:489
void rejectStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1120
void avaproofsSent(NodeId nodeid) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:809
double minQuorumConnectedScoreRatio
Definition: processor.h:223
void clearFinalizedItems() EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:511
static bool FromHex(Proof &proof, const std::string &hexProof, bilingual_str &errorOut)
Definition: proof.cpp:52
bool verify(const Amount &stakeUtxoDustThreshold, ProofValidationState &state) const
Definition: proof.cpp:120
static uint32_t amountToScore(Amount amount)
Definition: proof.cpp:101
uint32_t GetError() const
Definition: protocol.h:27
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
Chain notifications.
Definition: chain.h:257
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:136
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)
256-bit opaque blob.
Definition: uint256.h:129
static const uint256 ZERO
Definition: uint256.h:134
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
int64_t NodeId
Definition: eviction.h:16
std::array< uint8_t, CPubKey::SCHNORR_SIZE > SchnorrSig
a Schnorr signature
Definition: key.h:25
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:77
#define LogPrint(category,...)
Definition: logging.h:452
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:37
@ AVALANCHE
Definition: logging.h:91
CSerializedNetMsg Make(std::string msg_type, Args &&...args)
const char * AVAHELLO
Contains a delegation and a signature.
Definition: protocol.cpp:51
const char * AVARESPONSE
Contains an avalanche::Response.
Definition: protocol.cpp:53
const char * AVAPOLL
Contains an avalanche::Poll.
Definition: protocol.cpp:52
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
Definition: proof.h:41
std::variant< const ProofRef, const CBlockIndex *, const StakeContenderId, const CTransactionRef > AnyVoteItem
Definition: processor.h:95
static bool VerifyDelegation(const Delegation &dg, const CPubKey &expectedPubKey, bilingual_str &error)
Definition: processor.cpp:93
static bool isNull(const AnyVoteItem &item)
Definition: processor.cpp:417
static bool VerifyProof(const Amount &stakeUtxoDustThreshold, const Proof &proof, bilingual_str &error)
Definition: processor.cpp:61
static uint256 GetVoteItemId(const AnyVoteItem &item)
Definition: processor.cpp:40
RCUPtr< const Proof > ProofRef
Definition: proof.h:186
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
Definition: init.h:31
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
Definition: nodeid.h:15
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
static const std::string AVAPEERS_FILE_NAME
Definition: processor.cpp:37
Response response
Definition: processor.cpp:522
static constexpr std::chrono::milliseconds AVALANCHE_TIME_STEP
Run the avalanche event loop every 10ms.
Definition: processor.cpp:35
SchnorrSig sig
Definition: processor.cpp:523
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...
Definition: processor.h:60
static constexpr std::chrono::milliseconds AVALANCHE_DEFAULT_QUERY_TIMEOUT
How long before we consider that a query timed out.
Definition: processor.h:65
static constexpr size_t AVALANCHE_MAX_ELEMENT_POLL
Maximum item that can be polled at once.
Definition: processor.h:54
static constexpr int AVALANCHE_MAX_PROOF_STAKES
How many UTXOs can be used for a single proof.
Definition: proof.h:30
@ MSG_TX
Definition: protocol.h:574
@ MSG_AVA_STAKE_CONTENDER
Definition: protocol.h:582
@ MSG_AVA_PROOF
Definition: protocol.h:581
@ MSG_BLOCK
Definition: protocol.h:575
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
Definition: serialize.h:276
#define READWRITE(...)
Definition: serialize.h:176
bool IsStakingRewardsActivated(const Consensus::Params &params, const CBlockIndex *pprev)
Definition: amount.h:21
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
bool stopEventLoop() EXCLUSIVE_LOCKS_REQUIRED(!cs_running)
Definition: eventloop.cpp:45
bool startEventLoop(CScheduler &scheduler, std::function< void()> runEventLoop, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!cs_running)
Definition: eventloop.cpp:13
A TxId is the identifier of a transaction.
Definition: txid.h:14
const std::chrono::milliseconds queryTimeoutDuration
Definition: config.h:13
bool operator()(const CBlockIndex *pindex) const LOCKS_EXCLUDED(cs_main)
Definition: processor.cpp:1475
bool operator()(const CBlockIndex *pindex) const LOCKS_EXCLUDED(cs_main)
Definition: processor.cpp:1408
ProofRegistrationState proofState GUARDED_BY(cs_proofState)
std::vector< std::pair< ProofId, CScript > > winners
Definition: processor.h:251
StakeContenderIds are unique for each block to ensure that the peer polling for their acceptance has ...
Vote history.
Definition: voterecord.h:49
Bilingual messages:
Definition: translation.h:17
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static constexpr uint32_t AVALANCHE_VOTE_STALE_FACTOR
Scaling factor applied to confidence to determine staleness threshold.
Definition: voterecord.h:35
static constexpr uint32_t AVALANCHE_VOTE_STALE_MIN_THRESHOLD
Lowest configurable staleness threshold (finalization score + necessary votes to increase confidence ...
Definition: voterecord.h:28
static constexpr uint32_t AVALANCHE_VOTE_STALE_THRESHOLD
Number of votes before a record may be considered as stale.
Definition: voterecord.h:22