Bitcoin ABC 0.32.4
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
547 pfrom, CNetMsgMaker(pfrom->GetCommonVersion())
549 TCPResponse(std::move(response), sessionKey)));
550}
551
553 std::vector<VoteItemUpdate> &updates,
554 bool &disconnect, std::string &error) {
555 disconnect = false;
556 updates.clear();
557 {
558 // Save the time at which we can query again.
560
561 // FIXME: This will override the time even when we received an old stale
562 // message. This should check that the message is indeed the most up to
563 // date one before updating the time.
564 peerManager->updateNextRequestTime(
565 nodeid, Now<SteadyMilliseconds>() +
566 std::chrono::milliseconds(response.getCooldown()));
567 }
568
569 std::vector<CInv> invs;
570
571 {
572 // Check that the query exists. There is a possibility that it has been
573 // deleted if the query timed out, so we don't disconnect for poor
574 // networking over time.
575 // Disconnecting has to be handled at callsite to avoid DoS.
576 auto w = queries.getWriteView();
577 auto it = w->find(std::make_tuple(nodeid, response.getRound()));
578 if (it == w.end()) {
579 error = "unexpected-ava-response";
580 return false;
581 }
582
583 invs = std::move(it->invs);
584 w->erase(it);
585 }
586
587 // Verify that the request and the vote are consistent.
588 const std::vector<Vote> &votes = response.GetVotes();
589 size_t size = invs.size();
590 if (votes.size() != size) {
591 disconnect = true;
592 error = "invalid-ava-response-size";
593 return false;
594 }
595
596 for (size_t i = 0; i < size; i++) {
597 if (invs[i].hash != votes[i].GetHash()) {
598 disconnect = true;
599 error = "invalid-ava-response-content";
600 return false;
601 }
602 }
603
604 std::map<AnyVoteItem, Vote, VoteMapComparator> responseItems;
605
606 // At this stage we are certain that invs[i] matches votes[i], so we can use
607 // the inv type to retrieve what is being voted on.
608 for (size_t i = 0; i < size; i++) {
609 auto item = getVoteItemFromInv(invs[i]);
610
611 if (isNull(item)) {
612 // This should not happen, but just in case...
613 continue;
614 }
615
616 if (!isWorthPolling(item)) {
617 // There is no point polling this item.
618 continue;
619 }
620
621 responseItems.insert(std::make_pair(std::move(item), votes[i]));
622 }
623
624 auto voteRecordsWriteView = voteRecords.getWriteView();
625
626 // Register votes.
627 for (const auto &p : responseItems) {
628 auto item = p.first;
629 const Vote &v = p.second;
630
631 auto it = voteRecordsWriteView->find(item);
632 if (it == voteRecordsWriteView.end()) {
633 // We are not voting on that item anymore.
634 continue;
635 }
636
637 auto &vr = it->second;
638 if (!vr.registerVote(nodeid, v.GetError())) {
639 if (vr.isStale(staleVoteThreshold, staleVoteFactor)) {
640 updates.emplace_back(std::move(item), VoteStatus::Stale);
641
642 // Just drop stale votes. If we see this item again, we'll
643 // do a new vote.
644 voteRecordsWriteView->erase(it);
645 }
646 // This vote did not provide any extra information, move on.
647 continue;
648 }
649
650 if (!vr.hasFinalized()) {
651 // This item has not been finalized, so we have nothing more to
652 // do.
653 updates.emplace_back(std::move(item), vr.isAccepted()
656 continue;
657 }
658
659 // We just finalized a vote. If it is valid, then let the caller
660 // know. Either way, remove the item from the map.
661 updates.emplace_back(std::move(item), vr.isAccepted()
664 voteRecordsWriteView->erase(it);
665 }
666
667 // FIXME This doesn't belong here as it has nothing to do with vote
668 // registration.
669 for (const auto &update : updates) {
670 if (update.getStatus() != VoteStatus::Finalized &&
671 update.getStatus() != VoteStatus::Invalid) {
672 continue;
673 }
674
675 const auto &item = update.getVoteItem();
676
677 if (!std::holds_alternative<const CBlockIndex *>(item)) {
678 continue;
679 }
680
681 if (update.getStatus() == VoteStatus::Invalid) {
682 // Track invalidated blocks. Other invalidated types are not
683 // tracked because they may be rejected for transient reasons
684 // (ex: immature proofs or orphaned txs) With blocks this is not
685 // the case. A rejected block will not be mined on. To prevent
686 // reorgs, invalidated blocks should never be polled again.
688 invalidatedBlocks.insert(GetVoteItemId(item));
689 continue;
690 }
691
692 // At this point the block index can only be finalized
693 const CBlockIndex *pindex = std::get<const CBlockIndex *>(item);
695 if (finalizationTip &&
696 finalizationTip->GetAncestor(pindex->nHeight) == pindex) {
697 continue;
698 }
699
700 finalizationTip = pindex;
701 }
702
703 return true;
704}
705
707 return sessionKey.GetPubKey();
708}
709
712
713 Delegation delegation;
714 if (peerData) {
715 if (!canShareLocalProof()) {
716 if (!delayedAvahelloNodeIds.emplace(pfrom->GetId()).second) {
717 // Nothing to do
718 return false;
719 }
720 } else {
721 delegation = peerData->delegation;
722 }
723 }
724
725 HashWriter hasher{};
726 hasher << delegation.getId();
727 hasher << pfrom->GetLocalNonce();
728 hasher << pfrom->nRemoteHostNonce;
729 hasher << pfrom->GetLocalExtraEntropy();
730 hasher << pfrom->nRemoteExtraEntropy;
731
732 // Now let's sign!
734 if (!sessionKey.SignSchnorr(hasher.GetHash(), sig)) {
735 return false;
736 }
737
739 pfrom, CNetMsgMaker(pfrom->GetCommonVersion())
740 .Make(NetMsgType::AVAHELLO, Hello(delegation, sig)));
741
742 return delegation.getLimitedProofId() != uint256::ZERO;
743}
744
747 return sendHelloInternal(pfrom));
748}
749
752
753 auto it = delayedAvahelloNodeIds.begin();
754 while (it != delayedAvahelloNodeIds.end()) {
755 if (connman->ForNode(*it, [&](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(
757 return sendHelloInternal(pnode);
758 })) {
759 // Our proof has been announced to this node
760 it = delayedAvahelloNodeIds.erase(it);
761 } else {
762 ++it;
763 }
764 }
765}
766
768 return peerData ? peerData->proof : ProofRef();
769}
770
773
775 if (!peerData) {
776 return state;
777 }
778
779 if (peerData->proof) {
781
782 const ProofId &proofid = peerData->proof->getId();
783
784 if (peerManager->isInConflictingPool(proofid)) {
786 "conflicting-utxos");
787 return state;
788 }
789
790 if (peerManager->isInvalid(proofid)) {
791 // If proof is invalid but verifies valid, it's been rejected by
792 // avalanche
794 "avalanche-invalidated");
795 return state;
796 }
797 }
798
799 return WITH_LOCK(peerData->cs_proofState, return peerData->proofState);
800}
801
804 scheduler, [this]() { this->runEventLoop(); }, AVALANCHE_TIME_STEP);
805}
806
808 return eventLoop.stopEventLoop();
809}
810
813
815 // Before IBD is complete there is no way to make sure a proof is valid
816 // or not, e.g. it can be spent in a block we don't know yet. In order
817 // to increase confidence that our proof set is similar to other nodes
818 // on the network, the messages received during IBD are not accounted.
819 return;
820 }
821
823 if (peerManager->latchAvaproofsSent(nodeid)) {
825 }
826}
827
828/*
829 * Returns a bool indicating whether we have a usable Avalanche quorum enabling
830 * us to take decisions based on polls.
831 */
834
835 {
837 if (peerManager->getNodeCount() < 8) {
838 // There is no point polling if we know the vote cannot converge
839 return false;
840 }
841 }
842
843 /*
844 * The following parameters can naturally go temporarly below the threshold
845 * under normal circumstances, like during a proof replacement with a lower
846 * stake amount, or the discovery of a new proofs for which we don't have a
847 * node yet.
848 * In order to prevent our node from starting and stopping the polls
849 * spuriously on such event, the quorum establishement is latched. The only
850 * parameters that should not latched is the minimum node count, as this
851 * would cause the poll to be inconclusive anyway and should not happen
852 * under normal circumstances.
853 */
855 return true;
856 }
857
858 // Don't do Avalanche while node is IBD'ing
860 return false;
861 }
862
864 return false;
865 }
866
867 auto localProof = getLocalProof();
868
869 // Get the registered proof score and registered score we have nodes for
870 uint32_t totalPeersScore;
871 uint32_t connectedPeersScore;
872 {
874 totalPeersScore = peerManager->getTotalPeersScore();
875 connectedPeersScore = peerManager->getConnectedPeersScore();
876
877 // Consider that we are always connected to our proof, even if we are
878 // the single node using that proof.
879 if (localProof &&
880 peerManager->forPeer(localProof->getId(), [](const Peer &peer) {
881 return peer.node_count == 0;
882 })) {
883 connectedPeersScore += localProof->getScore();
884 }
885 }
886
887 // Ensure enough is being staked overall
888 if (totalPeersScore < minQuorumScore) {
889 return false;
890 }
891
892 // Ensure we have connected score for enough of the overall score
893 uint32_t minConnectedScore =
894 std::round(double(totalPeersScore) * minQuorumConnectedScoreRatio);
895 if (connectedPeersScore < minConnectedScore) {
896 return false;
897 }
898
899 quorumIsEstablished = true;
900
901 // Attempt to compute the staking rewards winner now so we don't have to
902 // wait for a block if we already have all the prerequisites.
903 const CBlockIndex *pprev = WITH_LOCK(cs_main, return chainman.ActiveTip());
904 bool computedRewards = false;
905 if (pprev && IsStakingRewardsActivated(chainman.GetConsensus(), pprev)) {
906 computedRewards = computeStakingReward(pprev);
907 }
908 if (pprev && isStakingPreconsensusActivated(pprev) && !computedRewards) {
909 // It's possible to have quorum shortly after startup if peers were
910 // loaded from disk, but staking rewards may not be ready yet. In this
911 // case, we can still promote and poll for contenders.
913 }
914
915 return true;
916}
917
919 // The flag is latched
921 return true;
922 }
923
924 // Don't share our proof if we don't have any inbound connection.
925 // This is a best effort measure to prevent advertising a proof if we have
926 // limited network connectivity.
928
930}
931
933 if (!pindex) {
934 return false;
935 }
936
937 // If the quorum is not established there is no point picking a winner that
938 // will be rejected.
939 if (!isQuorumEstablished()) {
940 return false;
941 }
942
943 {
945 if (stakingRewards.count(pindex->GetBlockHash()) > 0) {
946 return true;
947 }
948 }
949
950 StakingReward _stakingRewards;
951 _stakingRewards.blockheight = pindex->nHeight;
952
953 bool rewardsInserted = false;
954 if (WITH_LOCK(cs_peerManager, return peerManager->selectStakingRewardWinner(
955 pindex, _stakingRewards.winners))) {
956 {
958 rewardsInserted =
959 stakingRewards
960 .emplace(pindex->GetBlockHash(), std::move(_stakingRewards))
961 .second;
962 }
963
964 if (isStakingPreconsensusActivated(pindex)) {
966 }
967 }
968
969 return rewardsInserted;
970}
971
974 return stakingRewards.erase(prevBlockHash) > 0;
975}
976
977void Processor::cleanupStakingRewards(const int minHeight) {
978 // Avoid cs_main => cs_peerManager reverse order locking
982
983 {
985 // std::erase_if is only defined since C++20
986 for (auto it = stakingRewards.begin(); it != stakingRewards.end();) {
987 if (it->second.blockheight < minHeight) {
988 it = stakingRewards.erase(it);
989 } else {
990 ++it;
991 }
992 }
993 }
994
996 return peerManager->cleanupStakeContenders(minHeight));
997}
998
1000 const BlockHash &prevBlockHash,
1001 std::vector<std::pair<ProofId, CScript>> &winners) const {
1003 auto it = stakingRewards.find(prevBlockHash);
1004 if (it == stakingRewards.end()) {
1005 return false;
1006 }
1007
1008 winners = it->second.winners;
1009 return true;
1010}
1011
1013 std::vector<CScript> &payouts) const {
1014 std::vector<std::pair<ProofId, CScript>> winners;
1015 if (!getStakingRewardWinners(prevBlockHash, winners)) {
1016 return false;
1017 }
1018
1019 payouts.clear();
1020 payouts.reserve(winners.size());
1021 for (auto &winner : winners) {
1022 payouts.push_back(std::move(winner.second));
1023 }
1024
1025 return true;
1026}
1027
1029 const std::vector<CScript> &payouts) {
1030 assert(pprev);
1031
1032 StakingReward stakingReward;
1033 stakingReward.blockheight = pprev->nHeight;
1034
1035 stakingReward.winners.reserve(payouts.size());
1036 for (const CScript &payout : payouts) {
1037 stakingReward.winners.push_back({ProofId(), payout});
1038 }
1039
1040 if (isStakingPreconsensusActivated(pprev)) {
1042 peerManager->setStakeContenderWinners(pprev, payouts);
1043 }
1044
1046 return stakingRewards.insert_or_assign(pprev->GetBlockHash(), stakingReward)
1047 .second;
1048}
1049
1051 const CBlockIndex *pprev,
1052 const std::vector<std::pair<ProofId, CScript>> &winners) {
1053 assert(pprev);
1054
1055 StakingReward stakingReward;
1056 stakingReward.blockheight = pprev->nHeight;
1057 stakingReward.winners = winners;
1058
1060 return stakingRewards.insert_or_assign(pprev->GetBlockHash(), stakingReward)
1061 .second;
1062}
1063
1064void Processor::FinalizeNode(const ::Config &config, const CNode &node) {
1066
1067 const NodeId nodeid = node.GetId();
1068 WITH_LOCK(cs_peerManager, peerManager->removeNode(nodeid));
1069 WITH_LOCK(cs_delayedAvahelloNodeIds, delayedAvahelloNodeIds.erase(nodeid));
1070}
1071
1073 const StakeContenderId &contenderId) const {
1076
1077 BlockHash prevblockhash;
1078 int status =
1079 WITH_LOCK(cs_peerManager, return peerManager->getStakeContenderStatus(
1080 contenderId, prevblockhash));
1081
1082 if (status != -1) {
1083 std::vector<std::pair<ProofId, CScript>> winners;
1084 getStakingRewardWinners(prevblockhash, winners);
1085 if (winners.size() == 0) {
1086 // If we have not selected a local staking rewards winner yet,
1087 // indicate this contender is pending to avoid convergence issues.
1088 return -2;
1089 }
1090 }
1091
1092 return status;
1093}
1094
1097 peerManager->acceptStakeContender(contenderId);
1098}
1099
1102
1103 BlockHash prevblockhash;
1104 std::vector<std::pair<ProofId, CScript>> winners;
1105 {
1107 peerManager->finalizeStakeContender(contenderId, prevblockhash,
1108 winners);
1109 }
1110
1111 // Set staking rewards to include newly finalized contender
1112 if (winners.size() > 0) {
1113 const CBlockIndex *block = WITH_LOCK(
1114 cs_main,
1115 return chainman.m_blockman.LookupBlockIndex(prevblockhash));
1116 if (block) {
1117 setStakingRewardWinners(block, winners);
1118 }
1119 }
1120}
1121
1124 peerManager->rejectStakeContender(contenderId);
1125}
1126
1128 assert(pprev);
1129
1130 if (!isQuorumEstablished()) {
1131 // Avoid growing the contender cache before it's possible to clean it up
1132 // (by finalizing blocks).
1133 return;
1134 }
1135
1136 {
1138 peerManager->promoteStakeContendersToBlock(pprev);
1139 }
1140
1141 // If staking rewards have not been computed yet, we will try again when
1142 // they have been.
1143 std::vector<StakeContenderId> pollableContenders;
1144 if (setContenderStatusForLocalWinners(pprev, pollableContenders)) {
1145 for (const StakeContenderId &contender : pollableContenders) {
1146 addToReconcile(contender);
1147 }
1148 }
1149}
1150
1152 const CBlockIndex *pindex,
1153 std::vector<StakeContenderId> &pollableContenders) {
1154 const BlockHash prevblockhash = pindex->GetBlockHash();
1155 std::vector<std::pair<ProofId, CScript>> winners;
1156 getStakingRewardWinners(prevblockhash, winners);
1157
1159 return peerManager->setContenderStatusForLocalWinners(
1160 pindex, winners, AVALANCHE_CONTENDER_MAX_POLLABLE, pollableContenders);
1161}
1162
1164 const bool registerLocalProof = canShareLocalProof();
1165 auto registerProofs = [&]() {
1167
1168 auto registeredProofs = peerManager->updatedBlockTip();
1169
1170 ProofRegistrationState localProofState;
1171 if (peerData && peerData->proof && registerLocalProof) {
1172 if (peerManager->registerProof(peerData->proof, localProofState)) {
1173 registeredProofs.insert(peerData->proof);
1174 }
1175
1176 if (localProofState.GetResult() ==
1178 // If our proof already exists, that's fine but we don't want to
1179 // erase the state with a duplicated proof status, so let's
1180 // retrieve the proper state. It also means we are able to
1181 // update the status should the proof move from one pool to the
1182 // other.
1183 const ProofId &localProofId = peerData->proof->getId();
1184 if (peerManager->isImmature(localProofId)) {
1186 "immature-proof");
1187 }
1188 if (peerManager->isInConflictingPool(localProofId)) {
1189 localProofState.Invalid(
1191 "conflicting-utxos");
1192 }
1193 if (peerManager->isBoundToPeer(localProofId)) {
1194 localProofState = ProofRegistrationState();
1195 }
1196 }
1197
1198 WITH_LOCK(peerData->cs_proofState,
1199 peerData->proofState = std::move(localProofState));
1200 }
1201
1202 return registeredProofs;
1203 };
1204
1205 auto registeredProofs = registerProofs();
1206 for (const auto &proof : registeredProofs) {
1207 reconcileOrFinalize(proof);
1208 }
1209
1210 const CBlockIndex *activeTip =
1212 if (activeTip && isStakingPreconsensusActivated(activeTip)) {
1214 }
1215}
1216
1219 WITH_LOCK(cs_main, return chainman.ActiveTip()))) {
1220 addToReconcile(tx);
1221 }
1222}
1223
1225 // Don't poll if quorum hasn't been established yet
1226 if (!isQuorumEstablished()) {
1227 return;
1228 }
1229
1230 // First things first, check if we have requests that timed out and clear
1231 // them.
1233
1234 // Make sure there is at least one suitable node to query before gathering
1235 // invs.
1236 NodeId nodeid = WITH_LOCK(cs_peerManager, return peerManager->selectNode());
1237 if (nodeid == NO_NODE) {
1238 return;
1239 }
1240 std::vector<CInv> invs = getInvsForNextPoll();
1241 if (invs.empty()) {
1242 return;
1243 }
1244
1246
1247 do {
1253 bool hasSent = connman->ForNode(
1254 nodeid, [this, &invs](CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(
1256 uint64_t current_round = round++;
1257
1258 {
1259 // Compute the time at which this requests times out.
1260 auto timeout = Now<SteadyMilliseconds>() +
1262 // Register the query.
1263 queries.getWriteView()->insert(
1264 {pnode->GetId(), current_round, timeout, invs});
1265 // Set the timeout.
1266 peerManager->updateNextRequestTime(pnode->GetId(), timeout);
1267 }
1268
1269 pnode->invsPolled(invs.size());
1270
1271 // Send the query to the node.
1273 pnode, CNetMsgMaker(pnode->GetCommonVersion())
1275 Poll(current_round, std::move(invs))));
1276 return true;
1277 });
1278
1279 // Success!
1280 if (hasSent) {
1281 return;
1282 }
1283
1284 // This node is obsolete, delete it.
1285 peerManager->removeNode(nodeid);
1286
1287 // Get next suitable node to try again
1288 nodeid = peerManager->selectNode();
1289 } while (nodeid != NO_NODE);
1290}
1291
1293 auto now = Now<SteadyMilliseconds>();
1294 std::map<CInv, uint8_t> timedout_items{};
1295
1296 {
1297 // Clear expired requests.
1298 auto w = queries.getWriteView();
1299 auto it = w->get<query_timeout>().begin();
1300 while (it != w->get<query_timeout>().end() && it->timeout < now) {
1301 for (const auto &i : it->invs) {
1302 timedout_items[i]++;
1303 }
1304
1305 w->get<query_timeout>().erase(it++);
1306 }
1307 }
1308
1309 if (timedout_items.empty()) {
1310 return;
1311 }
1312
1313 // In flight request accounting.
1314 auto voteRecordsWriteView = voteRecords.getWriteView();
1315 for (const auto &p : timedout_items) {
1316 auto item = getVoteItemFromInv(p.first);
1317
1318 if (isNull(item)) {
1319 continue;
1320 }
1321
1322 auto it = voteRecordsWriteView->find(item);
1323 if (it == voteRecordsWriteView.end()) {
1324 continue;
1325 }
1326
1327 it->second.clearInflightRequest(p.second);
1328 }
1329}
1330
1331std::vector<CInv> Processor::getInvsForNextPoll(bool forPoll) {
1332 std::vector<CInv> invs;
1333
1334 {
1335 // First remove all items that are not worth polling.
1336 auto w = voteRecords.getWriteView();
1337 for (auto it = w->begin(); it != w->end();) {
1338 if (!isWorthPolling(it->first)) {
1339 it = w->erase(it);
1340 } else {
1341 ++it;
1342 }
1343 }
1344 }
1345
1346 auto buildInvFromVoteItem = variant::overloaded{
1347 [](const ProofRef &proof) {
1348 return CInv(MSG_AVA_PROOF, proof->getId());
1349 },
1350 [](const CBlockIndex *pindex) {
1351 return CInv(MSG_BLOCK, pindex->GetBlockHash());
1352 },
1353 [](const StakeContenderId &contenderId) {
1354 return CInv(MSG_AVA_STAKE_CONTENDER, contenderId);
1355 },
1356 [](const CTransactionRef &tx) { return CInv(MSG_TX, tx->GetHash()); },
1357 };
1358
1359 auto r = voteRecords.getReadView();
1360 for (const auto &[item, voteRecord] : r) {
1361 if (invs.size() >= AVALANCHE_MAX_ELEMENT_POLL) {
1362 // Make sure we do not produce more invs than specified by the
1363 // protocol.
1364 return invs;
1365 }
1366
1367 const bool shouldPoll =
1368 forPoll ? voteRecord.registerPoll() : voteRecord.shouldPoll();
1369
1370 if (!shouldPoll) {
1371 continue;
1372 }
1373
1374 invs.emplace_back(std::visit(buildInvFromVoteItem, item));
1375 }
1376
1377 return invs;
1378}
1379
1381 if (inv.IsMsgBlk()) {
1383 BlockHash(inv.hash)));
1384 }
1385
1386 if (inv.IsMsgProof()) {
1388 return peerManager->getProof(ProofId(inv.hash)));
1389 }
1390
1391 if (inv.IsMsgStakeContender()) {
1392 return StakeContenderId(inv.hash);
1393 }
1394
1395 if (mempool && inv.IsMsgTx()) {
1396 LOCK(mempool->cs);
1397 if (CTransactionRef tx = mempool->get(TxId(inv.hash))) {
1398 return tx;
1399 }
1401 [&inv](const TxConflicting &conflicting) {
1402 return conflicting.GetTx(TxId(inv.hash));
1403 })) {
1404 return tx;
1405 }
1406 }
1407
1408 return {nullptr};
1409}
1410
1413
1414 LOCK(cs_main);
1415
1416 if (pindex->nStatus.isInvalid()) {
1417 // No point polling invalid blocks.
1418 return false;
1419 }
1420
1422 return processor.finalizationTip &&
1423 processor.finalizationTip->GetAncestor(
1424 pindex->nHeight) == pindex)) {
1425 // There is no point polling blocks that are ancestor of a block that
1426 // has been accepted by the network.
1427 return false;
1428 }
1429
1431 return processor.invalidatedBlocks.contains(
1432 pindex->GetBlockHash()))) {
1433 // Blocks invalidated by Avalanche should not be polled twice.
1434 return false;
1435 }
1436
1437 return true;
1438}
1439
1441 // Avoid lock order issues cs_main -> cs_peerManager
1443 AssertLockNotHeld(processor.cs_peerManager);
1444
1445 const ProofId &proofid = proof->getId();
1446
1447 LOCK(processor.cs_peerManager);
1448
1449 // No point polling immature or discarded proofs
1450 return processor.peerManager->isBoundToPeer(proofid) ||
1451 processor.peerManager->isInConflictingPool(proofid);
1452}
1453
1455 const StakeContenderId &contenderId) const {
1456 AssertLockNotHeld(processor.cs_peerManager);
1457 AssertLockNotHeld(processor.cs_stakingRewards);
1458
1459 // Only worth polling for contenders that we know about
1460 return processor.getStakeContenderStatus(contenderId) != -1;
1461}
1462
1464 if (!processor.mempool) {
1465 return false;
1466 }
1467
1468 AssertLockNotHeld(processor.mempool->cs);
1469 return WITH_LOCK(processor.mempool->cs,
1470 return processor.mempool->isWorthPolling(tx));
1471}
1472
1474 return !isRecentlyFinalized(GetVoteItemId(item)) &&
1475 std::visit(IsWorthPolling(*this), item);
1476}
1477
1479 const CBlockIndex *pindex) const {
1481
1482 return WITH_LOCK(cs_main,
1483 return processor.chainman.ActiveChain().Contains(pindex));
1484}
1485
1487 AssertLockNotHeld(processor.cs_peerManager);
1488
1489 return WITH_LOCK(
1490 processor.cs_peerManager,
1491 return processor.peerManager->isBoundToPeer(proof->getId()));
1492}
1493
1495 const StakeContenderId &contenderId) const {
1496 AssertLockNotHeld(processor.cs_peerManager);
1497 AssertLockNotHeld(processor.cs_stakingRewards);
1498
1499 return processor.getStakeContenderStatus(contenderId) == 0;
1500}
1501
1503 const CTransactionRef &tx) const {
1504 if (!processor.mempool) {
1505 return false;
1506 }
1507
1508 AssertLockNotHeld(processor.mempool->cs);
1509
1510 return WITH_LOCK(processor.mempool->cs,
1511 return processor.mempool->exists(tx->GetId()));
1512}
1513
1515 return m_preConsensus;
1516}
1517
1519 return m_stakingPreConsensus;
1520}
1521
1522} // namespace avalanche
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
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:824
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3085
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2758
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3039
Inv(ventory) message data.
Definition: protocol.h:582
bool IsMsgBlk() const
Definition: protocol.h:613
bool IsMsgTx() const
Definition: protocol.h:601
bool IsMsgStakeContender() const
Definition: protocol.h:609
uint256 hash
Definition: protocol.h:585
bool IsMsgProof() const
Definition: protocol.h:605
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
CSerializedNetMsg Make(int nFlags, std::string msg_type, Args &&...args) const
Information about a peer.
Definition: net.h:395
NodeId GetId() const
Definition: net.h:687
uint64_t GetLocalNonce() const
Definition: net.h:689
int GetCommonVersion() const
Definition: net.h:713
uint64_t nRemoteHostNonce
Definition: net.h:441
uint64_t nRemoteExtraEntropy
Definition: net.h:443
uint64_t GetLocalExtraEntropy() const
Definition: net.h:690
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:2937
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:677
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:1186
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:1444
const Consensus::Params & GetConsensus() const
Definition: validation.h:1282
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1327
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:100
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:1380
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:710
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:1331
bool isStakingPreconsensusActivated(const CBlockIndex *pprev) const
Definition: processor.cpp:1518
RWCollection< QuerySet > queries
Definition: processor.h:209
ProofRegistrationState getLocalProofRegistrationState() const EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:771
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:1151
void transactionAddedToMempool(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:1217
bool sendHello(CNode *pfrom) EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Send a avahello message.
Definition: processor.cpp:745
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:802
bool isQuorumEstablished() LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:832
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:1028
void runEventLoop() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1224
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:1163
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:1064
bool getStakingRewardWinners(const BlockHash &prevBlockHash, std::vector< std::pair< ProofId, CScript > > &winners) const EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
Definition: processor.cpp:999
std::atomic< bool > m_canShareLocalProof
Definition: processor.h:225
void cleanupStakingRewards(const int minHeight) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards
Definition: processor.cpp:977
bool isAccepted(const AnyVoteItem &item) const
Definition: processor.cpp:465
ProofRef getLocalProof() const
Definition: processor.cpp:767
void acceptStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1095
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:1072
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:1127
void sendDelayedAvahello() EXCLUSIVE_LOCKS_REQUIRED(!cs_delayedAvahelloNodeIds)
Definition: processor.cpp:750
void finalizeStakeContender(const StakeContenderId &contenderId) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1100
std::unique_ptr< PeerData > peerData
Definition: processor.h:213
bool eraseStakingRewardWinner(const BlockHash &prevBlockHash) EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
Definition: processor.cpp:972
bool isPreconsensusActivated(const CBlockIndex *pprev) const
Definition: processor.cpp:1514
CConnman * connman
Definition: processor.h:161
bool isWorthPolling(const AnyVoteItem &item) const EXCLUSIVE_LOCKS_REQUIRED(!cs_finalizedItems)
Definition: processor.cpp:1473
CPubKey getSessionPubKey() const
Definition: processor.cpp:706
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:932
bool registerVotes(NodeId nodeid, const Response &response, std::vector< VoteItemUpdate > &updates, bool &disconnect, std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:552
void clearTimedoutRequests() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:1292
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:1122
void avaproofsSent(NodeId nodeid) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager)
Definition: processor.cpp:811
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
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:566
@ MSG_AVA_STAKE_CONTENDER
Definition: protocol.h:574
@ MSG_AVA_PROOF
Definition: protocol.h:573
@ MSG_BLOCK
Definition: protocol.h:567
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
Definition: serialize.h:215
#define READWRITE(...)
Definition: serialize.h:168
bool IsStakingRewardsActivated(const Consensus::Params &params, const CBlockIndex *pprev)
Definition: amount.h:19
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:1478
bool operator()(const CBlockIndex *pindex) const LOCKS_EXCLUDED(cs_main)
Definition: processor.cpp:1411
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