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