Bitcoin ABC 0.33.8
P2P Digital Currency
processor_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2018-2020 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
7#include <arith_uint256.h>
14#include <chain.h>
15#include <config.h>
16#include <core_io.h>
17#include <key_io.h>
18#include <net_processing.h> // For ::PeerManager
19#include <reverse_iterator.h>
20#include <scheduler.h>
21#include <util/time.h>
22#include <util/translation.h> // For bilingual_str
23#include <validation.h>
24
25#include <avalanche/test/util.h>
26#include <test/util/net.h>
27#include <test/util/setup_common.h>
28
29#include <boost/mpl/list.hpp>
30#include <boost/mpl/size.hpp>
31#include <boost/test/unit_test.hpp>
32
33#include <functional>
34#include <limits>
35#include <type_traits>
36#include <vector>
37
38using namespace avalanche;
39using util::ToString;
40
41namespace avalanche {
42namespace {
43 struct AvalancheTest {
44 static void runEventLoop(avalanche::Processor &p) { p.runEventLoop(); }
45
46 static std::vector<CInv> getInvsForNextPoll(Processor &p) {
47 auto r = p.voteRecords.getReadView();
49 false);
50 }
51
52 static NodeId getSuitableNodeToQuery(Processor &p) {
54 return p.peerManager->selectNode());
55 }
56
57 static uint64_t getRound(const Processor &p) { return p.round; }
58
59 static uint32_t getMinQuorumScore(const Processor &p) {
60 return p.minQuorumScore;
61 }
62
63 static double getMinQuorumConnectedScoreRatio(const Processor &p) {
65 }
66
67 static void clearavaproofsNodeCounter(Processor &p) {
69 }
70
71 static void addVoteRecord(Processor &p, AnyVoteItem &item,
72 VoteRecord &voteRecord) {
73 p.voteRecords.getWriteView()->insert(
74 std::make_pair(item, voteRecord));
75 }
76
77 static void removeVoteRecord(Processor &p, AnyVoteItem &item) {
78 p.voteRecords.getWriteView()->erase(item);
79 }
80
81 static void setFinalizationTip(Processor &p,
82 const CBlockIndex *pindex) {
84 p.finalizationTip = pindex;
85 }
86
87 static void setLocalProofShareable(Processor &p, bool shareable) {
88 p.m_canShareLocalProof = shareable;
89 }
90
91 static void updatedBlockTip(Processor &p) { p.updatedBlockTip(); }
92
93 static void addProofToRecentfinalized(Processor &p,
94 const ProofId &proofid) {
96 return p.finalizedItems.insert(proofid));
97 }
98
99 static bool setContenderStatusForLocalWinners(
100 Processor &p, const CBlockIndex *pindex,
101 std::vector<StakeContenderId> &pollableContenders) {
102 return p.setContenderStatusForLocalWinners(pindex,
103 pollableContenders);
104 }
105
106 static void setStakingPreconsensus(Processor &p, bool enabled) {
107 p.m_stakingPreConsensus = enabled;
108 }
109
110 static void clearInvsNotWorthPolling(Processor &p) {
112 }
113 };
114} // namespace
115
116struct TestVoteRecord : public VoteRecord {
117 explicit TestVoteRecord(uint16_t conf) : VoteRecord(true) {
118 confidence |= conf << 1;
119 }
120};
121} // namespace avalanche
122
123namespace {
124CService ip(uint32_t i) {
125 struct in_addr s;
126 s.s_addr = i;
127 return CService(CNetAddr(s), Params().GetDefaultPort());
128}
129
130struct AvalancheProcessorTestingSetup : public AvalancheTestChain100Setup {
131 AvalancheProcessorTestingSetup() : AvalancheTestChain100Setup() {
132 AvalancheTest::setStakingPreconsensus(*m_node.avalanche, false);
133 }
134
135 CNode *ConnectNode(ServiceFlags nServices) {
136 static NodeId id = 0;
137
138 CAddress addr(ip(FastRandomContext().rand<uint32_t>()), NODE_NONE);
139 auto node =
140 new CNode(id++, /*sock=*/nullptr, addr,
141 /* nKeyedNetGroupIn */ 0,
142 /* nLocalHostNonceIn */ 0,
143 /* nLocalExtraEntropyIn */ 0, CAddress(),
144 /* pszDest */ "", ConnectionType::OUTBOUND_FULL_RELAY,
145 /* inbound_onion */ false);
146 node->SetCommonVersion(PROTOCOL_VERSION);
147 node->m_has_all_wanted_services =
149 m_node.peerman->InitializeNode(config, *node, NODE_NETWORK);
150 node->nVersion = 1;
151 node->fSuccessfullyConnected = true;
152
153 m_connman->AddTestNode(*node);
154 return node;
155 }
156
157 ProofRef GetProof(CScript payoutScript = UNSPENDABLE_ECREG_PAYOUT_SCRIPT) {
158 const CKey key = CKey::MakeCompressedKey();
159 const COutPoint outpoint{TxId(GetRandHash()), 0};
161 const Amount amount = PROOF_DUST_THRESHOLD;
162 const uint32_t height = 100;
163
164 LOCK(cs_main);
165 CCoinsViewCache &coins =
166 Assert(m_node.chainman)->ActiveChainstate().CoinsTip();
167 coins.AddCoin(outpoint, Coin(CTxOut(amount, script), height, false),
168 false);
169
170 ProofBuilder pb(0, 0, masterpriv, payoutScript);
171 BOOST_CHECK(pb.addUTXO(outpoint, amount, height, false, key));
172 return pb.build();
173 }
174
175 bool addNode(NodeId nodeid, const ProofId &proofid) {
176 return m_node.avalanche->withPeerManager(
177 [&](avalanche::PeerManager &pm) {
178 return pm.addNode(nodeid, proofid,
180 });
181 }
182
183 bool addNode(NodeId nodeid) {
184 auto proof = GetProof();
185 return m_node.avalanche->withPeerManager(
186 [&](avalanche::PeerManager &pm) {
187 return pm.registerProof(proof) &&
188 pm.addNode(nodeid, proof->getId(),
190 });
191 }
192
193 std::array<CNode *, 8> ConnectNodes() {
194 auto proof = GetProof();
196 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
197 return pm.registerProof(proof);
198 }));
199 const ProofId &proofid = proof->getId();
200
201 std::array<CNode *, 8> nodes;
202 for (CNode *&n : nodes) {
203 n = ConnectNode(NODE_AVALANCHE);
204 BOOST_CHECK(addNode(n->GetId(), proofid));
205 }
206
207 return nodes;
208 }
209
210 void runEventLoop() { AvalancheTest::runEventLoop(*m_node.avalanche); }
211
212 NodeId getSuitableNodeToQuery() {
213 return AvalancheTest::getSuitableNodeToQuery(*m_node.avalanche);
214 }
215
216 std::vector<CInv> getInvsForNextPoll() {
217 return AvalancheTest::getInvsForNextPoll(*m_node.avalanche);
218 }
219
220 uint64_t getRound() const {
221 return AvalancheTest::getRound(*m_node.avalanche);
222 }
223
224 bool registerVotes(NodeId nodeid, const avalanche::Response &response,
225 std::vector<avalanche::VoteItemUpdate> &updates,
226 std::string &error) {
227 bool disconnect;
228 return m_node.avalanche->registerVotes(nodeid, response, updates,
229 disconnect, error);
230 }
231
232 bool registerVotes(NodeId nodeid, const avalanche::Response &response,
233 std::vector<avalanche::VoteItemUpdate> &updates) {
234 bool disconnect;
235 std::string error;
236 return m_node.avalanche->registerVotes(nodeid, response, updates,
237 disconnect, error);
238 }
239
240 bool addToReconcile(const AnyVoteItem &item) {
241 return m_node.avalanche->addToReconcile(item);
242 }
243
244 void clearInvsNotWorthPolling() {
245 AvalancheTest::clearInvsNotWorthPolling(*m_node.avalanche);
246 }
247};
248
249struct BlockProvider {
250 AvalancheProcessorTestingSetup *fixture;
251 uint32_t invType{MSG_BLOCK};
252
253 BlockProvider(AvalancheProcessorTestingSetup *_fixture)
254 : fixture(_fixture) {}
255
256 CBlockIndex *buildVoteItem() const {
257 CBlock block = fixture->CreateAndProcessBlock({}, CScript());
258 const BlockHash blockHash = block.GetHash();
259
260 LOCK(cs_main);
261 return Assert(fixture->m_node.chainman)
262 ->m_blockman.LookupBlockIndex(blockHash);
263 }
264
265 uint256 getVoteItemId(const CBlockIndex *pindex) const {
266 return pindex->GetBlockHash();
267 }
268
269 std::vector<Vote> buildVotesForItems(uint32_t error,
270 std::vector<CBlockIndex *> &&items) {
271 size_t numItems = items.size();
272
273 std::vector<Vote> votes;
274 votes.reserve(numItems);
275
276 // Votes are sorted by most work first
277 std::sort(items.begin(), items.end(), CBlockIndexWorkComparator());
278 for (auto &item : reverse_iterate(items)) {
279 votes.emplace_back(error, item->GetBlockHash());
280 }
281
282 return votes;
283 }
284
285 void invalidateItem(CBlockIndex *pindex) {
287 pindex->nStatus = pindex->nStatus.withFailed();
288 }
289
290 const CBlockIndex *fromAnyVoteItem(const AnyVoteItem &item) {
291 return std::get<const CBlockIndex *>(item);
292 }
293};
294
295struct ProofProvider {
296 AvalancheProcessorTestingSetup *fixture;
297 uint32_t invType{MSG_AVA_PROOF};
298
299 ProofProvider(AvalancheProcessorTestingSetup *_fixture)
300 : fixture(_fixture) {}
301
302 ProofRef buildVoteItem() const {
303 ProofRef proof = fixture->GetProof();
304 fixture->m_node.avalanche->withPeerManager(
305 [&](avalanche::PeerManager &pm) {
306 BOOST_CHECK(pm.registerProof(proof));
307 });
308 return proof;
309 }
310
311 uint256 getVoteItemId(const ProofRef &proof) const {
312 return proof->getId();
313 }
314
315 std::vector<Vote> buildVotesForItems(uint32_t error,
316 std::vector<ProofRef> &&items) {
317 size_t numItems = items.size();
318
319 std::vector<Vote> votes;
320 votes.reserve(numItems);
321
322 // Votes are sorted by high score first
323 std::sort(items.begin(), items.end(), ProofComparatorByScore());
324 for (auto &item : items) {
325 votes.emplace_back(error, item->getId());
326 }
327
328 return votes;
329 }
330
331 void invalidateItem(const ProofRef &proof) {
332 fixture->m_node.avalanche->withPeerManager(
333 [&](avalanche::PeerManager &pm) {
334 pm.rejectProof(
335 proof->getId(),
337 });
338 }
339
340 ProofRef fromAnyVoteItem(const AnyVoteItem &item) {
341 return std::get<const ProofRef>(item);
342 }
343};
344
345struct StakeContenderProvider {
346 AvalancheProcessorTestingSetup *fixture;
347
348 std::vector<avalanche::VoteItemUpdate> updates;
349 uint32_t invType{MSG_AVA_STAKE_CONTENDER};
350
351 StakeContenderProvider(AvalancheProcessorTestingSetup *_fixture)
352 : fixture(_fixture) {}
353
354 StakeContenderId buildVoteItem() const {
355 ChainstateManager &chainman = *Assert(fixture->m_node.chainman);
356 const CBlockIndex *chaintip =
357 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
358
359 std::vector<CScript> winners;
360 if (!fixture->m_node.avalanche->getStakingRewardWinners(
361 chaintip->GetBlockHash(), winners)) {
362 // If staking rewards are not ready, just set it to some winner.
363 // This ensures getStakeContenderStatus will not return pending.
364 const ProofRef proofWinner = fixture->GetProof();
365 std::vector<CScript> payouts{proofWinner->getPayoutScript()};
366 fixture->m_node.avalanche->setStakingRewardWinners(chaintip,
367 payouts);
368 }
369
370 // Create a new contender
371 const ProofRef proof = fixture->GetProof();
372 const StakeContenderId contenderId(chaintip->GetBlockHash(),
373 proof->getId());
374
375 fixture->m_node.avalanche->withPeerManager(
376 [&](avalanche::PeerManager &pm) { pm.addStakeContender(proof); });
377
378 // Many of these tests assume that building a new item means it is
379 // accepted by default. Contenders are different in that they are
380 // only accepted if they are a stake winner. We stick the the
381 // convention for these tests and accept the contender.
382 fixture->m_node.avalanche->acceptStakeContender(contenderId);
383
384 BOOST_CHECK(fixture->m_node.avalanche->getStakeContenderStatus(
385 contenderId) == 0);
386 return contenderId;
387 }
388
389 uint256 getVoteItemId(const StakeContenderId &contenderId) const {
390 return contenderId;
391 }
392
393 std::vector<Vote>
394 buildVotesForItems(uint32_t error, std::vector<StakeContenderId> &&items) {
395 size_t numItems = items.size();
396
397 std::vector<Vote> votes;
398 votes.reserve(numItems);
399
400 // Contenders are sorted by id
401 std::sort(items.begin(), items.end(),
402 [](const StakeContenderId &lhs, const StakeContenderId &rhs) {
403 return lhs < rhs;
404 });
405 for (auto &item : items) {
406 votes.emplace_back(error, item);
407 }
408
409 return votes;
410 }
411
412 void invalidateItem(const StakeContenderId &contenderId) {
413 fixture->m_node.avalanche->rejectStakeContender(contenderId);
414
415 // Warning: This is a special case for stake contenders because
416 // invalidation does not cause isWorthPolling to return false. This is
417 // because invalidation of contenders is only intended to halt polling.
418 // They will continue to be tracked in the cache, being promoted and
419 // polled again (respective to the proof) for each block.
420 AnyVoteItem contenderVoteItem(contenderId);
421 AvalancheTest::removeVoteRecord(*(fixture->m_node.avalanche),
422 contenderVoteItem);
423 }
424
425 StakeContenderId fromAnyVoteItem(const AnyVoteItem &item) {
426 return std::get<const StakeContenderId>(item);
427 }
428};
429
430struct TxProvider {
431 AvalancheProcessorTestingSetup *fixture;
432
433 std::vector<avalanche::VoteItemUpdate> updates;
434 uint32_t invType{MSG_TX};
435
436 TxProvider(AvalancheProcessorTestingSetup *_fixture) : fixture(_fixture) {}
437
438 CTransactionRef buildVoteItem() const {
440 mtx.nVersion = 2;
441 mtx.vin.emplace_back(COutPoint{TxId(FastRandomContext().rand256()), 0});
442 mtx.vout.emplace_back(1 * COIN, CScript() << OP_TRUE);
443
444 CTransactionRef tx = MakeTransactionRef(std::move(mtx));
445
446 TestMemPoolEntryHelper mempoolEntryHelper;
447 auto entry = mempoolEntryHelper.Fee(1000 * SATOSHI).FromTx(tx);
448
449 CTxMemPool *mempool = Assert(fixture->m_node.mempool.get());
450 {
451 LOCK2(cs_main, mempool->cs);
452 mempool->addUnchecked(entry);
453 BOOST_CHECK(mempool->exists(tx->GetId()));
454 }
455
456 return tx;
457 }
458
459 uint256 getVoteItemId(const CTransactionRef &tx) const {
460 return tx->GetId();
461 }
462
463 std::vector<Vote> buildVotesForItems(uint32_t error,
464 std::vector<CTransactionRef> &&items) {
465 size_t numItems = items.size();
466
467 std::vector<Vote> votes;
468 votes.reserve(numItems);
469
470 // Transactions are sorted by TxId
471 std::sort(items.begin(), items.end(),
472 [](const CTransactionRef &lhs, const CTransactionRef &rhs) {
473 return lhs->GetId() < rhs->GetId();
474 });
475 for (auto &item : items) {
476 votes.emplace_back(error, item->GetId());
477 }
478
479 return votes;
480 }
481
482 void invalidateItem(const CTransactionRef &tx) {
483 BOOST_CHECK(tx != nullptr);
484 CTxMemPool *mempool = Assert(fixture->m_node.mempool.get());
485
486 LOCK(mempool->cs);
488 BOOST_CHECK(!mempool->exists(tx->GetId()));
489 }
490
491 CTransactionRef fromAnyVoteItem(const AnyVoteItem &item) {
492 return std::get<const CTransactionRef>(item);
493 }
494};
495
496} // namespace
497
498BOOST_FIXTURE_TEST_SUITE(processor_tests, AvalancheProcessorTestingSetup)
499
500// FIXME A std::tuple can be used instead of boost::mpl::list after boost 1.67
501using VoteItemProviders = boost::mpl::list<BlockProvider, ProofProvider,
502 StakeContenderProvider, TxProvider>;
504 boost::mpl::list<BlockProvider, ProofProvider, TxProvider>;
505using Uint256VoteItemProviders = boost::mpl::list<StakeContenderProvider>;
506static_assert(boost::mpl::size<VoteItemProviders>::value ==
507 boost::mpl::size<NullableVoteItemProviders>::value +
508 boost::mpl::size<Uint256VoteItemProviders>::value);
509
511 P provider(this);
512
513 std::set<VoteStatus> status{
514 VoteStatus::Invalid, VoteStatus::Rejected, VoteStatus::Accepted,
515 VoteStatus::Finalized, VoteStatus::Stale,
516 };
517
518 auto item = provider.buildVoteItem();
519
520 for (auto s : status) {
521 VoteItemUpdate itemUpdate(item, s);
522 // The use of BOOST_CHECK instead of BOOST_CHECK_EQUAL prevents from
523 // having to define operator<<() for each argument type.
524 BOOST_CHECK(provider.fromAnyVoteItem(itemUpdate.getVoteItem()) == item);
525 BOOST_CHECK(itemUpdate.getStatus() == s);
526 }
527}
528
529namespace {
530Response next(Response &r) {
531 auto copy = r;
532 r = {r.getRound() + 1, r.getCooldown(), r.GetVotes()};
533 return copy;
534}
535} // namespace
536
538 P provider(this);
539 ChainstateManager &chainman = *Assert(m_node.chainman);
540 const CBlockIndex *chaintip =
541 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
542
543 auto item = provider.buildVoteItem();
544 auto itemid = provider.getVoteItemId(item);
545
546 // Adding the item twice does nothing.
547 BOOST_CHECK(addToReconcile(item));
548 BOOST_CHECK(!addToReconcile(item));
549 BOOST_CHECK(m_node.avalanche->isPolled(item));
550 BOOST_CHECK(m_node.avalanche->isAccepted(item));
551
552 // Create nodes that supports avalanche so we can finalize the item.
553 auto avanodes = ConnectNodes();
554
555 int nextNodeIndex = 0;
556 std::vector<avalanche::VoteItemUpdate> updates;
557 auto registerNewVote = [&](const Response &resp) {
558 runEventLoop();
559 auto nodeid = avanodes[nextNodeIndex++ % avanodes.size()]->GetId();
560 std::string error;
561 bool vote_is_registered = registerVotes(nodeid, resp, updates, error);
562 BOOST_CHECK_MESSAGE(vote_is_registered,
563 "registerVotes failed with error: " << error);
564 };
565
566 // Finalize the item.
567 auto finalize = [&](const auto finalizeItemId) {
568 Response resp = {getRound(), 0, {Vote(0, finalizeItemId)}};
569 for (int i = 0; i < AVALANCHE_FINALIZATION_SCORE + 6; i++) {
570 registerNewVote(next(resp));
571 if (updates.size() > 0) {
572 break;
573 }
574 }
575 BOOST_CHECK_EQUAL(updates.size(), 1);
576 BOOST_CHECK(updates[0].getStatus() == VoteStatus::Finalized);
577 m_node.avalanche->setRecentlyFinalized(finalizeItemId);
578 };
579 finalize(itemid);
580
581 // The finalized item cannot be reconciled for a while.
582 BOOST_CHECK(!addToReconcile(item));
583
584 auto finalizeNewItem = [&]() {
585 auto anotherItem = provider.buildVoteItem();
586 AnyVoteItem anotherVoteItem = AnyVoteItem(anotherItem);
587 auto anotherItemId = provider.getVoteItemId(anotherItem);
588
590 AvalancheTest::addVoteRecord(*m_node.avalanche, anotherVoteItem,
591 voteRecord);
592 finalize(anotherItemId);
593 };
594
595 // The filter can have new items added up to its size and the item will
596 // still not reconcile.
597 for (uint32_t i = 0; i < AVALANCHE_FINALIZED_ITEMS_FILTER_NUM_ELEMENTS;
598 i++) {
599 finalizeNewItem();
600 BOOST_CHECK(!addToReconcile(item));
601 }
602
603 // But if we keep going it will eventually roll out of the filter and can
604 // be reconciled again.
605 for (uint32_t i = 0; i < AVALANCHE_FINALIZED_ITEMS_FILTER_NUM_ELEMENTS;
606 i++) {
607 finalizeNewItem();
608 }
609
610 // Roll back the finalization point so that reconciling the old block does
611 // not fail the finalization check. This is a no-op for other types.
612 AvalancheTest::setFinalizationTip(*m_node.avalanche, chaintip);
613
614 BOOST_CHECK(addToReconcile(item));
615}
616
618 P provider(this);
619
620 // Check that null case is handled on the public interface
621 BOOST_CHECK(!m_node.avalanche->isPolled(nullptr));
622 BOOST_CHECK(!m_node.avalanche->isAccepted(nullptr));
623 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(nullptr), -1);
624
625 auto item = decltype(provider.buildVoteItem())();
626 BOOST_CHECK(item == nullptr);
627 BOOST_CHECK(!addToReconcile(item));
628
629 // Check that adding item to vote on doesn't change the outcome. A
630 // comparator is used under the hood, and this is skipped if there are no
631 // vote records.
632 item = provider.buildVoteItem();
633 BOOST_CHECK(addToReconcile(item));
634
635 BOOST_CHECK(!m_node.avalanche->isPolled(nullptr));
636 BOOST_CHECK(!m_node.avalanche->isAccepted(nullptr));
637 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(nullptr), -1);
638}
639
641 P provider(this);
642
643 auto itemZero = decltype(provider.buildVoteItem())();
644
645 // Check that zero case is handled on the public interface
646 BOOST_CHECK(!m_node.avalanche->isPolled(itemZero));
647 BOOST_CHECK(!m_node.avalanche->isAccepted(itemZero));
648 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(itemZero), -1);
649
650 BOOST_CHECK(itemZero == uint256::ZERO);
651 BOOST_CHECK(!addToReconcile(itemZero));
652
653 // Check that adding item to vote on doesn't change the outcome. A
654 // comparator is used under the hood, and this is skipped if there are no
655 // vote records.
656 auto item = provider.buildVoteItem();
657 BOOST_CHECK(addToReconcile(item));
658
659 BOOST_CHECK(!m_node.avalanche->isPolled(itemZero));
660 BOOST_CHECK(!m_node.avalanche->isAccepted(itemZero));
661 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(itemZero), -1);
662}
663
665 P provider(this);
666 const uint32_t invType = provider.invType;
667
668 auto item = provider.buildVoteItem();
669 auto itemid = provider.getVoteItemId(item);
670
671 // Create nodes that supports avalanche.
672 auto avanodes = ConnectNodes();
673
674 // Querying for random item returns false.
675 BOOST_CHECK(!m_node.avalanche->isPolled(item));
676 BOOST_CHECK(!m_node.avalanche->isAccepted(item));
677
678 // Add a new item. Check it is added to the polls.
679 BOOST_CHECK(addToReconcile(item));
680 auto invs = getInvsForNextPoll();
681 BOOST_CHECK_EQUAL(invs.size(), 1);
682 BOOST_CHECK_EQUAL(invs[0].type, invType);
683 BOOST_CHECK(invs[0].hash == itemid);
684
685 BOOST_CHECK(m_node.avalanche->isPolled(item));
686 BOOST_CHECK(m_node.avalanche->isAccepted(item));
687
688 int nextNodeIndex = 0;
689 std::vector<avalanche::VoteItemUpdate> updates;
690 auto registerNewVote = [&](const Response &resp) {
691 runEventLoop();
692 auto nodeid = avanodes[nextNodeIndex++ % avanodes.size()]->GetId();
693 BOOST_CHECK(registerVotes(nodeid, resp, updates));
694 };
695
696 // Let's vote for this item a few times.
697 Response resp{0, 0, {Vote(0, itemid)}};
698 for (int i = 0; i < 6; i++) {
699 registerNewVote(next(resp));
700 BOOST_CHECK(m_node.avalanche->isAccepted(item));
701 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item), 0);
702 BOOST_CHECK_EQUAL(updates.size(), 0);
703 }
704
705 // A single neutral vote do not change anything.
706 resp = {getRound(), 0, {Vote(-1, itemid)}};
707 registerNewVote(next(resp));
708 BOOST_CHECK(m_node.avalanche->isAccepted(item));
709 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item), 0);
710 BOOST_CHECK_EQUAL(updates.size(), 0);
711
712 resp = {getRound(), 0, {Vote(0, itemid)}};
713 for (int i = 1; i < 7; i++) {
714 registerNewVote(next(resp));
715 BOOST_CHECK(m_node.avalanche->isAccepted(item));
716 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item), i);
717 BOOST_CHECK_EQUAL(updates.size(), 0);
718 }
719
720 // Two neutral votes will stall progress.
721 resp = {getRound(), 0, {Vote(-1, itemid)}};
722 registerNewVote(next(resp));
723 BOOST_CHECK(m_node.avalanche->isAccepted(item));
724 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item), 6);
725 BOOST_CHECK_EQUAL(updates.size(), 0);
726 registerNewVote(next(resp));
727 BOOST_CHECK(m_node.avalanche->isAccepted(item));
728 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item), 6);
729 BOOST_CHECK_EQUAL(updates.size(), 0);
730
731 resp = {getRound(), 0, {Vote(0, itemid)}};
732 for (int i = 2; i < 8; i++) {
733 registerNewVote(next(resp));
734 BOOST_CHECK(m_node.avalanche->isAccepted(item));
735 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item), 6);
736 BOOST_CHECK_EQUAL(updates.size(), 0);
737 }
738
739 // We vote for it numerous times to finalize it.
740 for (int i = 7; i < AVALANCHE_FINALIZATION_SCORE; i++) {
741 registerNewVote(next(resp));
742 BOOST_CHECK(m_node.avalanche->isAccepted(item));
743 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item), i);
744 BOOST_CHECK_EQUAL(updates.size(), 0);
745 }
746
747 // As long as it is not finalized, we poll.
748 invs = getInvsForNextPoll();
749 BOOST_CHECK_EQUAL(invs.size(), 1);
750 BOOST_CHECK_EQUAL(invs[0].type, invType);
751 BOOST_CHECK(invs[0].hash == itemid);
752
753 // Now finalize the decision.
754 registerNewVote(next(resp));
755 BOOST_CHECK_EQUAL(updates.size(), 1);
756 BOOST_CHECK(provider.fromAnyVoteItem(updates[0].getVoteItem()) == item);
757 BOOST_CHECK(updates[0].getStatus() == VoteStatus::Finalized);
758
759 // Once the decision is finalized, there is no poll for it.
760 invs = getInvsForNextPoll();
761 BOOST_CHECK_EQUAL(invs.size(), 0);
762
763 // Get a new item to vote on
764 item = provider.buildVoteItem();
765 itemid = provider.getVoteItemId(item);
766 BOOST_CHECK(addToReconcile(item));
767
768 // Now let's finalize rejection.
769 invs = getInvsForNextPoll();
770 BOOST_CHECK_EQUAL(invs.size(), 1);
771 BOOST_CHECK_EQUAL(invs[0].type, invType);
772 BOOST_CHECK(invs[0].hash == itemid);
773
774 resp = {getRound(), 0, {Vote(1, itemid)}};
775 for (int i = 0; i < 6; i++) {
776 registerNewVote(next(resp));
777 BOOST_CHECK(m_node.avalanche->isAccepted(item));
778 BOOST_CHECK_EQUAL(updates.size(), 0);
779 }
780
781 // Now the state will flip.
782 registerNewVote(next(resp));
783 BOOST_CHECK(!m_node.avalanche->isAccepted(item));
784 BOOST_CHECK_EQUAL(updates.size(), 1);
785 BOOST_CHECK(provider.fromAnyVoteItem(updates[0].getVoteItem()) == item);
786 BOOST_CHECK(updates[0].getStatus() == VoteStatus::Rejected);
787
788 // Now it is rejected, but we can vote for it numerous times.
789 for (int i = 1; i < AVALANCHE_FINALIZATION_SCORE; i++) {
790 registerNewVote(next(resp));
791 BOOST_CHECK(!m_node.avalanche->isAccepted(item));
792 BOOST_CHECK_EQUAL(updates.size(), 0);
793 }
794
795 // As long as it is not finalized, we poll.
796 invs = getInvsForNextPoll();
797 BOOST_CHECK_EQUAL(invs.size(), 1);
798 BOOST_CHECK_EQUAL(invs[0].type, invType);
799 BOOST_CHECK(invs[0].hash == itemid);
800
801 // Now finalize the decision.
802 registerNewVote(next(resp));
803 BOOST_CHECK(!m_node.avalanche->isAccepted(item));
804 BOOST_CHECK_EQUAL(updates.size(), 1);
805 BOOST_CHECK(provider.fromAnyVoteItem(updates[0].getVoteItem()) == item);
806 BOOST_CHECK(updates[0].getStatus() == VoteStatus::Invalid);
807
808 // Once the decision is finalized, there is no poll for it.
809 invs = getInvsForNextPoll();
810 BOOST_CHECK_EQUAL(invs.size(), 0);
811}
812
814 P provider(this);
815 const uint32_t invType = provider.invType;
816
817 auto itemA = provider.buildVoteItem();
818 auto itemidA = provider.getVoteItemId(itemA);
819
820 auto itemB = provider.buildVoteItem();
821 auto itemidB = provider.getVoteItemId(itemB);
822
823 // Create several nodes that support avalanche.
824 auto avanodes = ConnectNodes();
825
826 // Querying for random item returns false.
827 BOOST_CHECK(!m_node.avalanche->isAccepted(itemA));
828 BOOST_CHECK(!m_node.avalanche->isAccepted(itemB));
829
830 // Start voting on item A.
831 BOOST_CHECK(addToReconcile(itemA));
832 auto invs = getInvsForNextPoll();
833 BOOST_CHECK_EQUAL(invs.size(), 1);
834 BOOST_CHECK_EQUAL(invs[0].type, invType);
835 BOOST_CHECK(invs[0].hash == itemidA);
836
837 uint64_t round = getRound();
838 runEventLoop();
839 std::vector<avalanche::VoteItemUpdate> updates;
840 BOOST_CHECK(registerVotes(avanodes[0]->GetId(),
841 {round, 0, {Vote(0, itemidA)}}, updates));
842 BOOST_CHECK_EQUAL(updates.size(), 0);
843
844 // Start voting on item B after one vote.
845 std::vector<Vote> votes = provider.buildVotesForItems(0, {itemA, itemB});
846 Response resp{round + 1, 0, votes};
847 BOOST_CHECK(addToReconcile(itemB));
848 invs = getInvsForNextPoll();
849 BOOST_CHECK_EQUAL(invs.size(), 2);
850
851 // Ensure the inv ordering is as expected
852 for (size_t i = 0; i < invs.size(); i++) {
853 BOOST_CHECK_EQUAL(invs[i].type, invType);
854 BOOST_CHECK(invs[i].hash == votes[i].GetHash());
855 }
856
857 // Let's vote for these items a few times.
858 for (int i = 0; i < 4; i++) {
859 NodeId nodeid = getSuitableNodeToQuery();
860 runEventLoop();
861 BOOST_CHECK(registerVotes(nodeid, next(resp), updates));
862 BOOST_CHECK_EQUAL(updates.size(), 0);
863 }
864
865 // Now it is accepted, but we can vote for it numerous times.
866 for (int i = 0; i < AVALANCHE_FINALIZATION_SCORE; i++) {
867 NodeId nodeid = getSuitableNodeToQuery();
868 runEventLoop();
869 BOOST_CHECK(registerVotes(nodeid, next(resp), updates));
870 BOOST_CHECK_EQUAL(updates.size(), 0);
871 }
872
873 // Running two iterration of the event loop so that vote gets triggered on A
874 // and B.
875 NodeId firstNodeid = getSuitableNodeToQuery();
876 runEventLoop();
877 NodeId secondNodeid = getSuitableNodeToQuery();
878 runEventLoop();
879
880 BOOST_CHECK(firstNodeid != secondNodeid);
881
882 // Next vote will finalize item A.
883 BOOST_CHECK(registerVotes(firstNodeid, next(resp), updates));
884 BOOST_CHECK_EQUAL(updates.size(), 1);
885 BOOST_CHECK(provider.fromAnyVoteItem(updates[0].getVoteItem()) == itemA);
886 BOOST_CHECK(updates[0].getStatus() == VoteStatus::Finalized);
887
888 // We do not vote on A anymore.
889 invs = getInvsForNextPoll();
890 BOOST_CHECK_EQUAL(invs.size(), 1);
891 BOOST_CHECK_EQUAL(invs[0].type, invType);
892 BOOST_CHECK(invs[0].hash == itemidB);
893
894 // Next vote will finalize item B.
895 BOOST_CHECK(registerVotes(secondNodeid, resp, updates));
896 BOOST_CHECK_EQUAL(updates.size(), 1);
897 BOOST_CHECK(provider.fromAnyVoteItem(updates[0].getVoteItem()) == itemB);
898 BOOST_CHECK(updates[0].getStatus() == VoteStatus::Finalized);
899
900 // There is nothing left to vote on.
901 invs = getInvsForNextPoll();
902 BOOST_CHECK_EQUAL(invs.size(), 0);
903}
904
906 P provider(this);
907 const uint32_t invType = provider.invType;
908
909 auto item = provider.buildVoteItem();
910 auto itemid = provider.getVoteItemId(item);
911
912 // There is no node to query.
913 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), NO_NODE);
914
915 // Add enough nodes to have a valid quorum, and the same amount with no
916 // avalanche support
917 std::set<NodeId> avanodeIds;
918 auto avanodes = ConnectNodes();
919 for (auto avanode : avanodes) {
920 ConnectNode(NODE_NONE);
921 avanodeIds.insert(avanode->GetId());
922 }
923
924 auto getSelectedAvanodeId = [&]() {
925 NodeId avanodeid = getSuitableNodeToQuery();
926 BOOST_CHECK(avanodeIds.find(avanodeid) != avanodeIds.end());
927 return avanodeid;
928 };
929
930 // It returns one of the avalanche peer.
931 NodeId avanodeid = getSelectedAvanodeId();
932
933 // Register an item and check it is added to the list of elements to poll.
934 BOOST_CHECK(addToReconcile(item));
935 auto invs = getInvsForNextPoll();
936 BOOST_CHECK_EQUAL(invs.size(), 1);
937 BOOST_CHECK_EQUAL(invs[0].type, invType);
938 BOOST_CHECK(invs[0].hash == itemid);
939
940 std::set<NodeId> unselectedNodeids = avanodeIds;
941 unselectedNodeids.erase(avanodeid);
942 const size_t remainingNodeIds = unselectedNodeids.size();
943
944 uint64_t round = getRound();
945 for (size_t i = 0; i < remainingNodeIds; i++) {
946 // Trigger a poll on avanode.
947 runEventLoop();
948
949 // Another node is selected
950 NodeId nodeid = getSuitableNodeToQuery();
951 BOOST_CHECK(unselectedNodeids.find(nodeid) != avanodeIds.end());
952 unselectedNodeids.erase(nodeid);
953 }
954
955 // There is no more suitable peer available, so return nothing.
956 BOOST_CHECK(unselectedNodeids.empty());
957 runEventLoop();
958 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), NO_NODE);
959
960 // Respond to the request.
961 Response resp = {round, 0, {Vote(0, itemid)}};
962 std::vector<avalanche::VoteItemUpdate> updates;
963 BOOST_CHECK(registerVotes(avanodeid, resp, updates));
964 BOOST_CHECK_EQUAL(updates.size(), 0);
965
966 // Now that avanode fullfilled his request, it is added back to the list of
967 // queriable nodes.
968 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), avanodeid);
969
970 auto checkRegisterVotesError = [&](NodeId nodeid,
972 const std::string &expectedError) {
973 std::string error;
974 BOOST_CHECK(!registerVotes(nodeid, response, updates, error));
975 BOOST_CHECK_EQUAL(error, expectedError);
976 BOOST_CHECK_EQUAL(updates.size(), 0);
977 };
978
979 // Sending a response when not polled fails.
980 checkRegisterVotesError(avanodeid, next(resp), "unexpected-ava-response");
981
982 // Trigger a poll on avanode.
983 round = getRound();
984 runEventLoop();
985 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), NO_NODE);
986
987 // Sending responses that do not match the request also fails.
988 // 1. Too many results.
989 resp = {round, 0, {Vote(0, itemid), Vote(0, itemid)}};
990 runEventLoop();
991 checkRegisterVotesError(avanodeid, resp, "invalid-ava-response-size");
992 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), avanodeid);
993
994 // 2. Not enough results.
995 resp = {getRound(), 0, {}};
996 runEventLoop();
997 checkRegisterVotesError(avanodeid, resp, "invalid-ava-response-size");
998 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), avanodeid);
999
1000 // 3. Do not match the poll.
1001 resp = {getRound(), 0, {Vote()}};
1002 runEventLoop();
1003 checkRegisterVotesError(avanodeid, resp, "invalid-ava-response-content");
1004 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), avanodeid);
1005
1006 // At this stage we have reached the max inflight requests for our inv, so
1007 // it won't be requested anymore until the requests are fullfilled. Let's
1008 // vote on another item with no inflight request so the remaining tests
1009 // makes sense.
1010 invs = getInvsForNextPoll();
1011 BOOST_CHECK(invs.empty());
1012
1013 item = provider.buildVoteItem();
1014 itemid = provider.getVoteItemId(item);
1015 BOOST_CHECK(addToReconcile(item));
1016
1017 invs = getInvsForNextPoll();
1018 BOOST_CHECK_EQUAL(invs.size(), 1);
1019
1020 // 4. Invalid round count. Request is not discarded.
1021 uint64_t queryRound = getRound();
1022 runEventLoop();
1023
1024 resp = {queryRound + 1, 0, {Vote()}};
1025 checkRegisterVotesError(avanodeid, resp, "unexpected-ava-response");
1026
1027 resp = {queryRound - 1, 0, {Vote()}};
1028 checkRegisterVotesError(avanodeid, resp, "unexpected-ava-response");
1029
1030 // 5. Making request for invalid nodes do not work. Request is not
1031 // discarded.
1032 resp = {queryRound, 0, {Vote(0, itemid)}};
1033 checkRegisterVotesError(avanodeid + 1234, resp, "unexpected-ava-response");
1034
1035 // Proper response gets processed and avanode is available again.
1036 resp = {queryRound, 0, {Vote(0, itemid)}};
1037 BOOST_CHECK(registerVotes(avanodeid, resp, updates));
1038 BOOST_CHECK_EQUAL(updates.size(), 0);
1039 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), avanodeid);
1040
1041 // Out of order response are rejected.
1042 const auto item2 = provider.buildVoteItem();
1043 BOOST_CHECK(addToReconcile(item2));
1044
1045 std::vector<Vote> votes = provider.buildVotesForItems(0, {item, item2});
1046 resp = {getRound(), 0, {votes[1], votes[0]}};
1047 runEventLoop();
1048 checkRegisterVotesError(avanodeid, resp, "invalid-ava-response-content");
1049 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), avanodeid);
1050
1051 // But they are accepted in order.
1052 resp = {getRound(), 0, votes};
1053 runEventLoop();
1054 BOOST_CHECK(registerVotes(avanodeid, resp, updates));
1055 BOOST_CHECK_EQUAL(updates.size(), 0);
1056 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), avanodeid);
1057}
1058
1060 P provider(this);
1061 const uint32_t invType = provider.invType;
1062
1063 auto itemA = provider.buildVoteItem();
1064 auto itemB = provider.buildVoteItem();
1065
1066 auto avanodes = ConnectNodes();
1067 int nextNodeIndex = 0;
1068
1069 // Build votes to get proper ordering
1070 std::vector<Vote> votes = provider.buildVotesForItems(0, {itemA, itemB});
1071
1072 // Register the items and check they are added to the list of elements to
1073 // poll.
1074 BOOST_CHECK(addToReconcile(itemA));
1075 BOOST_CHECK(addToReconcile(itemB));
1076 auto invs = getInvsForNextPoll();
1077 BOOST_CHECK_EQUAL(invs.size(), 2);
1078 for (size_t i = 0; i < invs.size(); i++) {
1079 BOOST_CHECK_EQUAL(invs[i].type, invType);
1080 BOOST_CHECK(invs[i].hash == votes[i].GetHash());
1081 }
1082
1083 // When an item is marked invalid, stop polling.
1084 provider.invalidateItem(itemB);
1085
1086 Response goodResp{getRound(), 0, {Vote(0, provider.getVoteItemId(itemA))}};
1087 std::vector<avalanche::VoteItemUpdate> updates;
1088 runEventLoop();
1090 registerVotes(avanodes[nextNodeIndex++ % avanodes.size()]->GetId(),
1091 goodResp, updates));
1092 BOOST_CHECK_EQUAL(updates.size(), 0);
1093
1094 // Verify itemB is no longer being polled for
1095 invs = getInvsForNextPoll();
1096 BOOST_CHECK_EQUAL(invs.size(), 1);
1097 BOOST_CHECK_EQUAL(invs[0].type, invType);
1098 BOOST_CHECK(invs[0].hash == goodResp.GetVotes()[0].GetHash());
1099
1100 // Votes including itemB are rejected
1101 Response badResp{getRound(), 0, votes};
1102 runEventLoop();
1103 std::string error;
1105 !registerVotes(avanodes[nextNodeIndex++ % avanodes.size()]->GetId(),
1106 badResp, updates, error));
1107 BOOST_CHECK_EQUAL(error, "invalid-ava-response-size");
1108
1109 // Vote until itemA is invalidated by avalanche
1110 votes = provider.buildVotesForItems(1, {itemA});
1111 auto registerNewVote = [&]() {
1112 Response resp = {getRound(), 0, votes};
1113 runEventLoop();
1114 auto nodeid = avanodes[nextNodeIndex++ % avanodes.size()]->GetId();
1115 BOOST_CHECK(registerVotes(nodeid, resp, updates));
1116 };
1117 for (size_t i = 0; i < 4000; i++) {
1118 registerNewVote();
1119 if (updates.size() > 0 &&
1120 updates[0].getStatus() == VoteStatus::Invalid) {
1121 break;
1122 }
1123 }
1124
1125 // Verify itemA is no longer being polled for
1126 invs = getInvsForNextPoll();
1127 BOOST_CHECK_EQUAL(invs.size(), 0);
1128
1129 // Votes including itemA are rejected
1130 badResp = Response(getRound(), 0, votes);
1131 runEventLoop();
1133 !registerVotes(avanodes[nextNodeIndex++ % avanodes.size()]->GetId(),
1134 badResp, updates, error));
1135 BOOST_CHECK_EQUAL(error, "unexpected-ava-response");
1136}
1137
1138BOOST_TEST_DECORATOR(*boost::unit_test::timeout(60))
1140 P provider(this);
1141 ChainstateManager &chainman = *Assert(m_node.chainman);
1142
1143 auto queryTimeDuration = std::chrono::milliseconds(10);
1144 setArg("-avatimeout", ToString(queryTimeDuration.count()));
1145 // This would fail the test for blocks
1146 setArg("-avalanchestakingpreconsensus", "0");
1147
1149 bilingual_str error;
1150 m_node.avalanche = Processor::MakeProcessor(
1151 *m_node.args, *m_node.chain, m_node.connman.get(), chainman,
1152 m_node.mempool.get(), *m_node.scheduler, error);
1153
1154 const auto item = provider.buildVoteItem();
1155 const auto itemid = provider.getVoteItemId(item);
1156
1157 // Add the item
1158 BOOST_CHECK(addToReconcile(item));
1159
1160 // Create a quorum of nodes that support avalanche.
1161 ConnectNodes();
1162 NodeId avanodeid = NO_NODE;
1163
1164 // Expire requests after some time.
1165 for (int i = 0; i < 10; i++) {
1166 Response resp = {getRound(), 0, {Vote(0, itemid)}};
1167 avanodeid = getSuitableNodeToQuery();
1168
1169 auto start = Now<SteadyMilliseconds>();
1170 runEventLoop();
1171 // We cannot guarantee that we'll wait for just 1ms, so we have to bail
1172 // if we aren't within the proper time range.
1173 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1174 runEventLoop();
1175
1176 std::vector<avalanche::VoteItemUpdate> updates;
1177 bool ret = registerVotes(avanodeid, next(resp), updates);
1178 if (Now<SteadyMilliseconds>() > start + queryTimeDuration) {
1179 // We waited for too long, bail. Because we can't know for sure when
1180 // previous steps ran, ret is not deterministic and we do not check
1181 // it.
1182 i--;
1183 continue;
1184 }
1185
1186 // We are within time bounds, so the vote should have worked.
1187 BOOST_CHECK(ret);
1188
1189 avanodeid = getSuitableNodeToQuery();
1190
1191 // Now try again but wait for expiration.
1192 runEventLoop();
1193 std::this_thread::sleep_for(queryTimeDuration);
1194 runEventLoop();
1195 BOOST_CHECK(!registerVotes(avanodeid, next(resp), updates));
1196 }
1197}
1198
1200 P provider(this);
1201 const uint32_t invType = provider.invType;
1202
1203 // Create enough nodes so that we run into the inflight request limit.
1204 auto proof = GetProof();
1205 BOOST_CHECK(m_node.avalanche->withPeerManager(
1206 [&](avalanche::PeerManager &pm) { return pm.registerProof(proof); }));
1207
1208 std::array<CNode *, AVALANCHE_MAX_INFLIGHT_POLL + 1> nodes;
1209 for (auto &n : nodes) {
1210 n = ConnectNode(NODE_AVALANCHE);
1211 BOOST_CHECK(addNode(n->GetId(), proof->getId()));
1212 }
1213
1214 // Add an item to poll
1215 const auto item = provider.buildVoteItem();
1216 const auto itemid = provider.getVoteItemId(item);
1217 BOOST_CHECK(addToReconcile(item));
1218
1219 // Ensure there are enough requests in flight.
1220 std::map<NodeId, uint64_t> node_round_map;
1221 for (int i = 0; i < AVALANCHE_MAX_INFLIGHT_POLL; i++) {
1222 NodeId nodeid = getSuitableNodeToQuery();
1223 BOOST_CHECK(node_round_map.find(nodeid) == node_round_map.end());
1224 node_round_map.insert(std::pair<NodeId, uint64_t>(nodeid, getRound()));
1225 auto invs = getInvsForNextPoll();
1226 BOOST_CHECK_EQUAL(invs.size(), 1);
1227 BOOST_CHECK_EQUAL(invs[0].type, invType);
1228 BOOST_CHECK(invs[0].hash == itemid);
1229 runEventLoop();
1230 }
1231
1232 // Now that we have enough in flight requests, we shouldn't poll.
1233 auto suitablenodeid = getSuitableNodeToQuery();
1234 BOOST_CHECK(suitablenodeid != NO_NODE);
1235 auto invs = getInvsForNextPoll();
1236 BOOST_CHECK_EQUAL(invs.size(), 0);
1237 runEventLoop();
1238 BOOST_CHECK_EQUAL(getSuitableNodeToQuery(), suitablenodeid);
1239
1240 // Send one response, now we can poll again.
1241 auto it = node_round_map.begin();
1242 Response resp = {it->second, 0, {Vote(0, itemid)}};
1243 std::vector<avalanche::VoteItemUpdate> updates;
1244 BOOST_CHECK(registerVotes(it->first, resp, updates));
1245 node_round_map.erase(it);
1246
1247 invs = getInvsForNextPoll();
1248 BOOST_CHECK_EQUAL(invs.size(), 1);
1249 BOOST_CHECK_EQUAL(invs[0].type, invType);
1250 BOOST_CHECK(invs[0].hash == itemid);
1251}
1252
1253BOOST_AUTO_TEST_CASE(quorum_diversity) {
1254 std::vector<VoteItemUpdate> updates;
1255
1256 CBlock block = CreateAndProcessBlock({}, CScript());
1257 const BlockHash blockHash = block.GetHash();
1258 const CBlockIndex *pindex;
1259 {
1260 LOCK(cs_main);
1261 pindex =
1262 Assert(m_node.chainman)->m_blockman.LookupBlockIndex(blockHash);
1263 }
1264
1265 // Create nodes that supports avalanche.
1266 auto avanodes = ConnectNodes();
1267
1268 // Querying for random block returns false.
1269 BOOST_CHECK(!m_node.avalanche->isAccepted(pindex));
1270
1271 // Add a new block. Check it is added to the polls.
1272 BOOST_CHECK(m_node.avalanche->addToReconcile(pindex));
1273
1274 // Do one valid round of voting.
1275 uint64_t round = getRound();
1276 Response resp{round, 0, {Vote(0, blockHash)}};
1277
1278 // Check that all nodes can vote.
1279 for (size_t i = 0; i < avanodes.size(); i++) {
1280 runEventLoop();
1281 BOOST_CHECK(registerVotes(avanodes[i]->GetId(), next(resp), updates));
1282 }
1283
1284 // Generate a query for every single node.
1285 const NodeId firstNodeId = getSuitableNodeToQuery();
1286 std::map<NodeId, uint64_t> node_round_map;
1287 round = getRound();
1288 for (size_t i = 0; i < avanodes.size(); i++) {
1289 NodeId nodeid = getSuitableNodeToQuery();
1290 BOOST_CHECK(node_round_map.find(nodeid) == node_round_map.end());
1291 node_round_map[nodeid] = getRound();
1292 runEventLoop();
1293 }
1294
1295 // Now only the first node can vote. All others would be duplicate in the
1296 // quorum.
1297 auto confidence = m_node.avalanche->getConfidence(pindex);
1298 BOOST_REQUIRE(confidence > 0);
1299
1300 for (auto &[nodeid, r] : node_round_map) {
1301 if (nodeid == firstNodeId) {
1302 // Node 0 is the only one which can vote at this stage.
1303 round = r;
1304 continue;
1305 }
1306
1308 registerVotes(nodeid, {r, 0, {Vote(0, blockHash)}}, updates));
1309 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(pindex), confidence);
1310 }
1311
1313 registerVotes(firstNodeId, {round, 0, {Vote(0, blockHash)}}, updates));
1314 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(pindex), confidence + 1);
1315}
1316
1318 CScheduler s;
1319
1320 CBlock block = CreateAndProcessBlock({}, CScript());
1321 const BlockHash blockHash = block.GetHash();
1322 const CBlockIndex *pindex;
1323 {
1324 LOCK(cs_main);
1325 pindex =
1326 Assert(m_node.chainman)->m_blockman.LookupBlockIndex(blockHash);
1327 }
1328
1329 // Starting the event loop.
1330 BOOST_CHECK(m_node.avalanche->startEventLoop(s));
1331
1332 // There is one task planned in the next hour (our event loop).
1333 std::chrono::steady_clock::time_point start, stop;
1334 BOOST_CHECK_EQUAL(s.getQueueInfo(start, stop), 1);
1335
1336 // Starting twice doesn't start it twice.
1337 BOOST_CHECK(!m_node.avalanche->startEventLoop(s));
1338
1339 // Start the scheduler thread.
1340 std::thread schedulerThread(std::bind(&CScheduler::serviceQueue, &s));
1341
1342 // Create a quorum of nodes that support avalanche.
1343 auto avanodes = ConnectNodes();
1344
1345 // There is no query in flight at the moment.
1346 NodeId nodeid = getSuitableNodeToQuery();
1347 BOOST_CHECK_NE(nodeid, NO_NODE);
1348
1349 // Add a new block. Check it is added to the polls.
1350 uint64_t queryRound = getRound();
1351 BOOST_CHECK(m_node.avalanche->addToReconcile(pindex));
1352
1353 // Wait until all nodes got a poll
1354 for (int i = 0; i < 60 * 1000; i++) {
1355 // Technically, this is a race condition, but this should do just fine
1356 // as we wait up to 1 minute for an event that should take 80ms.
1357 UninterruptibleSleep(std::chrono::milliseconds(1));
1358 if (getRound() == queryRound + avanodes.size()) {
1359 break;
1360 }
1361 }
1362
1363 // Check that we effectively got a request and not timed out.
1364 BOOST_CHECK(getRound() > queryRound);
1365
1366 // Respond and check the cooldown time is respected.
1367 uint64_t responseRound = getRound();
1368 auto queryTime = Now<SteadyMilliseconds>() + std::chrono::milliseconds(100);
1369
1370 std::vector<VoteItemUpdate> updates;
1371 // Only the first node answers, so it's the only one that gets polled again
1372 BOOST_CHECK(registerVotes(nodeid, {queryRound, 100, {Vote(0, blockHash)}},
1373 updates));
1374
1375 for (int i = 0; i < 10000; i++) {
1376 // We make sure that we do not get a request before queryTime.
1377 UninterruptibleSleep(std::chrono::milliseconds(1));
1378 if (getRound() != responseRound) {
1379 BOOST_CHECK(Now<SteadyMilliseconds>() >= queryTime);
1380 break;
1381 }
1382 }
1383
1384 // But we eventually get one.
1385 BOOST_CHECK(getRound() > responseRound);
1386
1387 // Stop event loop.
1388 BOOST_CHECK(m_node.avalanche->stopEventLoop());
1389
1390 // We don't have any task scheduled anymore.
1391 BOOST_CHECK_EQUAL(s.getQueueInfo(start, stop), 0);
1392
1393 // Can't stop the event loop twice.
1394 BOOST_CHECK(!m_node.avalanche->stopEventLoop());
1395
1396 // Wait for the scheduler to stop.
1397 s.StopWhenDrained();
1398 schedulerThread.join();
1399}
1400
1402 CScheduler s;
1403 std::chrono::steady_clock::time_point start, stop;
1404
1405 std::thread schedulerThread;
1406 BOOST_CHECK(m_node.avalanche->startEventLoop(s));
1407 BOOST_CHECK_EQUAL(s.getQueueInfo(start, stop), 1);
1408
1409 // Start the service thread after the queue size check to prevent a race
1410 // condition where the thread may be processing the event loop task during
1411 // the check.
1412 schedulerThread = std::thread(std::bind(&CScheduler::serviceQueue, &s));
1413
1415 // Destroy the processor.
1416 m_node.avalanche.reset();
1417
1418 // Now that avalanche is destroyed, there is no more scheduled tasks.
1419 BOOST_CHECK_EQUAL(s.getQueueInfo(start, stop), 0);
1420
1421 // Wait for the scheduler to stop.
1422 s.StopWhenDrained();
1423 schedulerThread.join();
1424}
1425
1426BOOST_AUTO_TEST_CASE(add_proof_to_reconcile) {
1427 uint32_t score = MIN_VALID_PROOF_SCORE;
1428 Chainstate &active_chainstate = Assert(m_node.chainman)->ActiveChainstate();
1429
1430 auto addProofToReconcile = [&](uint32_t proofScore) {
1431 auto proof = buildRandomProof(active_chainstate, proofScore);
1432 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1433 BOOST_CHECK(pm.registerProof(proof));
1434 });
1435 BOOST_CHECK(m_node.avalanche->addToReconcile(proof));
1436 return proof;
1437 };
1438
1439 for (size_t i = 0; i < DEFAULT_AVALANCHE_MAX_ELEMENT_POLL; i++) {
1440 auto proof = addProofToReconcile(++score);
1441
1442 auto invs = AvalancheTest::getInvsForNextPoll(*m_node.avalanche);
1443 BOOST_CHECK_EQUAL(invs.size(), i + 1);
1444 BOOST_CHECK(invs.front().IsMsgProof());
1445 BOOST_CHECK_EQUAL(invs.front().hash, proof->getId());
1446 }
1447
1448 // From here a new proof is only polled if its score is in the top
1449 // DEFAULT_AVALANCHE_MAX_ELEMENT_POLL
1450 ProofId lastProofId;
1451 for (size_t i = 0; i < 10; i++) {
1452 auto proof = addProofToReconcile(++score);
1453
1454 auto invs = AvalancheTest::getInvsForNextPoll(*m_node.avalanche);
1456 BOOST_CHECK(invs.front().IsMsgProof());
1457 BOOST_CHECK_EQUAL(invs.front().hash, proof->getId());
1458
1459 lastProofId = proof->getId();
1460 }
1461
1462 for (size_t i = 0; i < 10; i++) {
1463 auto proof = addProofToReconcile(--score);
1464
1465 auto invs = AvalancheTest::getInvsForNextPoll(*m_node.avalanche);
1467 BOOST_CHECK(invs.front().IsMsgProof());
1468 BOOST_CHECK_EQUAL(invs.front().hash, lastProofId);
1469 }
1470
1471 {
1472 // The score is not high enough to get polled
1473 auto proof = addProofToReconcile(MIN_VALID_PROOF_SCORE);
1474 auto invs = AvalancheTest::getInvsForNextPoll(*m_node.avalanche);
1476 for (auto &inv : invs) {
1477 BOOST_CHECK_NE(inv.hash, proof->getId());
1478 }
1479 }
1480}
1481
1483 setArg("-avaproofstakeutxoconfirmations", "2");
1484 setArg("-avalancheconflictingproofcooldown", "0");
1485
1486 BOOST_CHECK(!m_node.avalanche->isAccepted(nullptr));
1487 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(nullptr), -1);
1488
1489 const CKey key = CKey::MakeCompressedKey();
1490
1491 const COutPoint conflictingOutpoint{TxId(GetRandHash()), 0};
1492 const COutPoint immatureOutpoint{TxId(GetRandHash()), 0};
1493 {
1495
1496 LOCK(cs_main);
1497 CCoinsViewCache &coins =
1498 Assert(m_node.chainman)->ActiveChainstate().CoinsTip();
1499 coins.AddCoin(conflictingOutpoint,
1500 Coin(CTxOut(PROOF_DUST_THRESHOLD, script), 10, false),
1501 false);
1502 coins.AddCoin(immatureOutpoint,
1503 Coin(CTxOut(PROOF_DUST_THRESHOLD, script), 100, false),
1504 false);
1505 }
1506
1507 auto buildProof = [&](const COutPoint &outpoint, uint64_t sequence,
1508 uint32_t height = 10) {
1509 ProofBuilder pb(sequence, 0, key, UNSPENDABLE_ECREG_PAYOUT_SCRIPT);
1511 pb.addUTXO(outpoint, PROOF_DUST_THRESHOLD, height, false, key));
1512 return pb.build();
1513 };
1514
1515 auto conflictingProof = buildProof(conflictingOutpoint, 1);
1516 auto validProof = buildProof(conflictingOutpoint, 2);
1517 auto immatureProof = buildProof(immatureOutpoint, 3, 100);
1518
1519 BOOST_CHECK(!m_node.avalanche->isAccepted(conflictingProof));
1520 BOOST_CHECK(!m_node.avalanche->isAccepted(validProof));
1521 BOOST_CHECK(!m_node.avalanche->isAccepted(immatureProof));
1522 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(conflictingProof), -1);
1523 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(validProof), -1);
1524 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(immatureProof), -1);
1525
1526 // Reconciling proofs that don't exist will fail
1527 BOOST_CHECK(!m_node.avalanche->addToReconcile(conflictingProof));
1528 BOOST_CHECK(!m_node.avalanche->addToReconcile(validProof));
1529 BOOST_CHECK(!m_node.avalanche->addToReconcile(immatureProof));
1530
1531 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1532 BOOST_CHECK(pm.registerProof(conflictingProof));
1533 BOOST_CHECK(pm.registerProof(validProof));
1534 BOOST_CHECK(!pm.registerProof(immatureProof));
1535
1536 BOOST_CHECK(pm.isBoundToPeer(validProof->getId()));
1537 BOOST_CHECK(pm.isInConflictingPool(conflictingProof->getId()));
1538 BOOST_CHECK(pm.isImmature(immatureProof->getId()));
1539 });
1540
1541 BOOST_CHECK(m_node.avalanche->addToReconcile(conflictingProof));
1542 BOOST_CHECK(!m_node.avalanche->isAccepted(conflictingProof));
1543 BOOST_CHECK(!m_node.avalanche->isAccepted(validProof));
1544 BOOST_CHECK(!m_node.avalanche->isAccepted(immatureProof));
1545 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(conflictingProof), 0);
1546 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(validProof), -1);
1547 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(immatureProof), -1);
1548
1549 BOOST_CHECK(m_node.avalanche->addToReconcile(validProof));
1550 BOOST_CHECK(!m_node.avalanche->isAccepted(conflictingProof));
1551 BOOST_CHECK(m_node.avalanche->isAccepted(validProof));
1552 BOOST_CHECK(!m_node.avalanche->isAccepted(immatureProof));
1553 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(conflictingProof), 0);
1554 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(validProof), 0);
1555 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(immatureProof), -1);
1556
1557 BOOST_CHECK(!m_node.avalanche->addToReconcile(immatureProof));
1558 BOOST_CHECK(!m_node.avalanche->isAccepted(conflictingProof));
1559 BOOST_CHECK(m_node.avalanche->isAccepted(validProof));
1560 BOOST_CHECK(!m_node.avalanche->isAccepted(immatureProof));
1561 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(conflictingProof), 0);
1562 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(validProof), 0);
1563 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(immatureProof), -1);
1564}
1565
1566BOOST_AUTO_TEST_CASE(quorum_detection) {
1567 // Set min quorum parameters for our test
1568 int minStake = 400'000'000;
1569 setArg("-avaminquorumstake", ToString(minStake));
1570 setArg("-avaminquorumconnectedstakeratio", "0.5");
1571
1572 // Create a new processor with our given quorum parameters
1573 const auto &currency = Currency::get();
1574 uint32_t minScore = Proof::amountToScore(minStake * currency.baseunit);
1575
1576 Chainstate &active_chainstate = Assert(m_node.chainman)->ActiveChainstate();
1577
1578 const CKey key = CKey::MakeCompressedKey();
1579 auto localProof =
1580 buildRandomProof(active_chainstate, minScore / 4, 100, key);
1581 setArg("-avamasterkey", EncodeSecret(key));
1582 setArg("-avaproof", localProof->ToHex());
1583
1585 bilingual_str error;
1586 ChainstateManager &chainman = *Assert(m_node.chainman);
1587 m_node.avalanche = Processor::MakeProcessor(
1588 *m_node.args, *m_node.chain, m_node.connman.get(), chainman,
1589 m_node.mempool.get(), *m_node.scheduler, error);
1590
1591 BOOST_CHECK(m_node.avalanche != nullptr);
1592 BOOST_CHECK(m_node.avalanche->getLocalProof() != nullptr);
1593 BOOST_CHECK_EQUAL(m_node.avalanche->getLocalProof()->getId(),
1594 localProof->getId());
1595 BOOST_CHECK_EQUAL(AvalancheTest::getMinQuorumScore(*m_node.avalanche),
1596 minScore);
1598 AvalancheTest::getMinQuorumConnectedScoreRatio(*m_node.avalanche), 0.5);
1599
1600 // The local proof has not been validated yet
1601 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1604 });
1605 BOOST_CHECK(!m_node.avalanche->isQuorumEstablished());
1606
1607 // Register the local proof. This is normally done when the chain tip is
1608 // updated. The local proof should be accounted for in the min quorum
1609 // computation but the peer manager doesn't know about that.
1610 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1611 BOOST_CHECK(pm.registerProof(m_node.avalanche->getLocalProof()));
1613 pm.isBoundToPeer(m_node.avalanche->getLocalProof()->getId()));
1614 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), minScore / 4);
1616 });
1617 BOOST_CHECK(!m_node.avalanche->isQuorumEstablished());
1618
1619 // Add enough nodes to get a conclusive vote
1620 for (NodeId id = 0; id < 8; id++) {
1621 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1622 pm.addNode(id, m_node.avalanche->getLocalProof()->getId(),
1624 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), minScore / 4);
1625 BOOST_CHECK_EQUAL(pm.getConnectedPeersScore(), minScore / 4);
1626 });
1627 }
1628
1629 // Add part of the required stake and make sure we still report no quorum
1630 auto proof1 = buildRandomProof(active_chainstate, minScore / 2);
1631 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1632 BOOST_CHECK(pm.registerProof(proof1));
1633 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), 3 * minScore / 4);
1634 BOOST_CHECK_EQUAL(pm.getConnectedPeersScore(), minScore / 4);
1635 });
1636 BOOST_CHECK(!m_node.avalanche->isQuorumEstablished());
1637
1638 // Add the rest of the stake, but we are still lacking connected stake
1639 const int64_t tipTime =
1640 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip())
1641 ->GetBlockTime();
1642 const COutPoint utxo{TxId(GetRandHash()), 0};
1643 const Amount amount = (int64_t(minScore / 4) * COIN) / 100;
1644 const int height = 100;
1645 const bool isCoinbase = false;
1646 {
1647 LOCK(cs_main);
1648 CCoinsViewCache &coins = active_chainstate.CoinsTip();
1649 coins.AddCoin(utxo,
1651 PKHash(key.GetPubKey()))),
1652 height, isCoinbase),
1653 false);
1654 }
1655 ProofBuilder pb(1, tipTime + 1, key, UNSPENDABLE_ECREG_PAYOUT_SCRIPT);
1656 BOOST_CHECK(pb.addUTXO(utxo, amount, height, isCoinbase, key));
1657 auto proof2 = pb.build();
1658
1659 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1660 BOOST_CHECK(pm.registerProof(proof2));
1661 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), minScore);
1662 BOOST_CHECK_EQUAL(pm.getConnectedPeersScore(), minScore / 4);
1663 });
1664 BOOST_CHECK(!m_node.avalanche->isQuorumEstablished());
1665
1666 // Adding a node should cause the quorum to be detected and locked-in
1667 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1668 pm.addNode(8, proof2->getId(), DEFAULT_AVALANCHE_MAX_ELEMENT_POLL);
1669 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), minScore);
1670 // The peer manager knows that proof2 has a node attached ...
1671 BOOST_CHECK_EQUAL(pm.getConnectedPeersScore(), minScore / 2);
1672 });
1673 // ... but the processor also account for the local proof, so we reached 50%
1674 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
1675
1676 // Go back to not having enough connected score, but we've already latched
1677 // the quorum as established
1678 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1679 pm.removeNode(8);
1680 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), minScore);
1681 BOOST_CHECK_EQUAL(pm.getConnectedPeersScore(), minScore / 4);
1682 });
1683 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
1684
1685 // Removing one more node drops our count below the minimum and the quorum
1686 // is no longer ready
1687 m_node.avalanche->withPeerManager(
1688 [&](avalanche::PeerManager &pm) { pm.removeNode(7); });
1689 BOOST_CHECK(!m_node.avalanche->isQuorumEstablished());
1690
1691 // It resumes when we have enough nodes again
1692 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1693 pm.addNode(7, m_node.avalanche->getLocalProof()->getId(),
1695 });
1696 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
1697
1698 // Remove peers one at a time until the quorum is no longer established
1699 auto spendProofUtxo = [&](ProofRef proof) {
1700 {
1701 LOCK(cs_main);
1702 CCoinsViewCache &coins = chainman.ActiveChainstate().CoinsTip();
1703 coins.SpendCoin(proof->getStakes()[0].getStake().getUTXO());
1704 }
1705 m_node.avalanche->withPeerManager([&proof](avalanche::PeerManager &pm) {
1706 pm.updatedBlockTip();
1707 BOOST_CHECK(!pm.isBoundToPeer(proof->getId()));
1708 });
1709 };
1710
1711 // Expire proof2, the quorum is still latched
1712 for (int64_t i = 0; i < 6; i++) {
1713 SetMockTime(proof2->getExpirationTime() + i);
1714 CreateAndProcessBlock({}, CScript());
1715 }
1717 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip())
1718 ->GetMedianTimePast(),
1719 proof2->getExpirationTime());
1720 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1721 pm.updatedBlockTip();
1722 BOOST_CHECK(!pm.exists(proof2->getId()));
1723 });
1724 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1725 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), 3 * minScore / 4);
1726 BOOST_CHECK_EQUAL(pm.getConnectedPeersScore(), minScore / 4);
1727 });
1728 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
1729
1730 spendProofUtxo(proof1);
1731 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1732 BOOST_CHECK_EQUAL(pm.getTotalPeersScore(), minScore / 4);
1733 BOOST_CHECK_EQUAL(pm.getConnectedPeersScore(), minScore / 4);
1734 });
1735 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
1736
1737 spendProofUtxo(m_node.avalanche->getLocalProof());
1738 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
1741 });
1742 // There is no node left
1743 BOOST_CHECK(!m_node.avalanche->isQuorumEstablished());
1744}
1745
1746BOOST_AUTO_TEST_CASE(quorum_detection_parameter_validation) {
1747 // Create vector of tuples of:
1748 // <min stake, min ratio, min avaproofs messages, success bool>
1749 const std::vector<std::tuple<std::string, std::string, std::string, bool>>
1750 testCases = {
1751 // All parameters are invalid
1752 {"", "", "", false},
1753 {"-1", "-1", "-1", false},
1754
1755 // Min stake is out of range
1756 {"-1", "0", "0", false},
1757 {"-0.01", "0", "0", false},
1758 {"21000000000000.01", "0", "0", false},
1759
1760 // Min connected ratio is out of range
1761 {"0", "-1", "0", false},
1762 {"0", "1.1", "0", false},
1763
1764 // Min avaproofs messages ratio is out of range
1765 {"0", "0", "-1", false},
1766
1767 // All parameters are valid
1768 {"0", "0", "0", true},
1769 {"0.00", "0", "0", true},
1770 {"0.01", "0", "0", true},
1771 {"1", "0.1", "0", true},
1772 {"10", "0.5", "0", true},
1773 {"10", "1", "0", true},
1774 {"21000000000000.00", "0", "0", true},
1775 {"0", "0", "1", true},
1776 {"0", "0", "100", true},
1777 };
1778
1779 // For each case set the parameters and check that making the processor
1780 // succeeds or fails as expected
1781 for (const auto &[stake, stakeRatio, numProofsMessages, success] :
1782 testCases) {
1783 setArg("-avaminquorumstake", stake);
1784 setArg("-avaminquorumconnectedstakeratio", stakeRatio);
1785 setArg("-avaminavaproofsnodecount", numProofsMessages);
1786
1787 bilingual_str error;
1788 std::unique_ptr<Processor> processor = Processor::MakeProcessor(
1789 *m_node.args, *m_node.chain, m_node.connman.get(),
1790 *Assert(m_node.chainman), m_node.mempool.get(), *m_node.scheduler,
1791 error);
1792
1793 if (success) {
1794 BOOST_CHECK(processor != nullptr);
1795 BOOST_CHECK(error.empty());
1796 BOOST_CHECK_EQUAL(error.original, "");
1797 } else {
1798 BOOST_CHECK(processor == nullptr);
1799 BOOST_CHECK(!error.empty());
1800 BOOST_CHECK(error.original != "");
1801 }
1802 }
1803}
1804
1805BOOST_AUTO_TEST_CASE(min_avaproofs_messages) {
1806 ChainstateManager &chainman = *Assert(m_node.chainman);
1807
1808 auto checkMinAvaproofsMessages = [&](int64_t minAvaproofsMessages) {
1809 setArg("-avaminavaproofsnodecount", ToString(minAvaproofsMessages));
1810
1811 bilingual_str error;
1812 auto processor = Processor::MakeProcessor(
1813 *m_node.args, *m_node.chain, m_node.connman.get(), chainman,
1814 m_node.mempool.get(), *m_node.scheduler, error);
1815
1816 auto addNode = [&](NodeId nodeid) {
1817 auto proof = buildRandomProof(chainman.ActiveChainstate(),
1819 processor->withPeerManager([&](avalanche::PeerManager &pm) {
1820 BOOST_CHECK(pm.registerProof(proof));
1821 BOOST_CHECK(pm.addNode(nodeid, proof->getId(),
1823 });
1824 };
1825
1826 // Add enough node to have a conclusive vote, but don't account any
1827 // avaproofs.
1828 // NOTE: we can't use the test facilites like ConnectNodes() because we
1829 // are not testing on m_node.avalanche.
1830 for (NodeId id = 100; id < 108; id++) {
1831 addNode(id);
1832 }
1833
1834 BOOST_CHECK_EQUAL(processor->isQuorumEstablished(),
1835 minAvaproofsMessages <= 0);
1836
1837 for (int64_t i = 0; i < minAvaproofsMessages - 1; i++) {
1838 addNode(i);
1839
1840 processor->avaproofsSent(i);
1841 BOOST_CHECK_EQUAL(processor->getAvaproofsNodeCounter(), i + 1);
1842
1843 // Receiving again on the same node does not increase the counter
1844 processor->avaproofsSent(i);
1845 BOOST_CHECK_EQUAL(processor->getAvaproofsNodeCounter(), i + 1);
1846
1847 BOOST_CHECK(!processor->isQuorumEstablished());
1848 }
1849
1850 addNode(minAvaproofsMessages);
1851 processor->avaproofsSent(minAvaproofsMessages);
1852 BOOST_CHECK(processor->isQuorumEstablished());
1853
1854 // Check the latch
1855 AvalancheTest::clearavaproofsNodeCounter(*processor);
1856 BOOST_CHECK(processor->isQuorumEstablished());
1857 };
1858
1859 checkMinAvaproofsMessages(0);
1860 checkMinAvaproofsMessages(1);
1861 checkMinAvaproofsMessages(10);
1862 checkMinAvaproofsMessages(100);
1863}
1864
1866 // Check that setting voting parameters has the expected effect
1867 setArg("-avastalevotethreshold",
1869 setArg("-avastalevotefactor", "2");
1870 // This would fail the test for blocks
1871 setArg("-avalanchestakingpreconsensus", "0");
1872
1873 const std::vector<std::tuple<int, int>> testCases = {
1874 // {number of yes votes, number of neutral votes}
1877 };
1878
1880 bilingual_str error;
1881 m_node.avalanche = Processor::MakeProcessor(
1882 *m_node.args, *m_node.chain, m_node.connman.get(),
1883 *Assert(m_node.chainman), m_node.mempool.get(), *m_node.scheduler,
1884 error);
1885
1886 BOOST_CHECK(m_node.avalanche != nullptr);
1887 BOOST_CHECK(error.empty());
1888
1889 P provider(this);
1890 const uint32_t invType = provider.invType;
1891
1892 const auto item = provider.buildVoteItem();
1893 const auto itemid = provider.getVoteItemId(item);
1894
1895 // Create nodes that supports avalanche.
1896 auto avanodes = ConnectNodes();
1897 int nextNodeIndex = 0;
1898
1899 std::vector<avalanche::VoteItemUpdate> updates;
1900 for (const auto &[numYesVotes, numNeutralVotes] : testCases) {
1901 // Add a new item. Check it is added to the polls.
1902 BOOST_CHECK(addToReconcile(item));
1903 auto invs = getInvsForNextPoll();
1904 BOOST_CHECK_EQUAL(invs.size(), 1);
1905 BOOST_CHECK_EQUAL(invs[0].type, invType);
1906 BOOST_CHECK(invs[0].hash == itemid);
1907
1908 BOOST_CHECK(m_node.avalanche->isAccepted(item));
1909
1910 auto registerNewVote = [&](const Response &resp) {
1911 runEventLoop();
1912 auto nodeid = avanodes[nextNodeIndex++ % avanodes.size()]->GetId();
1913 BOOST_CHECK(registerVotes(nodeid, resp, updates));
1914 };
1915
1916 // Add some confidence
1917 for (int i = 0; i < numYesVotes; i++) {
1918 Response resp = {getRound(), 0, {Vote(0, itemid)}};
1919 registerNewVote(next(resp));
1920 BOOST_CHECK(m_node.avalanche->isAccepted(item));
1921 BOOST_CHECK_EQUAL(m_node.avalanche->getConfidence(item),
1922 i >= 6 ? i - 5 : 0);
1923 BOOST_CHECK_EQUAL(updates.size(), 0);
1924 }
1925
1926 // Vote until just before item goes stale
1927 for (int i = 0; i < numNeutralVotes; i++) {
1928 Response resp = {getRound(), 0, {Vote(-1, itemid)}};
1929 registerNewVote(next(resp));
1930 BOOST_CHECK_EQUAL(updates.size(), 0);
1931 }
1932
1933 // As long as it is not stale, we poll.
1934 invs = getInvsForNextPoll();
1935 BOOST_CHECK_EQUAL(invs.size(), 1);
1936 BOOST_CHECK_EQUAL(invs[0].type, invType);
1937 BOOST_CHECK(invs[0].hash == itemid);
1938
1939 // Now stale
1940 Response resp = {getRound(), 0, {Vote(-1, itemid)}};
1941 registerNewVote(next(resp));
1942 BOOST_CHECK_EQUAL(updates.size(), 1);
1943 BOOST_CHECK(provider.fromAnyVoteItem(updates[0].getVoteItem()) == item);
1944 BOOST_CHECK(updates[0].getStatus() == VoteStatus::Stale);
1945
1946 // Once stale, there is no poll for it.
1947 invs = getInvsForNextPoll();
1948 BOOST_CHECK_EQUAL(invs.size(), 0);
1949 }
1950}
1951
1952BOOST_AUTO_TEST_CASE(block_vote_finalization_tip) {
1953 BlockProvider provider(this);
1954
1955 BOOST_CHECK(!m_node.avalanche->hasFinalizedTip());
1956
1957 std::vector<CBlockIndex *> blockIndexes;
1958 for (size_t i = 0; i < DEFAULT_AVALANCHE_MAX_ELEMENT_POLL; i++) {
1959 CBlockIndex *pindex = provider.buildVoteItem();
1960 BOOST_CHECK(addToReconcile(pindex));
1961 blockIndexes.push_back(pindex);
1962 }
1963
1964 auto invs = getInvsForNextPoll();
1966 for (size_t i = 0; i < DEFAULT_AVALANCHE_MAX_ELEMENT_POLL; i++) {
1968 invs[i].hash,
1969 blockIndexes[DEFAULT_AVALANCHE_MAX_ELEMENT_POLL - i - 1]
1970 ->GetBlockHash());
1971 }
1972
1973 // Build a vote vector with the 11th block only being accepted and others
1974 // unknown.
1975 const BlockHash eleventhBlockHash =
1976 blockIndexes[DEFAULT_AVALANCHE_MAX_ELEMENT_POLL - 10 - 1]
1977 ->GetBlockHash();
1978 std::vector<Vote> votes;
1980 for (size_t i = DEFAULT_AVALANCHE_MAX_ELEMENT_POLL; i > 0; i--) {
1981 BlockHash blockhash = blockIndexes[i - 1]->GetBlockHash();
1982 votes.emplace_back(blockhash == eleventhBlockHash ? 0 : -1, blockhash);
1983 }
1984
1985 auto avanodes = ConnectNodes();
1986 int nextNodeIndex = 0;
1987
1988 std::vector<avalanche::VoteItemUpdate> updates;
1989 auto registerNewVote = [&]() {
1990 Response resp = {getRound(), 0, votes};
1991 runEventLoop();
1992 auto nodeid = avanodes[nextNodeIndex++ % avanodes.size()]->GetId();
1993 BOOST_CHECK(registerVotes(nodeid, resp, updates));
1994 };
1995
1996 BOOST_CHECK(!m_node.avalanche->hasFinalizedTip());
1997
1998 // Vote for the blocks until the one being accepted finalizes
1999 bool eleventhBlockFinalized = false;
2000 for (size_t i = 0; i < 10000 && !eleventhBlockFinalized; i++) {
2001 registerNewVote();
2002
2003 for (auto &update : updates) {
2004 if (update.getStatus() == VoteStatus::Finalized &&
2005 provider.fromAnyVoteItem(update.getVoteItem())
2006 ->GetBlockHash() == eleventhBlockHash) {
2007 eleventhBlockFinalized = true;
2008 BOOST_CHECK(m_node.avalanche->hasFinalizedTip());
2009 } else {
2010 BOOST_CHECK(!m_node.avalanche->hasFinalizedTip());
2011 }
2012 }
2013 }
2014 BOOST_CHECK(eleventhBlockFinalized);
2015 BOOST_CHECK(m_node.avalanche->hasFinalizedTip());
2016
2017 // From now only the 10 blocks with more work are polled for
2018 clearInvsNotWorthPolling();
2019 invs = getInvsForNextPoll();
2020 BOOST_CHECK_EQUAL(invs.size(), 10);
2021 for (size_t i = 0; i < 10; i++) {
2023 invs[i].hash,
2024 blockIndexes[DEFAULT_AVALANCHE_MAX_ELEMENT_POLL - i - 1]
2025 ->GetBlockHash());
2026 }
2027
2028 // Adding ancestor blocks to reconcile will fail
2029 for (size_t i = 0; i < DEFAULT_AVALANCHE_MAX_ELEMENT_POLL - 10 - 1; i++) {
2030 BOOST_CHECK(!addToReconcile(blockIndexes[i]));
2031 }
2032
2033 // Create a couple concurrent chain tips
2034 CBlockIndex *tip = provider.buildVoteItem();
2035
2036 auto &activeChainstate = m_node.chainman->ActiveChainstate();
2038 activeChainstate.InvalidateBlock(state, tip);
2039
2040 // Use another script to make sure we don't generate the same block again
2041 CBlock altblock = CreateAndProcessBlock({}, CScript() << OP_TRUE);
2042 auto alttip = WITH_LOCK(
2043 cs_main, return Assert(m_node.chainman)
2044 ->m_blockman.LookupBlockIndex(altblock.GetHash()));
2045 BOOST_CHECK(alttip);
2046 BOOST_CHECK(alttip->pprev == tip->pprev);
2047 BOOST_CHECK(alttip->GetBlockHash() != tip->GetBlockHash());
2048
2049 // Reconsider the previous tip valid, so we have concurrent tip candidates
2050 {
2051 LOCK(cs_main);
2052 activeChainstate.ResetBlockFailureFlags(tip);
2053 }
2054 activeChainstate.ActivateBestChain(state);
2055
2056 BOOST_CHECK(addToReconcile(tip));
2057 BOOST_CHECK(addToReconcile(alttip));
2058 clearInvsNotWorthPolling();
2059 invs = getInvsForNextPoll();
2060 BOOST_CHECK_EQUAL(invs.size(), 12);
2061
2062 // Vote for the tip until it finalizes
2063 BlockHash tiphash = tip->GetBlockHash();
2064 votes.clear();
2065 votes.reserve(12);
2066 for (auto &inv : invs) {
2067 votes.emplace_back(inv.hash == tiphash ? 0 : -1, inv.hash);
2068 }
2069
2070 bool tipFinalized = false;
2071 for (size_t i = 0; i < 10000 && !tipFinalized; i++) {
2072 registerNewVote();
2073
2074 for (auto &update : updates) {
2075 if (update.getStatus() == VoteStatus::Finalized &&
2076 provider.fromAnyVoteItem(update.getVoteItem())
2077 ->GetBlockHash() == tiphash) {
2078 tipFinalized = true;
2079 }
2080 }
2081 }
2082 BOOST_CHECK(tipFinalized);
2083
2084 // Now the tip and all its ancestors will be removed from polls. Only the
2085 // alttip remains because it is on a forked chain so we want to keep polling
2086 // for that one until it's invalidated or stalled.
2087 clearInvsNotWorthPolling();
2088 invs = getInvsForNextPoll();
2089 BOOST_CHECK_EQUAL(invs.size(), 1);
2090 BOOST_CHECK_EQUAL(invs[0].hash, alttip->GetBlockHash());
2091
2092 // Cannot reconcile a finalized block
2093 BOOST_CHECK(!addToReconcile(tip));
2094
2095 // Vote for alttip until it invalidates
2096 BlockHash alttiphash = alttip->GetBlockHash();
2097 votes = {{1, alttiphash}};
2098
2099 bool alttipInvalidated = false;
2100 for (size_t i = 0; i < 10000 && !alttipInvalidated; i++) {
2101 registerNewVote();
2102
2103 for (auto &update : updates) {
2104 if (update.getStatus() == VoteStatus::Invalid &&
2105 provider.fromAnyVoteItem(update.getVoteItem())
2106 ->GetBlockHash() == alttiphash) {
2107 alttipInvalidated = true;
2108 }
2109 }
2110 }
2111 BOOST_CHECK(alttipInvalidated);
2112 invs = getInvsForNextPoll();
2113 BOOST_CHECK_EQUAL(invs.size(), 0);
2114
2115 // Cannot reconcile an invalidated block
2116 BOOST_CHECK(!addToReconcile(alttip));
2117}
2118
2119BOOST_AUTO_TEST_CASE(vote_map_comparator) {
2120 ChainstateManager &chainman = *Assert(m_node.chainman);
2121 Chainstate &activeChainState = chainman.ActiveChainstate();
2122
2123 const int numberElementsEachType = 100;
2125
2126 std::vector<ProofRef> proofs;
2127 for (size_t i = 1; i <= numberElementsEachType; i++) {
2128 auto proof =
2129 buildRandomProof(activeChainState, i * MIN_VALID_PROOF_SCORE);
2130 BOOST_CHECK(proof != nullptr);
2131 proofs.emplace_back(std::move(proof));
2132 }
2133 Shuffle(proofs.begin(), proofs.end(), rng);
2134
2135 std::vector<CBlockIndex> indexes;
2136 for (size_t i = 1; i <= numberElementsEachType; i++) {
2137 CBlockIndex index;
2138 index.nChainWork = i;
2139 indexes.emplace_back(std::move(index));
2140 }
2141 Shuffle(indexes.begin(), indexes.end(), rng);
2142
2143 auto allItems = std::make_tuple(std::move(proofs), std::move(indexes));
2144 static const size_t numTypes = std::tuple_size<decltype(allItems)>::value;
2145
2146 RWCollection<VoteMap> voteMap;
2147
2148 {
2149 auto writeView = voteMap.getWriteView();
2150 for (size_t i = 0; i < numberElementsEachType; i++) {
2151 // Randomize the insert order at each loop increment
2152 const size_t firstType = rng.randrange(numTypes);
2153
2154 for (size_t j = 0; j < numTypes; j++) {
2155 switch ((firstType + j) % numTypes) {
2156 // ProofRef
2157 case 0:
2158 writeView->insert(std::make_pair(
2159 std::get<0>(allItems)[i], VoteRecord(true)));
2160 break;
2161 // CBlockIndex *
2162 case 1:
2163 writeView->insert(std::make_pair(
2164 &std::get<1>(allItems)[i], VoteRecord(true)));
2165 break;
2166 default:
2167 break;
2168 }
2169 }
2170 }
2171 }
2172
2173 {
2174 // Check ordering
2175 auto readView = voteMap.getReadView();
2176 auto it = readView.begin();
2177
2178 // The first batch of items is the proofs ordered by score (descending)
2179 uint32_t lastScore = std::numeric_limits<uint32_t>::max();
2180 for (size_t i = 0; i < numberElementsEachType; i++) {
2181 BOOST_CHECK(std::holds_alternative<const ProofRef>(it->first));
2182
2183 uint32_t currentScore =
2184 std::get<const ProofRef>(it->first)->getScore();
2185 BOOST_CHECK_LT(currentScore, lastScore);
2186 lastScore = currentScore;
2187
2188 it++;
2189 }
2190
2191 // The next batch of items is the block indexes ordered by work
2192 // (descending)
2193 arith_uint256 lastWork = ~arith_uint256(0);
2194 for (size_t i = 0; i < numberElementsEachType; i++) {
2195 BOOST_CHECK(std::holds_alternative<const CBlockIndex *>(it->first));
2196
2197 arith_uint256 currentWork =
2198 std::get<const CBlockIndex *>(it->first)->nChainWork;
2199 BOOST_CHECK(currentWork < lastWork);
2200 lastWork = currentWork;
2201
2202 it++;
2203 }
2204
2205 BOOST_CHECK(it == readView.end());
2206 }
2207}
2208
2209BOOST_AUTO_TEST_CASE(block_reconcile_initial_vote) {
2210 auto &chainman = Assert(m_node.chainman);
2211 Chainstate &chainstate = chainman->ActiveChainstate();
2212
2213 const auto block = std::make_shared<const CBlock>(
2214 this->CreateBlock({}, CScript(), chainstate));
2215 const BlockHash blockhash = block->GetHash();
2216
2218 CBlockIndex *blockindex;
2219 {
2220 LOCK(cs_main);
2221 BOOST_CHECK(chainman->AcceptBlock(block, state,
2222 /*fRequested=*/true, /*dbp=*/nullptr,
2223 /*fNewBlock=*/nullptr,
2224 /*min_pow_checked=*/true));
2225
2226 blockindex = chainman->m_blockman.LookupBlockIndex(blockhash);
2227 BOOST_CHECK(blockindex);
2228 }
2229
2230 // The block is not connected yet, and not added to the poll list yet
2231 BOOST_CHECK(AvalancheTest::getInvsForNextPoll(*m_node.avalanche).empty());
2232 BOOST_CHECK(!m_node.avalanche->isAccepted(blockindex));
2233
2234 // Call ActivateBestChain to connect the new block
2236 chainstate.ActivateBestChain(state, block, m_node.avalanche.get()));
2237 // It is a valid block so the tip is updated
2238 BOOST_CHECK_EQUAL(chainstate.m_chain.Tip(), blockindex);
2239
2240 // Check the block is added to the poll
2241 auto invs = AvalancheTest::getInvsForNextPoll(*m_node.avalanche);
2242 BOOST_CHECK_EQUAL(invs.size(), 1);
2243 BOOST_CHECK_EQUAL(invs[0].type, MSG_BLOCK);
2244 BOOST_CHECK_EQUAL(invs[0].hash, blockhash);
2245
2246 // This block is our new tip so we should vote "yes"
2247 BOOST_CHECK(m_node.avalanche->isAccepted(blockindex));
2248}
2249
2250BOOST_AUTO_TEST_CASE(compute_staking_rewards) {
2251 auto now = GetTime<std::chrono::seconds>();
2252 SetMockTime(now);
2253
2254 // Pick in the middle
2255 BlockHash prevBlockHash{uint256::ZERO};
2256
2257 std::vector<CScript> winners;
2258
2260 !m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2261
2262 // Null index
2263 BOOST_CHECK(!m_node.avalanche->computeStakingReward(nullptr));
2265 !m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2266
2267 CBlockIndex prevBlock;
2268 prevBlock.phashBlock = &prevBlockHash;
2269 prevBlock.nHeight = 100;
2270 prevBlock.nTime = now.count();
2271
2272 // No quorum
2273 BOOST_CHECK(!m_node.avalanche->computeStakingReward(&prevBlock));
2275 !m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2276
2277 // Setup a bunch of proofs
2278 size_t numProofs = 10;
2279 std::vector<ProofRef> proofs;
2280 proofs.reserve(numProofs);
2281 for (size_t i = 0; i < numProofs; i++) {
2282 const CKey key = CKey::MakeCompressedKey();
2283 CScript payoutScript = GetScriptForRawPubKey(key.GetPubKey());
2284
2285 auto proof = GetProof(payoutScript);
2286 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2287 BOOST_CHECK(pm.registerProof(proof));
2288 BOOST_CHECK(pm.addNode(i, proof->getId(),
2290 // Finalize the proof
2291 BOOST_CHECK(pm.forPeer(proof->getId(), [&](const Peer peer) {
2292 return pm.setFinalized(peer.peerid);
2293 }));
2294 });
2295
2296 proofs.emplace_back(std::move(proof));
2297 }
2298
2299 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
2300
2301 // Proofs are too recent so we still have no winner
2302 BOOST_CHECK(!m_node.avalanche->computeStakingReward(&prevBlock));
2304 !m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2305
2306 // Make sure we picked a payout script from one of our proofs
2307 auto winnerExists = [&](const CScript &expectedWinner) {
2308 const std::string winnerString = FormatScript(expectedWinner);
2309
2310 for (const ProofRef &proof : proofs) {
2311 if (winnerString == FormatScript(proof->getPayoutScript())) {
2312 return true;
2313 }
2314 }
2315 return false;
2316 };
2317
2318 // Elapse some time
2319 now += 1h + 1s;
2320 SetMockTime(now);
2321 prevBlock.nTime = now.count();
2322
2323 // Now we successfully inserted a winner in our map
2324 BOOST_CHECK(m_node.avalanche->computeStakingReward(&prevBlock));
2326 m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2327 BOOST_CHECK(winnerExists(winners[0]));
2328
2329 // Subsequent calls are a no-op
2330 BOOST_CHECK(m_node.avalanche->computeStakingReward(&prevBlock));
2332 m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2333 BOOST_CHECK(winnerExists(winners[0]));
2334
2335 CBlockIndex prevBlockHigh = prevBlock;
2336 BlockHash prevBlockHashHigh =
2337 BlockHash(ArithToUint256({std::numeric_limits<uint64_t>::max()}));
2338 prevBlockHigh.phashBlock = &prevBlockHashHigh;
2339 prevBlockHigh.nHeight = 101;
2340 BOOST_CHECK(m_node.avalanche->computeStakingReward(&prevBlockHigh));
2342 m_node.avalanche->getStakingRewardWinners(prevBlockHashHigh, winners));
2343 BOOST_CHECK(winnerExists(winners[0]));
2344
2345 // No impact on previous winner so far
2347 m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2348 BOOST_CHECK(winnerExists(winners[0]));
2349
2350 // Cleanup to height 101
2351 m_node.avalanche->cleanupStakingRewards(101);
2352
2353 // Now the previous winner has been cleared
2355 !m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2356
2357 // But the last one remain
2359 m_node.avalanche->getStakingRewardWinners(prevBlockHashHigh, winners));
2360 BOOST_CHECK(winnerExists(winners[0]));
2361
2362 // We can add it again
2363 BOOST_CHECK(m_node.avalanche->computeStakingReward(&prevBlock));
2365 m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2366 BOOST_CHECK(winnerExists(winners[0]));
2367
2368 // Cleanup to higher height
2369 m_node.avalanche->cleanupStakingRewards(200);
2370
2371 // No winner anymore
2373 !m_node.avalanche->getStakingRewardWinners(prevBlockHash, winners));
2375 !m_node.avalanche->getStakingRewardWinners(prevBlockHashHigh, winners));
2376}
2377
2378BOOST_AUTO_TEST_CASE(local_proof_status) {
2379 const CKey key = CKey::MakeCompressedKey();
2380
2381 const COutPoint outpoint{TxId(GetRandHash()), 0};
2382 {
2384
2385 LOCK(cs_main);
2386 CCoinsViewCache &coins =
2387 Assert(m_node.chainman)->ActiveChainstate().CoinsTip();
2388 coins.AddCoin(outpoint,
2389 Coin(CTxOut(PROOF_DUST_THRESHOLD, script), 100, false),
2390 false);
2391 }
2392
2393 auto buildProof = [&](const COutPoint &outpoint, uint64_t sequence,
2394 uint32_t height) {
2395 ProofBuilder pb(sequence, 0, key, UNSPENDABLE_ECREG_PAYOUT_SCRIPT);
2397 pb.addUTXO(outpoint, PROOF_DUST_THRESHOLD, height, false, key));
2398 return pb.build();
2399 };
2400
2401 auto localProof = buildProof(outpoint, 1, 100);
2402
2403 setArg("-avamasterkey", EncodeSecret(key));
2404 setArg("-avaproof", localProof->ToHex());
2405 setArg("-avalancheconflictingproofcooldown", "0");
2406 setArg("-avalanchepeerreplacementcooldown", "0");
2407 setArg("-avaproofstakeutxoconfirmations", "3");
2408
2410 bilingual_str error;
2411 ChainstateManager &chainman = *Assert(m_node.chainman);
2412 m_node.avalanche = Processor::MakeProcessor(
2413 *m_node.args, *m_node.chain, m_node.connman.get(), chainman,
2414 m_node.mempool.get(), *m_node.scheduler, error);
2415
2416 BOOST_CHECK_EQUAL(m_node.avalanche->getLocalProof()->getId(),
2417 localProof->getId());
2418
2419 auto checkLocalProofState = [&](const bool boundToPeer,
2421 expectedResult) {
2423 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2424 return pm.isBoundToPeer(localProof->getId());
2425 }),
2426 boundToPeer);
2427 BOOST_CHECK_MESSAGE(
2428 m_node.avalanche->getLocalProofRegistrationState().GetResult() ==
2429 expectedResult,
2430 m_node.avalanche->getLocalProofRegistrationState().ToString());
2431 };
2432
2433 checkLocalProofState(false, ProofRegistrationResult::NONE);
2434
2435 // Not ready to share, the local proof isn't registered
2436 BOOST_CHECK(!m_node.avalanche->canShareLocalProof());
2437 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2438 checkLocalProofState(false, ProofRegistrationResult::NONE);
2439
2440 // Ready to share, but the proof is immature
2441 AvalancheTest::setLocalProofShareable(*m_node.avalanche, true);
2442 BOOST_CHECK(m_node.avalanche->canShareLocalProof());
2443 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2444 checkLocalProofState(false, ProofRegistrationResult::IMMATURE);
2445
2446 // Mine a block to re-evaluate the proof, it remains immature
2447 mineBlocks(1);
2448 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2449 checkLocalProofState(false, ProofRegistrationResult::IMMATURE);
2450
2451 // One more block and the proof turns mature
2452 mineBlocks(1);
2453 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2454 checkLocalProofState(true, ProofRegistrationResult::NONE);
2455
2456 // Build a conflicting proof and check the status is updated accordingly
2457 auto conflictingProof = buildProof(outpoint, 2, 100);
2458 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2459 BOOST_CHECK(pm.registerProof(conflictingProof));
2460 BOOST_CHECK(pm.isBoundToPeer(conflictingProof->getId()));
2461 BOOST_CHECK(pm.isInConflictingPool(localProof->getId()));
2462 });
2463 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2464 checkLocalProofState(false, ProofRegistrationResult::CONFLICTING);
2465}
2466
2467BOOST_AUTO_TEST_CASE(reconcileOrFinalize) {
2468 setArg("-avalancheconflictingproofcooldown", "0");
2469 setArg("-avalanchepeerreplacementcooldown", "0");
2470
2471 // Proof is null
2472 BOOST_CHECK(!m_node.avalanche->reconcileOrFinalize(ProofRef()));
2473
2474 ChainstateManager &chainman = *Assert(m_node.chainman);
2475 Chainstate &activeChainState = chainman.ActiveChainstate();
2476
2477 const CKey key = CKey::MakeCompressedKey();
2478 const COutPoint outpoint{TxId(GetRandHash()), 0};
2479 {
2481
2482 LOCK(cs_main);
2483 CCoinsViewCache &coins = activeChainState.CoinsTip();
2484 coins.AddCoin(outpoint,
2485 Coin(CTxOut(PROOF_DUST_THRESHOLD, script), 100, false),
2486 false);
2487 }
2488
2489 auto buildProof = [&](const COutPoint &outpoint, uint64_t sequence) {
2490 ProofBuilder pb(sequence, 0, key, UNSPENDABLE_ECREG_PAYOUT_SCRIPT);
2492 pb.addUTXO(outpoint, PROOF_DUST_THRESHOLD, 100, false, key));
2493 return pb.build();
2494 };
2495
2496 auto proof = buildProof(outpoint, 1);
2497 BOOST_CHECK(proof);
2498
2499 // Not a peer nor conflicting
2500 BOOST_CHECK(!m_node.avalanche->reconcileOrFinalize(proof));
2501
2502 // Register the proof
2503 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2504 BOOST_CHECK(pm.registerProof(proof));
2505 BOOST_CHECK(pm.isBoundToPeer(proof->getId()));
2506 BOOST_CHECK(!pm.isInConflictingPool(proof->getId()));
2507 });
2508
2509 // Reconcile works
2510 BOOST_CHECK(m_node.avalanche->reconcileOrFinalize(proof));
2511 // Repeated calls fail and do nothing
2512 BOOST_CHECK(!m_node.avalanche->reconcileOrFinalize(proof));
2513
2514 // Finalize
2515 AvalancheTest::addProofToRecentfinalized(*m_node.avalanche, proof->getId());
2516 BOOST_CHECK(m_node.avalanche->isRecentlyFinalized(proof->getId()));
2517 BOOST_CHECK(m_node.avalanche->reconcileOrFinalize(proof));
2518
2519 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2520 // The peer is marked as final
2521 BOOST_CHECK(pm.forPeer(proof->getId(), [&](const Peer &peer) {
2522 return peer.hasFinalized;
2523 }));
2524 BOOST_CHECK(pm.isBoundToPeer(proof->getId()));
2525 BOOST_CHECK(!pm.isInConflictingPool(proof->getId()));
2526 });
2527
2528 // Same proof with a higher sequence number
2529 auto betterProof = buildProof(outpoint, 2);
2530 BOOST_CHECK(betterProof);
2531
2532 // Not registered nor conflicting yet
2533 BOOST_CHECK(!m_node.avalanche->reconcileOrFinalize(betterProof));
2534
2535 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2536 BOOST_CHECK(pm.registerProof(betterProof));
2537 BOOST_CHECK(pm.isBoundToPeer(betterProof->getId()));
2538 BOOST_CHECK(!pm.isInConflictingPool(betterProof->getId()));
2539
2540 BOOST_CHECK(!pm.isBoundToPeer(proof->getId()));
2542 });
2543
2544 // Recently finalized, not worth polling
2545 BOOST_CHECK(!m_node.avalanche->reconcileOrFinalize(proof));
2546 // But the better proof can be polled
2547 BOOST_CHECK(m_node.avalanche->reconcileOrFinalize(betterProof));
2548}
2549
2550BOOST_AUTO_TEST_CASE(stake_contenders) {
2552 bilingual_str error;
2553 m_node.avalanche = Processor::MakeProcessor(
2554 *m_node.args, *m_node.chain, m_node.connman.get(),
2555 *Assert(m_node.chainman), m_node.mempool.get(), *m_node.scheduler,
2556 error);
2557 BOOST_CHECK(m_node.avalanche);
2558
2559 auto now = GetTime<std::chrono::seconds>();
2560 SetMockTime(now);
2561
2562 AvalancheTest::setStakingPreconsensus(*m_node.avalanche, true);
2563
2564 ChainstateManager &chainman = *Assert(m_node.chainman);
2565 Chainstate &active_chainstate = chainman.ActiveChainstate();
2566 CBlockIndex *chaintip =
2567 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
2568
2569 auto proof1 = buildRandomProof(active_chainstate, MIN_VALID_PROOF_SCORE);
2570 const ProofId proofid1 = proof1->getId();
2571 const StakeContenderId contender1_block1(chaintip->GetBlockHash(),
2572 proofid1);
2573
2574 auto proof2 = buildRandomProof(active_chainstate, MIN_VALID_PROOF_SCORE);
2575 const ProofId proofid2 = proof2->getId();
2576 const StakeContenderId contender2_block1(chaintip->GetBlockHash(),
2577 proofid2);
2578
2579 // Add stake contenders. Without computing staking rewards, the status is
2580 // pending.
2581 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2582 pm.addStakeContender(proof1);
2583 pm.addStakeContender(proof2);
2584 });
2586 m_node.avalanche->getStakeContenderStatus(contender1_block1), -2);
2588 m_node.avalanche->getStakeContenderStatus(contender2_block1), -2);
2589
2590 // Sanity check unknown contender
2591 const StakeContenderId unknownContender(chaintip->GetBlockHash(),
2592 ProofId(GetRandHash()));
2594 m_node.avalanche->getStakeContenderStatus(unknownContender), -1);
2595
2596 // Register proof2 and save it as a remote proof so that it will be promoted
2597 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2598 pm.registerProof(proof2);
2599 for (NodeId n = 0; n < 8; n++) {
2601 }
2602 pm.saveRemoteProof(proofid2, 0, true);
2603 BOOST_CHECK(pm.forPeer(proofid2, [&](const Peer peer) {
2604 return pm.setFinalized(peer.peerid);
2605 }));
2606 });
2607
2608 // Make proofs old enough to be considered for staking rewards
2609 now += 1h + 1s;
2610 SetMockTime(now);
2611
2612 // Advance chaintip
2613 CBlock block = CreateAndProcessBlock({}, CScript());
2614 chaintip =
2615 WITH_LOCK(cs_main, return Assert(m_node.chainman)
2616 ->m_blockman.LookupBlockIndex(block.GetHash()));
2617 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2618
2619 // Compute local stake winner
2620 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
2621 BOOST_CHECK(m_node.avalanche->computeStakingReward(chaintip));
2622 {
2623 std::vector<CScript> winners;
2624 BOOST_CHECK(m_node.avalanche->getStakingRewardWinners(
2625 chaintip->GetBlockHash(), winners));
2626 BOOST_CHECK_EQUAL(winners.size(), 1);
2627 BOOST_CHECK(winners[0] == proof2->getPayoutScript());
2628 }
2629
2630 // Sanity check unknown contender
2632 m_node.avalanche->getStakeContenderStatus(unknownContender), -1);
2633
2634 // Old contender cache entries unaffected
2636 m_node.avalanche->getStakeContenderStatus(contender1_block1), -2);
2638 m_node.avalanche->getStakeContenderStatus(contender2_block1), -2);
2639
2640 // contender1 was not promoted
2641 const StakeContenderId contender1_block2 =
2642 StakeContenderId(chaintip->GetBlockHash(), proofid1);
2644 m_node.avalanche->getStakeContenderStatus(contender1_block2), -1);
2645
2646 // contender2 was promoted
2647 const StakeContenderId contender2_block2 =
2648 StakeContenderId(chaintip->GetBlockHash(), proofid2);
2650 m_node.avalanche->getStakeContenderStatus(contender2_block2), 0);
2651
2652 // Now that the finalization point has passed the block where contender1 was
2653 // added, cleaning up the cache will remove its entry. contender2 will have
2654 // its old entry cleaned up, but the promoted one remains.
2655 m_node.avalanche->cleanupStakingRewards(chaintip->nHeight);
2656
2658 m_node.avalanche->getStakeContenderStatus(unknownContender), -1);
2659
2661 m_node.avalanche->getStakeContenderStatus(contender1_block1), -1);
2663 m_node.avalanche->getStakeContenderStatus(contender1_block2), -1);
2664
2666 m_node.avalanche->getStakeContenderStatus(contender2_block1), -1);
2668 m_node.avalanche->getStakeContenderStatus(contender2_block2), 0);
2669
2670 // Manually set contenders as winners
2671 m_node.avalanche->setStakingRewardWinners(
2672 chaintip, {proof1->getPayoutScript(), proof2->getPayoutScript()});
2673 // contender1 has been forgotten, which is expected. When a proof becomes
2674 // invalid and is cleaned up from the cache, we do not expect peers to poll
2675 // for it any more.
2677 m_node.avalanche->getStakeContenderStatus(contender1_block2), -1);
2678 // contender2 is a winner despite avalanche not finalizing it
2680 m_node.avalanche->getStakeContenderStatus(contender2_block2), 0);
2681
2682 // Reject proof2, mine a new chain tip, finalize it, and cleanup the cache
2683 m_node.avalanche->withPeerManager(
2684 [&](avalanche::PeerManager &pm) { pm.rejectProof(proofid2); });
2685
2686 // Reestablish quorum with a new proof
2687 BOOST_CHECK(!m_node.avalanche->isQuorumEstablished());
2688 auto proof3 = buildRandomProof(active_chainstate, MIN_VALID_PROOF_SCORE);
2689 const ProofId proofid3 = proof3->getId();
2690 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2691 pm.registerProof(proof3);
2692 for (NodeId n = 0; n < 8; n++) {
2694 }
2695 });
2696 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
2697
2698 block = CreateAndProcessBlock({}, CScript());
2699 chaintip =
2700 WITH_LOCK(cs_main, return Assert(m_node.chainman)
2701 ->m_blockman.LookupBlockIndex(block.GetHash()));
2702 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2703 m_node.avalanche->cleanupStakingRewards(chaintip->nHeight);
2704
2706 m_node.avalanche->getStakeContenderStatus(unknownContender), -1);
2707
2708 // Old entries were cleaned up
2710 m_node.avalanche->getStakeContenderStatus(contender1_block2), -1);
2712 m_node.avalanche->getStakeContenderStatus(contender2_block2), -1);
2713
2714 // Neither contender was promoted and contender2 was cleaned up even though
2715 // it was once a manual winner.
2716 const StakeContenderId contender1_block3 =
2717 StakeContenderId(chaintip->GetBlockHash(), proofid1);
2719 m_node.avalanche->getStakeContenderStatus(contender1_block3), -1);
2720 const StakeContenderId contender2_block3 =
2721 StakeContenderId(chaintip->GetBlockHash(), proofid2);
2723 m_node.avalanche->getStakeContenderStatus(contender2_block3), -1);
2724
2725 // Reject proof3 so it does not conflict with the rest of the test
2726 m_node.avalanche->withPeerManager(
2727 [&](avalanche::PeerManager &pm) { pm.rejectProof(proofid3); });
2728
2729 // Generate a bunch of flaky proofs
2730 size_t numProofs = 8;
2731 std::vector<ProofRef> proofs;
2732 proofs.reserve(numProofs);
2733 for (size_t i = 0; i < numProofs; i++) {
2734 auto proof = buildRandomProof(active_chainstate, MIN_VALID_PROOF_SCORE);
2735 const ProofId proofid = proof->getId();
2736 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2737 // Registering the proof adds it as a contender
2738 pm.registerProof(proof);
2739 // Make it a remote proof so that it will be promoted
2740 pm.saveRemoteProof(proofid, i, true);
2741 BOOST_CHECK(pm.forPeer(proofid, [&](const Peer peer) {
2742 return pm.setFinalized(peer.peerid);
2743 }));
2744 });
2745 proofs.emplace_back(std::move(proof));
2746 }
2747
2748 // Add nodes only for the first proof so we have a quorum
2749 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2750 const ProofId proofid = proofs[0]->getId();
2751 for (NodeId n = 0; n < 8; n++) {
2753 }
2754 });
2755
2756 // Make proofs old enough to be considered for staking rewards
2757 now += 1h + 1s;
2758 SetMockTime(now);
2759
2760 // Try a few times in case the non-flaky proof get selected as winner
2761 std::vector<CScript> winners;
2762 for (int attempt = 0; attempt < 10; attempt++) {
2763 // Advance chaintip so the proofs are older than the last block time
2764 block = CreateAndProcessBlock({}, CScript());
2765 chaintip = WITH_LOCK(
2766 cs_main, return Assert(m_node.chainman)
2767 ->m_blockman.LookupBlockIndex(block.GetHash()));
2768 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2769
2770 // Compute local stake winner
2771 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
2772 BOOST_CHECK(m_node.avalanche->computeStakingReward(chaintip));
2773 BOOST_CHECK(m_node.avalanche->getStakingRewardWinners(
2774 chaintip->GetBlockHash(), winners));
2775 if (winners.size() == 8) {
2776 break;
2777 }
2778 }
2779
2780 BOOST_CHECK(winners.size() == 8);
2781
2782 // Verify that all winners were accepted
2783 size_t numAccepted = 0;
2784 for (const auto &proof : proofs) {
2785 const ProofId proofid = proof->getId();
2786 const StakeContenderId contender =
2787 StakeContenderId(chaintip->GetBlockHash(), proofid);
2788 if (m_node.avalanche->getStakeContenderStatus(contender) == 0) {
2789 numAccepted++;
2790 BOOST_CHECK(std::find(winners.begin(), winners.end(),
2791 proof->getPayoutScript()) != winners.end());
2792 }
2793 }
2794 BOOST_CHECK_EQUAL(winners.size(), numAccepted);
2795
2796 // Check that a highest ranking contender that was not selected as local
2797 // winner is still accepted.
2798 block = CreateAndProcessBlock({}, CScript());
2799 chaintip =
2800 WITH_LOCK(cs_main, return Assert(m_node.chainman)
2801 ->m_blockman.LookupBlockIndex(block.GetHash()));
2802 auto bestproof = buildRandomProof(
2803 active_chainstate,
2804 // Subtract some score so totalPeersScore doesn't overflow
2805 std::numeric_limits<uint32_t>::max() - MIN_VALID_PROOF_SCORE * 8);
2806 m_node.avalanche->withPeerManager(
2807 [&](avalanche::PeerManager &pm) { pm.addStakeContender(bestproof); });
2808 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2809
2810 // Compute local stake winners
2811 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
2812 BOOST_CHECK(m_node.avalanche->computeStakingReward(chaintip));
2813 BOOST_CHECK(m_node.avalanche->getStakingRewardWinners(
2814 chaintip->GetBlockHash(), winners));
2815
2816 // Sanity check bestproof was not selected as a winner
2817 BOOST_CHECK(std::find(winners.begin(), winners.end(),
2818 bestproof->getPayoutScript()) == winners.end());
2819
2820 // Best contender is accepted
2821 {
2822 const StakeContenderId bestcontender =
2823 StakeContenderId(chaintip->GetBlockHash(), bestproof->getId());
2825 m_node.avalanche->getStakeContenderStatus(bestcontender), 0);
2826 }
2827
2828 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2829 // Register bestproof so it will become dangling later
2830 pm.registerProof(bestproof);
2831 // Make it a remote proof so that it will be promoted
2832 pm.saveRemoteProof(bestproof->getId(), 0, true);
2833 pm.saveRemoteProof(bestproof->getId(), 1, false);
2834 });
2835
2836 block = CreateAndProcessBlock({}, CScript());
2837 chaintip =
2838 WITH_LOCK(cs_main, return Assert(m_node.chainman)
2839 ->m_blockman.LookupBlockIndex(block.GetHash()));
2840 AvalancheTest::updatedBlockTip(*m_node.avalanche);
2841 AvalancheTest::setFinalizationTip(*m_node.avalanche, chaintip);
2842 m_node.avalanche->cleanupStakingRewards(chaintip->nHeight);
2843
2844 // Make bestproof dangling since it has no nodes attached
2845 now += 15min + 1s;
2846 SetMockTime(now);
2847 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2848 std::unordered_set<ProofRef, SaltedProofHasher> dummy;
2849 pm.cleanupDanglingProofs(dummy);
2850 });
2851 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2852 BOOST_CHECK(pm.isDangling(bestproof->getId()));
2853 });
2854
2855 // Compute local stake winners
2856 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
2857 BOOST_CHECK(m_node.avalanche->computeStakingReward(chaintip));
2858 BOOST_CHECK(m_node.avalanche->getStakingRewardWinners(
2859 chaintip->GetBlockHash(), winners));
2860
2861 // Sanity check bestproof was not selected as a winner
2862 BOOST_CHECK(std::find(winners.begin(), winners.end(),
2863 bestproof->getPayoutScript()) == winners.end());
2864
2865 // Best contender is still accepted because it is a high ranking contender
2866 // with a remote proof
2867 {
2868 const StakeContenderId bestcontender =
2869 StakeContenderId(chaintip->GetBlockHash(), bestproof->getId());
2871 m_node.avalanche->getStakeContenderStatus(bestcontender), 0);
2872 }
2873}
2874
2875BOOST_AUTO_TEST_CASE(stake_contender_local_winners) {
2876 ChainstateManager &chainman = *Assert(m_node.chainman);
2877 Chainstate &active_chainstate = chainman.ActiveChainstate();
2878 CBlockIndex *chaintip =
2879 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
2880 const BlockHash chaintipHash = chaintip->GetBlockHash();
2881
2882 auto now = GetTime<std::chrono::seconds>();
2883 SetMockTime(now);
2884
2885 // Create a proof that will be the local stake winner
2886 auto localWinnerProof =
2887 buildRandomProof(active_chainstate, MIN_VALID_PROOF_SCORE);
2888 ProofId localWinnerProofId = localWinnerProof->getId();
2889 const StakeContenderId localWinnerContenderId(chaintipHash,
2890 localWinnerProof->getId());
2891 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2892 pm.addStakeContender(localWinnerProof);
2893 });
2894
2895 // Prepare the proof so that it becomes the local stake winner
2896 m_node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
2897 ConnectNode(NODE_AVALANCHE);
2898 pm.registerProof(localWinnerProof);
2899 for (NodeId n = 0; n < 8; n++) {
2900 pm.addNode(n, localWinnerProofId,
2902 }
2903 BOOST_CHECK(pm.forPeer(localWinnerProofId, [&](const Peer peer) {
2904 return pm.setFinalized(peer.peerid);
2905 }));
2906 });
2907
2908 // Make proof old enough to be considered for staking rewards
2909 now += 1h + 1s;
2910 SetMockTime(now);
2911 chaintip->nTime = now.count();
2912
2913 // Compute local stake winner
2914 BOOST_CHECK(m_node.avalanche->isQuorumEstablished());
2915 BOOST_CHECK(m_node.avalanche->computeStakingReward(chaintip));
2916
2917 std::vector<ProofRef> acceptedContenderProofs;
2918 acceptedContenderProofs.push_back(localWinnerProof);
2919 double bestRank =
2920 localWinnerContenderId.ComputeProofRewardRank(MIN_VALID_PROOF_SCORE);
2921
2922 // Test well past the max since we need to test the max number of accepted
2923 // contenders as well. Starts at 2 because the local winner is already
2924 // added.
2925 for (size_t numContenders = 2;
2926 numContenders < AVALANCHE_CONTENDER_MAX_POLLABLE * 10;
2927 numContenders++) {
2928 auto proof = buildRandomProof(active_chainstate, MIN_VALID_PROOF_SCORE);
2929 m_node.avalanche->withPeerManager(
2930 [&](avalanche::PeerManager &pm) { pm.addStakeContender(proof); });
2931
2932 const StakeContenderId contenderId(chaintipHash, proof->getId());
2933 double rank = contenderId.ComputeProofRewardRank(MIN_VALID_PROOF_SCORE);
2934
2935 if (rank <= bestRank) {
2936 bestRank = rank;
2937 acceptedContenderProofs.push_back(proof);
2938 const size_t numAccepted =
2940 acceptedContenderProofs.size());
2941 std::sort(acceptedContenderProofs.begin(),
2942 acceptedContenderProofs.begin() + numAccepted,
2943 [&](const ProofRef &left, const ProofRef &right) {
2944 const ProofId leftProofId = left->getId();
2945 const ProofId rightProofId = right->getId();
2946 const StakeContenderId leftContenderId(chaintipHash,
2947 leftProofId);
2948 const StakeContenderId rightContenderId(chaintipHash,
2949 rightProofId);
2950 return RewardRankComparator()(
2951 leftContenderId,
2952 leftContenderId.ComputeProofRewardRank(
2953 MIN_VALID_PROOF_SCORE),
2954 leftProofId, rightContenderId,
2955 rightContenderId.ComputeProofRewardRank(
2956 MIN_VALID_PROOF_SCORE),
2957 rightProofId);
2958 });
2959 }
2960
2961 std::vector<StakeContenderId> pollableContenders;
2962 BOOST_CHECK(AvalancheTest::setContenderStatusForLocalWinners(
2963 *m_node.avalanche, chaintip, pollableContenders));
2965 pollableContenders.size(),
2966 std::min(numContenders, AVALANCHE_CONTENDER_MAX_POLLABLE));
2967
2968 // Accepted contenders (up to the max, best first) are always included
2969 // in pollableContenders
2970 for (size_t i = 0; i < std::min(acceptedContenderProofs.size(),
2972 i++) {
2973 StakeContenderId acceptedContenderId = StakeContenderId(
2974 chaintipHash, acceptedContenderProofs[i]->getId());
2976 std::find(pollableContenders.begin(), pollableContenders.end(),
2977 acceptedContenderId) != pollableContenders.end());
2979 m_node.avalanche->getStakeContenderStatus(acceptedContenderId),
2980 0);
2981 }
2982
2983 // Check unaccepted contenders are still as we expect
2984 std::set<StakeContenderId> unacceptedContenderIds(
2985 pollableContenders.begin(), pollableContenders.end());
2986 for (auto &acceptedContenderProof : acceptedContenderProofs) {
2987 const StakeContenderId acceptedContenderId(
2988 chaintipHash, acceptedContenderProof->getId());
2989 unacceptedContenderIds.erase(acceptedContenderId);
2990 }
2991
2992 for (auto cid : unacceptedContenderIds) {
2993 BOOST_CHECK_EQUAL(m_node.avalanche->getStakeContenderStatus(cid),
2994 1);
2995 }
2996
2997 // Sanity check the local winner stays accepted
2999 m_node.avalanche->getStakeContenderStatus(localWinnerContenderId),
3000 0);
3001 }
3002}
3003
3004BOOST_AUTO_TEST_SUITE_END()
static constexpr Amount SATOSHI
Definition: amount.h:148
static constexpr Amount COIN
Definition: amount.h:149
uint256 ArithToUint256(const arith_uint256 &a)
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
#define Assert(val)
Identity function.
Definition: check.h:84
A CService with information about it as peer.
Definition: protocol.h:442
BlockHash GetHash() const
Definition: block.cpp:11
Definition: block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:29
uint32_t nTime
Definition: blockindex.h:76
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
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:154
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:358
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:98
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:174
An encapsulated secp256k1 private key.
Definition: key.h:28
static CKey MakeCompressedKey()
Produce a valid compressed key.
Definition: key.cpp:465
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:209
A mutable version of CTransaction.
Definition: transaction.h:274
std::vector< CTxOut > vout
Definition: transaction.h:277
std::vector< CTxIn > vin
Definition: transaction.h:276
Network address.
Definition: netaddress.h:114
Information about a peer.
Definition: net.h:395
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
void serviceQueue() EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Services the queue 'forever'.
Definition: scheduler.cpp:24
size_t getQueueInfo(std::chrono::steady_clock::time_point &first, std::chrono::steady_clock::time_point &last) const EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Returns number of tasks waiting to be serviced, and first and last task times.
Definition: scheduler.cpp:121
void StopWhenDrained() EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Tell any threads running serviceQueue to stop when there is no work left to be done.
Definition: scheduler.h:100
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:573
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
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:269
bool exists(const TxId &txid) const
Definition: txmempool.h:535
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void addUnchecked(CTxMemPoolEntryRef entry) EXCLUSIVE_LOCKS_REQUIRED(cs
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.h:382
An output of a transaction.
Definition: transaction.h:128
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:739
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Find the best known block, and make it the tip of the block chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:838
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:865
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1191
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1442
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1323
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1449
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Sufficiently validate a block for disk storage (and store on disk).
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1332
A UTXO entry.
Definition: coins.h:31
Fast randomness source.
Definition: random.h:411
ReadView getReadView() const
Definition: rwcollection.h:76
WriteView getWriteView()
Definition: rwcollection.h:82
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:266
256-bit unsigned big integer.
bool removeNode(NodeId nodeid)
uint32_t getConnectedPeersScore() const
Definition: peermanager.h:449
bool isDangling(const ProofId &proofid) const
bool addNode(NodeId nodeid, const ProofId &proofid, size_t max_elements)
Node API.
Definition: peermanager.cpp:33
bool exists(const ProofId &proofid) const
Return true if the (valid) proof exists, but only for non-dangling proofs.
Definition: peermanager.h:413
bool forPeer(const ProofId &proofid, Callable &&func) const
Definition: peermanager.h:421
uint32_t getTotalPeersScore() const
Definition: peermanager.h:448
std::unordered_set< ProofRef, SaltedProofHasher > updatedBlockTip()
Update the peer set when a new block is connected.
bool isBoundToPeer(const ProofId &proofid) const
bool saveRemoteProof(const ProofId &proofid, const NodeId nodeid, const bool present)
bool isImmature(const ProofId &proofid) const
bool rejectProof(const ProofId &proofid, RejectionMode mode=RejectionMode::DEFAULT)
void addStakeContender(const ProofRef &proof)
bool isInConflictingPool(const ProofId &proofid) const
void cleanupDanglingProofs(std::unordered_set< ProofRef, SaltedProofHasher > &registeredProofs)
bool registerProof(const ProofRef &proof, ProofRegistrationState &registrationState, RegistrationMode mode=RegistrationMode::DEFAULT)
Mutex cs_finalizedItems
Rolling bloom filter to track recently finalized inventory items of any type.
Definition: processor.h:473
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:1157
std::atomic< uint64_t > round
Keep track of peers and queries sent.
Definition: processor.h:182
void runEventLoop() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1230
void updatedBlockTip() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1169
RWCollection< VoteMap > voteRecords
Items to run avalanche on.
Definition: processor.h:177
uint32_t minQuorumScore
Quorum management.
Definition: processor.h:231
std::atomic< bool > m_canShareLocalProof
Definition: processor.h:234
std::vector< CInv > getInvsForNextPoll(RWCollection< VoteMap >::ReadView &voteRecordsReadView, size_t max_elements, bool forPoll=true) const
Definition: processor.cpp:1368
std::atomic< int64_t > avaproofsNodeCounter
Definition: processor.h:236
std::atomic_bool m_stakingPreConsensus
Definition: processor.h:279
Mutex cs_peerManager
Keep track of the peers and associated infos.
Definition: processor.h:187
void clearInvsNotWorthPolling() EXCLUSIVE_LOCKS_REQUIRED(!cs_peerManager
Definition: processor.cpp:1318
double minQuorumConnectedScoreRatio
Definition: processor.h:232
bool addUTXO(COutPoint utxo, Amount amount, uint32_t height, bool is_coinbase, CKey key)
const CScript & getPayoutScript() const
Definition: proof.h:164
const ProofId & getId() const
Definition: proof.h:167
const std::vector< SignedStake > & getStakes() const
Definition: proof.h:163
uint32_t getCooldown() const
Definition: protocol.h:45
const std::vector< Vote > & GetVotes() const
Definition: protocol.h:46
uint64_t getRound() const
Definition: protocol.h:44
const AnyVoteItem & getVoteItem() const
Definition: processor.h:115
const VoteStatus & getStatus() const
Definition: processor.h:114
static constexpr unsigned int size()
Definition: uint256.h:93
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
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
std::string FormatScript(const CScript &script)
Definition: core_write.cpp:24
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::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:102
@ NONE
Definition: logging.h:68
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
Definition: proof.h:38
ProofRegistrationResult
Definition: peermanager.h:144
std::variant< const ProofRef, const CBlockIndex *, const StakeContenderId, const CTransactionRef > AnyVoteItem
Definition: processor.h:104
const CScript UNSPENDABLE_ECREG_PAYOUT_SCRIPT
Definition: util.h:22
ProofRef buildRandomProof(Chainstate &active_chainstate, uint32_t score, int height, const CKey &masterKey)
Definition: util.cpp:20
constexpr uint32_t MIN_VALID_PROOF_SCORE
Definition: util.h:20
Definition: messages.h:12
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:150
NodeContext & m_node
Definition: interfaces.cpp:820
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
Definition: nodeid.h:15
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:316
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
Response response
Definition: processor.cpp:536
static constexpr size_t DEFAULT_AVALANCHE_MAX_ELEMENT_POLL
Maximum item that can be polled at once.
Definition: processor.h:55
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:69
static constexpr uint32_t AVALANCHE_FINALIZED_ITEMS_FILTER_NUM_ELEMENTS
The size of the finalized items filter.
Definition: processor.h:85
BOOST_AUTO_TEST_CASE_TEMPLATE(voteitemupdate, P, VoteItemProviders)
BOOST_AUTO_TEST_CASE(quorum_diversity)
boost::mpl::list< BlockProvider, ProofProvider, StakeContenderProvider, TxProvider > VoteItemProviders
boost::mpl::list< StakeContenderProvider > Uint256VoteItemProviders
boost::mpl::list< BlockProvider, ProofProvider, TxProvider > NullableVoteItemProviders
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition: protocol.h:427
@ MSG_TX
Definition: protocol.h:573
@ MSG_AVA_STAKE_CONTENDER
Definition: protocol.h:581
@ MSG_AVA_PROOF
Definition: protocol.h:580
@ MSG_BLOCK
Definition: protocol.h:574
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
@ NODE_NETWORK
Definition: protocol.h:342
@ NODE_AVALANCHE
Definition: protocol.h:380
static const int PROTOCOL_VERSION
network protocol versioning
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:512
uint256 GetRandHash() noexcept
========== CONVENIENCE FUNCTIONS FOR COMMONLY USED RANDOMNESS ==========
Definition: random.h:494
reverse_range< T > reverse_iterate(T &x)
@ OP_TRUE
Definition: script.h:61
static uint16_t GetDefaultPort()
Definition: bitcoin.h:18
static std::string ToString(const CService &ip)
Definition: db.h:36
static RPCHelpMan stop()
Definition: server.cpp:214
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:244
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
Definition: amount.h:21
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
static const Currency & get()
Definition: amount.cpp:18
A TxId is the identifier of a transaction.
Definition: txid.h:14
Compare proofs by score, then by id in case of equality.
StakeContenderIds are unique for each block to ensure that the peer polling for their acceptance has ...
double ComputeProofRewardRank(uint32_t proofScore) const
To make sure the selection is properly weighted according to the proof score, we normalize the conten...
Vote history.
Definition: voterecord.h:49
Bilingual messages:
Definition: translation.h:17
bool empty() const
Definition: translation.h:27
std::string original
Definition: translation.h:18
#define LOCK2(cs1, cs2)
Definition: sync.h:309
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:21
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:64
@ CONFLICT
Removed for conflict with in-block transaction.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static constexpr int AVALANCHE_MAX_INFLIGHT_POLL
How many inflight requests can exist for one item.
Definition: voterecord.h:40
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 int AVALANCHE_FINALIZATION_SCORE
Finalization score.
Definition: voterecord.h:17