Bitcoin ABC 0.34.5
P2P Digital Currency
Loading...
Searching...
No Matches
peermanager.cpp
Go to the documentation of this file.
1// Copyright (c) 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
12#include <cashaddrenc.h>
13#include <common/args.h>
15#include <logging.h>
16#include <random.h>
17#include <scheduler.h>
18#include <threadsafety.h>
19#include <uint256.h>
20#include <util/fastrange.h>
21#include <util/fs_helpers.h>
22#include <util/strencodings.h>
23#include <util/time.h>
24#include <validation.h> // For ChainstateManager
25
26#include <algorithm>
27#include <cassert>
28#include <limits>
29
30namespace avalanche {
31static constexpr uint64_t PEERS_DUMP_VERSION{1};
32
33bool PeerManager::addNode(NodeId nodeid, const ProofId &proofid,
34 size_t max_elements) {
35 auto &pview = peers.get<by_proofid>();
36 auto it = pview.find(proofid);
37 if (it == pview.end()) {
38 // If the node exists, it is actually updating its proof to an unknown
39 // one. In this case we need to remove it so it is not both active and
40 // pending at the same time.
41 removeNode(nodeid);
42 pendingNodes.emplace(proofid, nodeid, max_elements);
43 return false;
44 }
45
46 return addOrUpdateNode(peers.project<0>(it), nodeid, max_elements);
47}
48
49bool PeerManager::addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid,
50 size_t max_elements) {
51 assert(it != peers.end());
52
53 const PeerId peerid = it->peerid;
54
55 auto nit = nodes.find(nodeid);
56 if (nit == nodes.end()) {
57 if (!nodes.emplace(nodeid, peerid, max_elements).second) {
58 return false;
59 }
60 } else {
61 const PeerId oldpeerid = nit->peerid;
62 if (!nodes.modify(nit, [&](Node &n) { n.peerid = peerid; })) {
63 return false;
64 }
65
66 // We actually have this node already, we need to update it.
67 bool success = removeNodeFromPeer(peers.find(oldpeerid));
68 assert(success);
69 }
70
71 // Then increase the node counter, and create the slot if needed
72 bool success = addNodeToPeer(it);
73 assert(success);
74
75 // If the added node was in the pending set, remove it
76 pendingNodes.get<by_nodeid>().erase(nodeid);
77
78 // If the proof was in the dangling pool, remove it
79 const ProofId &proofid = it->getProofId();
80 if (danglingProofPool.getProof(proofid)) {
82 }
83
84 // We know for sure there is at least 1 node. Note that this can fail if
85 // there is more than 1, in this case it's a no-op.
86 shareableProofs.insert(it->proof);
87
88 return true;
89}
90
91bool PeerManager::addNodeToPeer(const PeerSet::iterator &it) {
92 assert(it != peers.end());
93 return peers.modify(it, [&](Peer &p) {
94 if (p.node_count++ > 0) {
95 // We are done.
96 return;
97 }
98
99 // We need to allocate this peer.
100 p.index = uint32_t(slots.size());
101 const uint32_t score = p.getScore();
102 const uint64_t start = slotCount;
103 slots.emplace_back(start, score, it->peerid);
104 slotCount = start + score;
105
106 // Add to our allocated score when we allocate a new peer in the slots
107 connectedPeersScore += score;
108 });
109}
110
112 // Remove all the remote proofs from this node
113 clearRemoteProofs(nodeid);
114
115 if (pendingNodes.get<by_nodeid>().erase(nodeid) > 0) {
116 // If this was a pending node, there is nothing else to do.
117 return true;
118 }
119
120 auto it = nodes.find(nodeid);
121 if (it == nodes.end()) {
122 return false;
123 }
124
125 const PeerId peerid = it->peerid;
126 nodes.erase(it);
127
128 // Keep the track of the reference count.
129 bool success = removeNodeFromPeer(peers.find(peerid));
130 assert(success);
131
132 return true;
133}
134
135bool PeerManager::removeNodeFromPeer(const PeerSet::iterator &it,
136 uint32_t count) {
137 // It is possible for nodes to be dangling. If there was an inflight query
138 // when the peer gets removed, the node was not erased. In this case there
139 // is nothing to do.
140 if (it == peers.end()) {
141 return true;
142 }
143
144 assert(count <= it->node_count);
145 if (count == 0) {
146 // This is a NOOP.
147 return false;
148 }
149
150 const uint32_t new_count = it->node_count - count;
151 if (!peers.modify(it, [&](Peer &p) { p.node_count = new_count; })) {
152 return false;
153 }
154
155 if (new_count > 0) {
156 // We are done.
157 return true;
158 }
159
160 // There are no more nodes left, we need to clean up. Remove from the radix
161 // tree (unless it's our local proof), subtract allocated score and remove
162 // from slots.
163 if (!isLocalProof(it->getProofId())) {
164 const auto removed = shareableProofs.remove(it->getProofId());
165 assert(removed);
166 }
167
168 const size_t i = it->index;
169 assert(i < slots.size());
170 assert(connectedPeersScore >= slots[i].getScore());
171 connectedPeersScore -= slots[i].getScore();
172
173 if (i + 1 == slots.size()) {
174 slots.pop_back();
175 slotCount = slots.empty() ? 0 : slots.back().getStop();
176 } else {
177 fragmentation += slots[i].getScore();
178 slots[i] = slots[i].withPeerId(NO_PEER);
179 }
180
181 return true;
182}
183
185 SteadyMilliseconds timeout,
186 uint64_t round) {
187 auto it = nodes.find(nodeid);
188 if (it == nodes.end()) {
189 return false;
190 }
191
192 return nodes.modify(it, [&](Node &n) {
193 n.nextRequestTime = timeout;
194 n.last_round = round;
195 });
196}
197
199 const Response &response) {
200 auto it = nodes.find(nodeid);
201 if (it == nodes.end()) {
202 return false;
203 }
204
205 if (it->last_round > response.getRound()) {
206 // This is a response for a previous round, ignore it.
207 return false;
208 }
209
210 auto timeout = Now<SteadyMilliseconds>() +
211 std::chrono::milliseconds(response.getCooldown());
212
213 return nodes.modify(it, [&](Node &n) {
214 n.nextRequestTime = timeout;
215 n.last_round = response.getRound();
216 });
217}
218
220 auto it = nodes.find(nodeid);
221 if (it == nodes.end()) {
222 return false;
223 }
224
225 return !it->avaproofsSent &&
226 nodes.modify(it, [&](Node &n) { n.avaproofsSent = true; });
227}
228
229static bool isImmatureState(const ProofValidationState &state) {
231}
232
234 PeerId peerid, const std::chrono::seconds &nextTime) {
235 auto it = peers.find(peerid);
236 if (it == peers.end()) {
237 // No such peer
238 return false;
239 }
240
241 // Make sure we don't move the time in the past.
242 peers.modify(it, [&](Peer &p) {
244 std::max(p.nextPossibleConflictTime, nextTime);
245 });
246
247 return it->nextPossibleConflictTime == nextTime;
248}
249
251 auto it = peers.find(peerid);
252 if (it == peers.end()) {
253 // No such peer
254 return false;
255 }
256
257 peers.modify(it, [&](Peer &p) { p.hasFinalized = true; });
258
259 return true;
260}
261
262template <typename ProofContainer>
263void PeerManager::moveToConflictingPool(const ProofContainer &proofs) {
264 auto &peersView = peers.get<by_proofid>();
265 for (const ProofRef &proof : proofs) {
266 auto it = peersView.find(proof->getId());
267 if (it != peersView.end()) {
268 removePeer(it->peerid);
269 }
270
272 }
273}
274
276 ProofRegistrationState &registrationState,
277 RegistrationMode mode) {
278 assert(proof);
279
280 const ProofId &proofid = proof->getId();
281
282 auto invalidate = [&](ProofRegistrationResult result,
283 const std::string &message) {
284 return registrationState.Invalid(
285 result, message, strprintf("proofid: %s", proofid.ToString()));
286 };
287
288 if ((mode != RegistrationMode::FORCE_ACCEPT ||
289 !isInConflictingPool(proofid)) &&
290 exists(proofid)) {
291 // In default mode, we expect the proof to be unknown, i.e. in none of
292 // the pools.
293 // In forced accept mode, the proof can be in the conflicting pool.
295 "proof-already-registered");
296 }
297
298 if (danglingProofPool.getProof(proofid) &&
299 pendingNodes.count(proofid) == 0) {
300 // Don't attempt to register a proof that we already evicted because it
301 // was dangling, but rather attempt to retrieve an associated node.
302 needMoreNodes = true;
303 return invalidate(ProofRegistrationResult::DANGLING, "dangling-proof");
304 }
305
306 // Check the proof's validity.
307 ProofValidationState validationState;
308 if (!WITH_LOCK(cs_main, return proof->verify(stakeUtxoDustThreshold,
309 chainman, validationState))) {
310 if (isImmatureState(validationState)) {
314 // Adding this proof exceeds the immature pool limit, so evict
315 // the lowest scoring proof.
318 }
319
320 return invalidate(ProofRegistrationResult::IMMATURE,
321 "immature-proof");
322 }
323
324 if (validationState.GetResult() ==
327 "utxo-missing-or-spent");
328 }
329
330 // Reject invalid proof and remember it's rejected so we don't validate
331 // it again, unless it's our local proof.
332 // An invalid signature means the proof is always invalid, but not
333 // necessarily its proofid.
334 if (!isLocalProof(proofid) &&
335 validationState.GetResult() !=
337 validationState.GetResult() !=
339 setInvalid(proofid);
340 }
341 return invalidate(ProofRegistrationResult::INVALID, "invalid-proof");
342 }
343
344 auto now = GetTime<std::chrono::seconds>();
345 auto nextCooldownTimePoint =
346 now + std::chrono::seconds(gArgs.GetIntArg(
347 "-avalancheconflictingproofcooldown",
349
350 ProofPool::ConflictingProofSet conflictingProofs;
351 switch (validProofPool.addProofIfNoConflict(proof, conflictingProofs)) {
353 if (mode != RegistrationMode::FORCE_ACCEPT) {
354 auto bestPossibleConflictTime = std::chrono::seconds(0);
355 auto &pview = peers.get<by_proofid>();
356 for (auto &conflictingProof : conflictingProofs) {
357 auto it = pview.find(conflictingProof->getId());
358 assert(it != pview.end());
359
360 // Search the most recent time over the peers
361 bestPossibleConflictTime = std::max(
362 bestPossibleConflictTime, it->nextPossibleConflictTime);
363
365 nextCooldownTimePoint);
366 }
367
368 if (bestPossibleConflictTime > now) {
369 // Cooldown not elapsed, reject the proof.
370 return invalidate(
372 "cooldown-not-elapsed");
373 }
374
375 // Give the proof a chance to replace the conflicting ones.
377 // If we have overridden other proofs due to conflict,
378 // remove the peers and attempt to move them to the
379 // conflicting pool.
380 moveToConflictingPool(conflictingProofs);
381
382 // Replacement is successful, continue to peer creation
383 break;
384 }
385
386 // Not the preferred proof, or replacement is not enabled
390 "rejected-proof")
392 "conflicting-utxos");
393 }
394
396
397 // Move the conflicting proofs from the valid pool to the
398 // conflicting pool
399 moveToConflictingPool(conflictingProofs);
400
401 auto status = validProofPool.addProofIfNoConflict(proof);
403
404 break;
405 }
407 // If the proof was already in the pool, don't duplicate the peer.
409 "proof-already-registered");
411 break;
412
413 // No default case, so the compiler can warn about missing cases
414 }
415
416 // At this stage we are going to create a peer so the proof should never
417 // exist in the conflicting pool, but use belt and suspenders.
419
420 // A preferred peer owning these UTXOs supersedes any dangling proof that
421 // was parked earlier for the same stakes.
422 for (const ProofRef &conflicting : danglingProofPool.getConflicts(proof)) {
423 const ProofId &conflictingProofId = conflicting->getId();
424 danglingProofPool.removeProof(conflictingProofId);
426 "Evicted dangling proof %s due to conflict with peer proof "
427 "%s\n",
428 conflictingProofId.GetHex(), proofid.GetHex());
429 }
430
431 // New peer means new peerid!
432 const PeerId peerid = nextPeerId++;
433
434 // We have no peer for this proof, time to create it.
435 auto inserted = peers.emplace(peerid, proof, nextCooldownTimePoint);
436 assert(inserted.second);
437
438 if (isLocalProof(proofid)) {
439 // Add it to the shareable proofs even if there is no node, we are the
440 // node. Otherwise it will be inserted after a node is attached to the
441 // proof.
442 shareableProofs.insert(proof);
443 }
444
445 // Add to our registered score when adding to the peer list
446 totalPeersScore += proof->getScore();
447
448 // If there are nodes waiting for this proof, add them
449 auto &pendingNodesView = pendingNodes.get<by_proofid>();
450 auto range = pendingNodesView.equal_range(proofid);
451
452 // We want to update the nodes then remove them from the pending set. That
453 // will invalidate the range iterators, so we need to save the node ids
454 // first before we can loop over them.
455 std::vector<std::pair<NodeId, size_t>> nodeids_and_max_elements;
456 nodeids_and_max_elements.reserve(std::distance(range.first, range.second));
457 std::transform(range.first, range.second,
458 std::back_inserter(nodeids_and_max_elements),
459 [](const PendingNode &n) {
460 return std::make_pair(n.nodeid, n.max_elements);
461 });
462
463 for (const auto &[nodeid, max_elements] : nodeids_and_max_elements) {
464 addOrUpdateNode(inserted.first, nodeid, max_elements);
465 }
466
468 addStakeContender(proof);
469 }
470
471 return true;
472}
473
475 if (isDangling(proofid) && mode == RejectionMode::INVALIDATE) {
477 return true;
478 }
479
480 if (!exists(proofid)) {
481 return false;
482 }
483
484 if (immatureProofPool.removeProof(proofid)) {
485 return true;
486 }
487
488 if (mode == RejectionMode::DEFAULT &&
490 // In default mode we keep the proof in the conflicting pool
491 return true;
492 }
493
494 if (mode == RejectionMode::INVALIDATE &&
496 // In invalidate mode we remove the proof completely
497 return true;
498 }
499
500 auto &pview = peers.get<by_proofid>();
501 auto it = pview.find(proofid);
502 assert(it != pview.end());
503
504 const ProofRef proof = it->proof;
505
506 if (!removePeer(it->peerid)) {
507 return false;
508 }
509
510 // If there was conflicting proofs, attempt to pull them back
511 for (const SignedStake &ss : proof->getStakes()) {
512 const ProofRef conflictingProof =
513 conflictingProofPool.getProof(ss.getStake().getUTXO());
514 if (!conflictingProof) {
515 continue;
516 }
517
518 conflictingProofPool.removeProof(conflictingProof->getId());
519 registerProof(conflictingProof);
520 }
521
522 if (mode == RejectionMode::DEFAULT) {
524 }
525
526 return true;
527}
528
530 std::unordered_set<ProofRef, SaltedProofHasher> &registeredProofs) {
531 registeredProofs.clear();
532 const auto now = GetTime<std::chrono::seconds>();
533
534 std::vector<ProofRef> newlyDanglingProofs;
535 for (const Peer &peer : peers) {
536 // If the peer is not our local proof, has been registered for some
537 // time and has no node attached, discard it.
538 if (!isLocalProof(peer.getProofId()) && peer.node_count == 0 &&
539 (peer.registration_time + Peer::DANGLING_TIMEOUT) <= now) {
540 // Check the remotes status to determine if we should set the proof
541 // as dangling. This prevents from dropping a proof on our own due
542 // to a network issue. If the remote presence status is inconclusive
543 // we assume our own position (missing = false).
544 if (!getRemotePresenceStatus(peer.getProofId()).value_or(false)) {
545 newlyDanglingProofs.push_back(peer.proof);
546 }
547 }
548 }
549
550 // Similarly, check if we have dangling proofs that could be pulled back
551 // because the network says so.
552 std::vector<ProofRef> previouslyDanglingProofs;
553 danglingProofPool.forEachProof([&](const ProofRef &proof) {
554 if (getRemotePresenceStatus(proof->getId()).value_or(false)) {
555 previouslyDanglingProofs.push_back(proof);
556 }
557 });
558 for (const ProofRef &proof : previouslyDanglingProofs) {
559 danglingProofPool.removeProof(proof->getId());
560 if (registerProof(proof)) {
561 registeredProofs.insert(proof);
562 }
563 }
564
565 for (const ProofRef &proof : newlyDanglingProofs) {
566 rejectProof(proof->getId(), RejectionMode::INVALIDATE);
567
568 // If a preferred peer already owns any of these UTXOs, do not park the
569 // proof as dangling — it can never be pulled back usefully.
570 // Note that since peer registration also checks for conflicts in the
571 // dangling pool, this condition should never be true. It is kept as a
572 // belt and suspenders check in the case this assumption is violated.
573 if (!validProofPool.getConflicts(proof).empty()) {
574 continue;
575 }
576
578 // If the proof is added, it means there is no better conflicting
579 // dangling proof and this is not a duplicated, so it's worth
580 // printing a message to the log.
582 "Proof dangling for too long (no connected node): %s\n",
583 proof->getId().GetHex());
584 }
585 }
586
587 // If we have dangling proof, this is a good indicator that we need to
588 // request more nodes from our peers.
589 needMoreNodes = !newlyDanglingProofs.empty();
590}
591
593 for (int retry = 0; retry < SELECT_NODE_MAX_RETRY; retry++) {
594 const PeerId p = selectPeer();
595
596 // If we cannot find a peer, it may be due to the fact that it is
597 // unlikely due to high fragmentation, so compact and retry.
598 if (p == NO_PEER) {
599 compact();
600 continue;
601 }
602
603 // See if that peer has an available node.
604 auto &nview = nodes.get<next_request_time>();
605 auto it = nview.lower_bound(boost::make_tuple(p, SteadyMilliseconds()));
606 if (it != nview.end() && it->peerid == p &&
607 it->nextRequestTime <= Now<SteadyMilliseconds>()) {
608 return it->nodeid;
609 }
610 }
611
612 // We failed to find a node to query, flag this so we can request more
613 needMoreNodes = true;
614
615 return NO_NODE;
616}
617
618std::unordered_set<ProofRef, SaltedProofHasher> PeerManager::updatedBlockTip() {
619 std::vector<ProofId> invalidProofIds;
620 std::vector<ProofRef> newImmatures;
621
622 {
623 LOCK(cs_main);
624
625 for (const auto &p : peers) {
627 if (!p.proof->verify(stakeUtxoDustThreshold, chainman, state)) {
628 if (isImmatureState(state)) {
629 newImmatures.push_back(p.proof);
630 }
631 invalidProofIds.push_back(p.getProofId());
632
634 "Invalidating proof %s: verification failed (%s)\n",
635 p.proof->getId().GetHex(), state.ToString());
636 }
637 }
638
639 // Disable thread safety analysis here because it does not play nicely
640 // with the lambda
642 [&](const ProofRef &proof) NO_THREAD_SAFETY_ANALYSIS {
645 if (!proof->verify(stakeUtxoDustThreshold, chainman, state)) {
646 invalidProofIds.push_back(proof->getId());
647
648 LogDebug(
650 "Invalidating dangling proof %s: verification failed "
651 "(%s)\n",
652 proof->getId().GetHex(), state.ToString());
653 }
654 });
655 }
656
657 // Remove the invalid proofs before the immature rescan. This makes it
658 // possible to pull back proofs with utxos that conflicted with these
659 // invalid proofs.
660 for (const ProofId &invalidProofId : invalidProofIds) {
661 rejectProof(invalidProofId, RejectionMode::INVALIDATE);
662 }
663
664 auto registeredProofs = immatureProofPool.rescan(*this);
665
666 for (auto &p : newImmatures) {
668 }
669
670 return registeredProofs;
671}
672
674 ProofRef proof;
675
676 forPeer(proofid, [&](const Peer &p) {
677 proof = p.proof;
678 return true;
679 });
680
681 if (!proof) {
682 proof = conflictingProofPool.getProof(proofid);
683 }
684
685 if (!proof) {
686 proof = immatureProofPool.getProof(proofid);
687 }
688
689 return proof;
690}
691
692bool PeerManager::isBoundToPeer(const ProofId &proofid) const {
693 auto &pview = peers.get<by_proofid>();
694 return pview.find(proofid) != pview.end();
695}
696
697bool PeerManager::isImmature(const ProofId &proofid) const {
698 return immatureProofPool.getProof(proofid) != nullptr;
699}
700
701bool PeerManager::isInConflictingPool(const ProofId &proofid) const {
702 return conflictingProofPool.getProof(proofid) != nullptr;
703}
704
705bool PeerManager::isDangling(const ProofId &proofid) const {
706 return danglingProofPool.getProof(proofid) != nullptr;
707}
708
709void PeerManager::setInvalid(const ProofId &proofid) {
710 invalidProofs.insert(proofid);
711}
712
713bool PeerManager::isInvalid(const ProofId &proofid) const {
714 return invalidProofs.contains(proofid);
715}
716
720
721bool PeerManager::saveRemoteProof(const ProofId &proofid, const NodeId nodeid,
722 const bool present) {
723 if (present && isStakingPreconsensusActivated() && isBoundToPeer(proofid) &&
724 !isRemotelyPresentProof(proofid)) {
725 // If this is the first time this peer's proof becomes a remote proof of
726 // any node, ensure it is included in the contender cache. There is a
727 // special case where the contender cache can lose track of a proof if
728 // it is not saved as a remote proof before the next finalized block
729 // (triggering promotion, where non-remote cache entries are dropped).
730 // This does not happen in the hot path since receiving a proof
731 // immediately saves it as a remote, however it becomes more likely if
732 // the proof was loaded from a file (-persistavapeers) or added via RPC.
733 addStakeContender(getProof(proofid));
734 }
735
736 // Get how many proofs this node has announced
737 auto &remoteProofsByLastUpdate = remoteProofs.get<by_lastUpdate>();
738 auto [begin, end] = remoteProofsByLastUpdate.equal_range(nodeid);
739
740 // Limit the number of proofs a single node can save:
741 // - At least MAX_REMOTE_PROOFS
742 // - Up to 2x as much as we have
743 // The MAX_REMOTE_PROOFS minimum is there to ensure we don't overlimit at
744 // startup when we don't have proofs yet.
745 while (size_t(std::distance(begin, end)) >=
746 std::max(MAX_REMOTE_PROOFS, 2 * peers.size())) {
747 // Remove the proof with the oldest update time
748 begin = remoteProofsByLastUpdate.erase(begin);
749 }
750
751 auto it = remoteProofs.find(boost::make_tuple(proofid, nodeid));
752 if (it != remoteProofs.end()) {
753 remoteProofs.erase(it);
754 }
755
756 return remoteProofs
757 .emplace(RemoteProof{proofid, nodeid, GetTime<std::chrono::seconds>(),
758 present})
759 .second;
760}
761
762std::vector<RemoteProof>
764 std::vector<RemoteProof> nodeRemoteProofs;
765
766 auto &remoteProofsByLastUpdate = remoteProofs.get<by_lastUpdate>();
767 auto [begin, end] = remoteProofsByLastUpdate.equal_range(nodeid);
768
769 for (auto &it = begin; it != end; it++) {
770 nodeRemoteProofs.emplace_back(*it);
771 }
772
773 return nodeRemoteProofs;
774}
775
776bool PeerManager::hasRemoteProofStatus(const ProofId &proofid) const {
777 auto &view = remoteProofs.get<by_proofid>();
778 return view.count(proofid) > 0;
779}
780
782 auto &view = remoteProofs.get<by_proofid>();
783 auto [begin, end] = view.equal_range(proofid);
784 return std::any_of(begin, end, [](const auto &remoteProof) {
785 return remoteProof.present;
786 });
787}
788
790 auto &remoteProofsView = remoteProofs.get<by_nodeid>();
791 auto [begin, end] = remoteProofsView.equal_range(nodeid);
792 remoteProofsView.erase(begin, end);
793}
794
795bool PeerManager::removePeer(const PeerId peerid) {
796 auto it = peers.find(peerid);
797 if (it == peers.end()) {
798 return false;
799 }
800
801 // Remove all nodes from this peer.
802 removeNodeFromPeer(it, it->node_count);
803
804 auto &nview = nodes.get<next_request_time>();
805
806 // Add the nodes to the pending set
807 auto range = nview.equal_range(peerid);
808 for (auto &nit = range.first; nit != range.second; ++nit) {
809 pendingNodes.emplace(it->getProofId(), nit->nodeid, nit->maxElements);
810 };
811
812 // Remove nodes associated with this peer, unless their timeout is still
813 // active. This ensure that we don't overquery them in case they are
814 // subsequently added to another peer.
815 nview.erase(
816 nview.lower_bound(boost::make_tuple(peerid, SteadyMilliseconds())),
817 nview.upper_bound(
818 boost::make_tuple(peerid, Now<SteadyMilliseconds>())));
819
820 // Release UTXOs attached to this proof.
821 validProofPool.removeProof(it->getProofId());
822
823 // If there were nodes attached, remove from the radix tree as well
824 auto removed = shareableProofs.remove(Uint256RadixKey(it->getProofId()));
825
826 m_unbroadcast_proofids.erase(it->getProofId());
827
828 // Remove the peer from the PeerSet and remove its score from the registered
829 // score total.
830 assert(totalPeersScore >= it->getScore());
831 totalPeersScore -= it->getScore();
832 peers.erase(it);
833 return true;
834}
835
837 if (slots.empty() || slotCount == 0) {
838 return NO_PEER;
839 }
840
841 const uint64_t max = slotCount;
842 for (int retry = 0; retry < SELECT_PEER_MAX_RETRY; retry++) {
843 size_t i =
844 selectPeerImpl(slots, FastRandomContext().randrange(max), max);
845 if (i != NO_PEER) {
846 return i;
847 }
848 }
849
850 return NO_PEER;
851}
852
854 // There is nothing to compact.
855 if (fragmentation == 0) {
856 return 0;
857 }
858
859 std::vector<Slot> newslots;
860 newslots.reserve(peers.size());
861
862 uint64_t prevStop = 0;
863 uint32_t i = 0;
864 for (auto it = peers.begin(); it != peers.end(); it++) {
865 if (it->node_count == 0) {
866 continue;
867 }
868
869 newslots.emplace_back(prevStop, it->getScore(), it->peerid);
870 prevStop = newslots.back().getStop();
871 if (!peers.modify(it, [&](Peer &p) { p.index = i++; })) {
872 return 0;
873 }
874 }
875
876 slots = std::move(newslots);
877
878 const uint64_t saved = slotCount - prevStop;
879 slotCount = prevStop;
880 fragmentation = 0;
881
882 return saved;
883}
884
886 uint64_t prevStop = 0;
887 uint32_t scoreFromSlots = 0;
888 for (size_t i = 0; i < slots.size(); i++) {
889 const Slot &s = slots[i];
890
891 // Slots must be in correct order.
892 if (s.getStart() < prevStop) {
893 return false;
894 }
895
896 prevStop = s.getStop();
897
898 // If this is a dead slot, then nothing more needs to be checked.
899 if (s.getPeerId() == NO_PEER) {
900 continue;
901 }
902
903 // We have a live slot, verify index.
904 auto it = peers.find(s.getPeerId());
905 if (it == peers.end() || it->index != i) {
906 return false;
907 }
908
909 // Accumulate score across slots
910 scoreFromSlots += slots[i].getScore();
911 }
912
913 // Score across slots must be the same as our allocated score
914 if (scoreFromSlots != connectedPeersScore) {
915 return false;
916 }
917
918 uint32_t scoreFromAllPeers = 0;
919 uint32_t scoreFromPeersWithNodes = 0;
920
921 std::unordered_set<COutPoint, SaltedOutpointHasher> peersUtxos;
922 for (const auto &p : peers) {
923 // Accumulate the score across peers to compare with total known score
924 scoreFromAllPeers += p.getScore();
925
926 // A peer should have a proof attached
927 if (!p.proof) {
928 return false;
929 }
930
931 // Check proof pool consistency
932 for (const auto &ss : p.proof->getStakes()) {
933 const COutPoint &outpoint = ss.getStake().getUTXO();
934 auto proof = validProofPool.getProof(outpoint);
935
936 if (!proof) {
937 // Missing utxo
938 return false;
939 }
940 if (proof != p.proof) {
941 // Wrong proof
942 return false;
943 }
944
945 if (!peersUtxos.emplace(outpoint).second) {
946 // Duplicated utxo
947 return false;
948 }
949 }
950
951 // Count node attached to this peer.
952 const auto count_nodes = [&]() {
953 size_t count = 0;
954 auto &nview = nodes.get<next_request_time>();
955 auto begin = nview.lower_bound(
956 boost::make_tuple(p.peerid, SteadyMilliseconds()));
957 auto end = nview.upper_bound(
958 boost::make_tuple(p.peerid + 1, SteadyMilliseconds()));
959
960 for (auto it = begin; it != end; ++it) {
961 count++;
962 }
963
964 return count;
965 };
966
967 if (p.node_count != count_nodes()) {
968 return false;
969 }
970
971 // If there are no nodes attached to this peer, then we are done.
972 if (p.node_count == 0) {
973 continue;
974 }
975
976 scoreFromPeersWithNodes += p.getScore();
977 // The index must point to a slot refering to this peer.
978 if (p.index >= slots.size() || slots[p.index].getPeerId() != p.peerid) {
979 return false;
980 }
981
982 // If the score do not match, same thing.
983 if (slots[p.index].getScore() != p.getScore()) {
984 return false;
985 }
986
987 // Check the proof is in the radix tree only if there are nodes attached
988 if ((isLocalProof(p.getProofId()) || p.node_count > 0) &&
989 shareableProofs.get(p.getProofId()) == nullptr) {
990 return false;
991 }
992 if (p.node_count == 0 &&
993 shareableProofs.get(p.getProofId()) != nullptr) {
994 return false;
995 }
996 }
997
998 // Check our accumulated scores against our registred and allocated scores
999 if (scoreFromAllPeers != totalPeersScore) {
1000 return false;
1001 }
1002 if (scoreFromPeersWithNodes != connectedPeersScore) {
1003 return false;
1004 }
1005
1006 // We checked the utxo consistency for all our peers utxos already, so if
1007 // the pool size differs from the expected one there are dangling utxos.
1008 if (validProofPool.size() != peersUtxos.size()) {
1009 return false;
1010 }
1011
1012 // Check there is no dangling proof in the radix tree
1014 return isBoundToPeer(pLeaf->getId());
1015 });
1016}
1017
1018PeerId selectPeerImpl(const std::vector<Slot> &slots, const uint64_t slot,
1019 const uint64_t max) {
1020 assert(slot <= max);
1021
1022 size_t begin = 0, end = slots.size();
1023 uint64_t bottom = 0, top = max;
1024
1025 // Try to find the slot using dichotomic search.
1026 while ((end - begin) > 8) {
1027 // The slot we picked in not allocated.
1028 if (slot < bottom || slot >= top) {
1029 return NO_PEER;
1030 }
1031
1032 // Guesstimate the position of the slot.
1033 size_t i = begin + ((slot - bottom) * (end - begin) / (top - bottom));
1034 assert(begin <= i && i < end);
1035
1036 // We have a match.
1037 if (slots[i].contains(slot)) {
1038 return slots[i].getPeerId();
1039 }
1040
1041 // We undershooted.
1042 if (slots[i].precedes(slot)) {
1043 begin = i + 1;
1044 if (begin >= end) {
1045 return NO_PEER;
1046 }
1047
1048 bottom = slots[begin].getStart();
1049 continue;
1050 }
1051
1052 // We overshooted.
1053 if (slots[i].follows(slot)) {
1054 end = i;
1055 top = slots[end].getStart();
1056 continue;
1057 }
1058
1059 // We have an unalocated slot.
1060 return NO_PEER;
1061 }
1062
1063 // Enough of that nonsense, let fallback to linear search.
1064 for (size_t i = begin; i < end; i++) {
1065 // We have a match.
1066 if (slots[i].contains(slot)) {
1067 return slots[i].getPeerId();
1068 }
1069 }
1070
1071 // We failed to find a slot, retry.
1072 return NO_PEER;
1073}
1074
1076 // The proof should be bound to a peer
1077 if (isBoundToPeer(proofid)) {
1078 m_unbroadcast_proofids.insert(proofid);
1079 }
1080}
1081
1083 m_unbroadcast_proofids.erase(proofid);
1084}
1085
1087 const CBlockIndex *pprev,
1088 std::vector<std::pair<ProofId, CScript>> &winners) {
1089 if (!pprev) {
1090 return false;
1091 }
1092
1093 const BlockHash prevblockhash = pprev->GetBlockHash();
1094
1095 // Rejected contenders only affect winner selection for their prevblock.
1097 rejectedContenderPrevBlockHash != prevblockhash) {
1099 }
1100
1101 // Don't select proofs that have not been known for long enough, i.e. at
1102 // least since twice the dangling proof cleanup timeout before the last
1103 // block time, so we're sure to not account for proofs more recent than the
1104 // previous block or lacking node connected.
1105 // The previous block time is capped to now for the unlikely event the
1106 // previous block time is in the future.
1107 auto registrationDelay = std::chrono::duration_cast<std::chrono::seconds>(
1109 auto maxRegistrationDelay =
1110 std::chrono::duration_cast<std::chrono::seconds>(
1112 auto minRegistrationDelay =
1113 std::chrono::duration_cast<std::chrono::seconds>(
1115
1116 const int64_t refTime = std::min(pprev->GetBlockTime(), GetTime());
1117
1118 const int64_t targetRegistrationTime = refTime - registrationDelay.count();
1119 const int64_t maxRegistrationTime = refTime - minRegistrationDelay.count();
1120 const int64_t minRegistrationTime = refTime - maxRegistrationDelay.count();
1121
1122 std::vector<ProofRef> selectedProofs;
1123 ProofRef firstCompliantProof = ProofRef();
1124 while (selectedProofs.size() < peers.size()) {
1125 double bestRewardRank = std::numeric_limits<double>::max();
1126 ProofRef selectedProof = ProofRef();
1127 int64_t selectedProofRegistrationTime{0};
1128 StakeContenderId bestRewardHash;
1129
1130 for (const Peer &peer : peers) {
1131 if (!peer.proof) {
1132 // Should never happen, continue
1133 continue;
1134 }
1135
1136 if (!peer.hasFinalized ||
1137 peer.registration_time.count() >= maxRegistrationTime) {
1138 continue;
1139 }
1140
1141 if (std::find_if(selectedProofs.begin(), selectedProofs.end(),
1142 [&peer](const ProofRef &proof) {
1143 return peer.getProofId() == proof->getId();
1144 }) != selectedProofs.end()) {
1145 continue;
1146 }
1147
1148 StakeContenderId proofRewardHash(prevblockhash, peer.getProofId());
1149 if (proofRewardHash == uint256::ZERO) {
1150 // This either the result of an incredibly unlikely lucky hash,
1151 // or a the hash is getting abused. In this case, skip the
1152 // proof.
1153 LogPrintf(
1154 "Staking reward hash has a suspicious value of zero for "
1155 "proof %s and blockhash %s, skipping\n",
1156 peer.getProofId().ToString(), prevblockhash.ToString());
1157 continue;
1158 }
1159
1160 double proofRewardRank =
1161 proofRewardHash.ComputeProofRewardRank(peer.getScore());
1162 // If selectedProof is nullptr, this means that bestRewardRank is
1163 // MAX_DOUBLE so the comparison will always select this proof as the
1164 // preferred one. As a consequence it is safe to use 0 as a proofid.
1166 proofRewardHash, proofRewardRank, peer.getProofId(),
1167 bestRewardHash, bestRewardRank,
1168 selectedProof ? selectedProof->getId()
1169 : ProofId(uint256::ZERO))) {
1170 bestRewardRank = proofRewardRank;
1171 selectedProof = peer.proof;
1172 selectedProofRegistrationTime = peer.registration_time.count();
1173 bestRewardHash = proofRewardHash;
1174 }
1175 }
1176
1177 if (!selectedProof) {
1178 // No winner
1179 break;
1180 }
1181
1182 if (!firstCompliantProof &&
1183 selectedProofRegistrationTime < targetRegistrationTime) {
1184 firstCompliantProof = selectedProof;
1185 }
1186
1187 selectedProofs.push_back(selectedProof);
1188
1189 if (selectedProofRegistrationTime < minRegistrationTime &&
1190 !isFlaky(selectedProof->getId()) &&
1191 rejectedContenderProofids.count(selectedProof->getId()) == 0) {
1192 break;
1193 }
1194 }
1195
1196 winners.clear();
1197
1198 if (!firstCompliantProof) {
1199 return false;
1200 }
1201
1202 winners.reserve(selectedProofs.size());
1203
1204 // Find the winner
1205 for (const ProofRef &proof : selectedProofs) {
1206 if (proof->getId() == firstCompliantProof->getId()) {
1207 winners.push_back({proof->getId(), proof->getPayoutScript()});
1208 }
1209 }
1210 // Add the others (if any) after the winner
1211 for (const ProofRef &proof : selectedProofs) {
1212 if (proof->getId() != firstCompliantProof->getId()) {
1213 winners.push_back({proof->getId(), proof->getPayoutScript()});
1214 }
1215 }
1216
1217 return true;
1218}
1219
1220bool PeerManager::setFlaky(const ProofId &proofid) {
1221 return manualFlakyProofids.insert(proofid).second;
1222}
1223
1224bool PeerManager::unsetFlaky(const ProofId &proofid) {
1225 return manualFlakyProofids.erase(proofid) > 0;
1226}
1227
1229 const BlockHash &prevblockhash) {
1230 if (rejectedContenderPrevBlockHash != prevblockhash) {
1232 rejectedContenderPrevBlockHash = prevblockhash;
1233 }
1234 return rejectedContenderProofids.insert(proofid).second;
1235}
1236
1241
1242bool PeerManager::isFlaky(const ProofId &proofid) const {
1243 if (isLocalProof(proofid)) {
1244 return false;
1245 }
1246
1247 if (manualFlakyProofids.count(proofid) > 0) {
1248 return true;
1249 }
1250
1251 // If we are missing connection to this proof, consider flaky
1252 if (forPeer(proofid,
1253 [](const Peer &peer) { return peer.node_count == 0; })) {
1254 return true;
1255 }
1256
1257 auto &remoteProofsByNodeId = remoteProofs.get<by_nodeid>();
1258 auto &nview = nodes.get<next_request_time>();
1259
1260 std::unordered_map<PeerId, std::unordered_set<ProofId, SaltedProofIdHasher>>
1261 missing_per_peer;
1262
1263 // Construct a set of missing proof ids per peer
1264 double total_score{0};
1265 for (const Peer &peer : peers) {
1266 const PeerId peerid = peer.peerid;
1267
1268 total_score += peer.getScore();
1269
1270 auto nodes_range = nview.equal_range(peerid);
1271 for (auto &nit = nodes_range.first; nit != nodes_range.second; ++nit) {
1272 auto proofs_range = remoteProofsByNodeId.equal_range(nit->nodeid);
1273 for (auto &proofit = proofs_range.first;
1274 proofit != proofs_range.second; ++proofit) {
1275 if (!proofit->present) {
1276 missing_per_peer[peerid].insert(proofit->proofid);
1277 }
1278 }
1279 };
1280 }
1281
1282 double missing_score{0};
1283
1284 // Now compute a score for the missing proof
1285 for (const auto &[peerid, missingProofs] : missing_per_peer) {
1286 if (missingProofs.size() > 3) {
1287 // Ignore peers with too many missing proofs
1288 continue;
1289 }
1290
1291 auto pit = peers.find(peerid);
1292 if (pit == peers.end()) {
1293 // Peer not found
1294 continue;
1295 }
1296
1297 if (missingProofs.count(proofid) > 0) {
1298 missing_score += pit->getScore();
1299 }
1300 }
1301
1302 return (missing_score / total_score) > 0.3;
1303}
1304
1305bool PeerManager::isLocalProof(const ProofId &proofid) const {
1306 return localProof && proofid == localProof->getId();
1307}
1308
1309std::optional<bool>
1311 auto &remoteProofsView = remoteProofs.get<by_proofid>();
1312 auto [begin, end] = remoteProofsView.equal_range(proofid);
1313
1314 if (begin == end) {
1315 // No remote registered anything yet, we are on our own
1316 return std::nullopt;
1317 }
1318
1319 double total_score{0};
1320 double present_score{0};
1321 double missing_score{0};
1322
1323 for (auto it = begin; it != end; it++) {
1324 auto nit = nodes.find(it->nodeid);
1325 if (nit == nodes.end()) {
1326 // No such node
1327 continue;
1328 }
1329
1330 const PeerId peerid = nit->peerid;
1331
1332 auto pit = peers.find(peerid);
1333 if (pit == peers.end()) {
1334 // Peer not found
1335 continue;
1336 }
1337
1338 uint32_t node_count = pit->node_count;
1339 if (isLocalProof(pit->getProofId())) {
1340 // If that's our local proof, account for ourself
1341 ++node_count;
1342 }
1343
1344 if (node_count == 0) {
1345 // should never happen
1346 continue;
1347 }
1348
1349 const double score = double(pit->getScore()) / node_count;
1350
1351 total_score += score;
1352 if (it->present) {
1353 present_score += score;
1354 } else {
1355 missing_score += score;
1356 }
1357 }
1358
1359 if (localProof) {
1360 auto &peersByProofid = peers.get<by_proofid>();
1361
1362 // Do we have a node connected for that proof ?
1363 bool present = false;
1364 auto pit = peersByProofid.find(proofid);
1365 if (pit != peersByProofid.end()) {
1366 present = pit->node_count > 0;
1367 }
1368
1369 pit = peersByProofid.find(localProof->getId());
1370 if (pit != peersByProofid.end()) {
1371 // Also divide by node_count, we can have several nodes even for our
1372 // local proof.
1373 const double score =
1374 double(pit->getScore()) / (1 + pit->node_count);
1375
1376 total_score += score;
1377 if (present) {
1378 present_score += score;
1379 } else {
1380 missing_score += score;
1381 }
1382 }
1383 }
1384
1385 if (present_score / total_score > 0.55) {
1386 return std::make_optional(true);
1387 }
1388
1389 if (missing_score / total_score > 0.55) {
1390 return std::make_optional(false);
1391 }
1392
1393 return std::nullopt;
1394}
1395
1396bool PeerManager::dumpPeersToFile(const fs::path &dumpPath) const {
1397 try {
1398 const fs::path dumpPathTmp = dumpPath + ".new";
1399 FILE *filestr = fsbridge::fopen(dumpPathTmp, "wb");
1400 if (!filestr) {
1401 return false;
1402 }
1403
1404 AutoFile file{filestr};
1405 file << PEERS_DUMP_VERSION;
1406 file << uint64_t(peers.size());
1407 for (const Peer &peer : peers) {
1408 file << peer.proof;
1409 file << peer.hasFinalized;
1410 file << int64_t(peer.registration_time.count());
1411 file << int64_t(peer.nextPossibleConflictTime.count());
1412 }
1413
1414 if (!FileCommit(file.Get())) {
1415 throw std::runtime_error(strprintf("Failed to commit to file %s",
1416 PathToString(dumpPathTmp)));
1417 }
1418 file.fclose();
1419
1420 if (!RenameOver(dumpPathTmp, dumpPath)) {
1421 throw std::runtime_error(strprintf("Rename failed from %s to %s",
1422 PathToString(dumpPathTmp),
1423 PathToString(dumpPath)));
1424 }
1425 } catch (const std::exception &e) {
1426 LogDebug(BCLog::AVALANCHE, "Failed to dump the avalanche peers: %s.\n",
1427 e.what());
1428 return false;
1429 }
1430
1431 LogDebug(BCLog::AVALANCHE, "Successfully dumped %d peers to %s.\n",
1432 peers.size(), PathToString(dumpPath));
1433
1434 return true;
1435}
1436
1438 const fs::path &dumpPath,
1439 std::unordered_set<ProofRef, SaltedProofHasher> &registeredProofs) {
1440 registeredProofs.clear();
1441
1442 FILE *filestr = fsbridge::fopen(dumpPath, "rb");
1443 AutoFile file{filestr};
1444 if (file.IsNull()) {
1446 "Failed to open avalanche peers file from disk.\n");
1447 return false;
1448 }
1449
1450 try {
1451 uint64_t version;
1452 file >> version;
1453
1454 if (version != PEERS_DUMP_VERSION) {
1456 "Unsupported avalanche peers file version.\n");
1457 return false;
1458 }
1459
1460 uint64_t numPeers;
1461 file >> numPeers;
1462
1463 auto &peersByProofId = peers.get<by_proofid>();
1464
1465 for (uint64_t i = 0; i < numPeers; i++) {
1466 ProofRef proof;
1467 bool hasFinalized;
1468 int64_t registrationTime;
1469 int64_t nextPossibleConflictTime;
1470
1471 file >> proof;
1472 file >> hasFinalized;
1473 file >> registrationTime;
1474 file >> nextPossibleConflictTime;
1475
1476 if (registerProof(proof)) {
1477 auto it = peersByProofId.find(proof->getId());
1478 if (it == peersByProofId.end()) {
1479 // Should never happen
1480 continue;
1481 }
1482
1483 // We don't modify any key so we don't need to rehash.
1484 // If the modify fails, it means we don't get the full benefit
1485 // from the file but we still added our peer to the set. The
1486 // non-overridden fields will be set the normal way.
1487 peersByProofId.modify(it, [&](Peer &p) {
1488 p.hasFinalized = hasFinalized;
1490 std::chrono::seconds{registrationTime};
1492 std::chrono::seconds{nextPossibleConflictTime};
1493 });
1494
1495 registeredProofs.insert(proof);
1496 }
1497 }
1498 } catch (const std::exception &e) {
1500 "Failed to read the avalanche peers file data on disk: %s.\n",
1501 e.what());
1502 return false;
1503 }
1504
1505 return true;
1506}
1507
1508void PeerManager::cleanupStakeContenders(const int requestedMinHeight) {
1509 stakeContenderCache.cleanup(requestedMinHeight);
1510}
1511
1513 const CBlockIndex *tip = WITH_LOCK(cs_main, return chainman.ActiveTip());
1514 stakeContenderCache.add(tip, proof);
1515
1516 const BlockHash blockhash = tip->GetBlockHash();
1517 const ProofId &proofid = proof->getId();
1519 "Cached stake contender with proofid %s, payout %s at block "
1520 "%s (height %d) with id %s\n",
1521 proofid.ToString(), HexStr(proof->getPayoutScript()),
1522 blockhash.ToString(), tip->nHeight,
1523 StakeContenderId(blockhash, proofid).ToString());
1524}
1525
1527 BlockHash &prevblockhashout) const {
1528 const auto contender = stakeContenderCache.getContenderInfo(contenderId);
1529 if (!contender) {
1530 return -1;
1531 }
1532
1533 prevblockhashout = contender->prevblockhash;
1534 if (contender->voteStatus != 0) {
1535 return contender->voteStatus;
1536 }
1537
1538 const ProofId &proofid = contender->proofid;
1539
1540 if (isInvalid(proofid)) {
1541 return 2;
1542 }
1543 if (isInConflictingPool(proofid)) {
1544 return 3;
1545 }
1546 if (isDangling(proofid) &&
1547 !getRemotePresenceStatus(proofid).value_or(false)) {
1548 return 4;
1549 }
1550
1551 // Bound peers need to be finalized and registered more than
1552 // 4 * DANGLING_TIMEOUT before the prev block.
1553 if (isBoundToPeer(proofid)) {
1554 auto &pview = peers.get<by_proofid>();
1555 auto it = pview.find(proofid);
1556 if (it == pview.end() || !it->hasFinalized) {
1557 return 5;
1558 }
1559
1560 const int64_t refTime = std::min(contender->prevblocktime, GetTime());
1561 const int64_t targetRegistrationTime =
1562 refTime - std::chrono::duration_cast<std::chrono::seconds>(
1564 .count();
1565 if (it->registration_time.count() >= targetRegistrationTime) {
1566 return 6;
1567 }
1568 }
1569
1570 // Cache-only contenders keep cache acceptance.
1571 return 0;
1572}
1573
1575 stakeContenderCache.accept(contenderId);
1576}
1577
1579 const StakeContenderId &contenderId, BlockHash &prevblockhash,
1580 std::vector<std::pair<ProofId, CScript>> &newWinners) {
1581 stakeContenderCache.finalize(contenderId);
1582
1583 // Get block hash related to this contender. We should not assume the
1584 // current chain tip is the block this contender is a winner for.
1585 stakeContenderCache.getVoteStatus(contenderId, prevblockhash);
1586
1587 // Calculate the new winners for this block
1588 stakeContenderCache.getWinners(prevblockhash, newWinners);
1589}
1590
1592 stakeContenderCache.reject(contenderId);
1593}
1594
1595std::optional<StakeContenderCacheInfo>
1597 return stakeContenderCache.getContenderInfo(contenderId);
1598}
1599
1600bool PeerManager::hasAcceptedStakeWinner(const BlockHash &prevblockhash) const {
1601 return stakeContenderCache.hasAcceptedWinner(prevblockhash);
1602}
1603
1605 const BlockHash &prevblockhash,
1606 std::vector<std::pair<ProofId, CScript>> &winners) const {
1607 return stakeContenderCache.getWinners(prevblockhash, winners);
1608}
1609
1611 stakeContenderCache.promoteToBlock(pindex, [&](const ProofId &proofid) {
1612 return isBoundToPeer(proofid) ||
1613 // isDangling check appears redundant, but remote proofs are not
1614 // guaranteed to be cleaned up when one of our peers is removed
1615 // for dangling too long. Whether or not a proof is dangling is
1616 // gated by remote presence status, so only proofs that are very
1617 // poorly connected to the network will stop being promoted.
1618 (isRemotelyPresentProof(proofid) && isDangling(proofid));
1619 });
1620}
1621
1623 const CBlockIndex *prevblock,
1624 const std::vector<std::pair<ProofId, CScript>> winners, size_t maxPollable,
1625 std::vector<StakeContenderId> &pollableContenders) {
1626 const BlockHash prevblockhash = prevblock->GetBlockHash();
1627 // Set status for local winners
1628 for (const auto &winner : winners) {
1629 const StakeContenderId contenderId(prevblockhash, winner.first);
1630 stakeContenderCache.finalize(contenderId);
1632 "Stake contender set as local winner: proofid %s, payout "
1633 "%s at block %s (height %d) with id %s\n",
1634 winner.first.ToString(), HexStr(winner.second),
1635 prevblockhash.ToString(), prevblock->nHeight,
1636 contenderId.ToString());
1637 }
1638
1639 // Treat the highest ranking contender similarly to local winners except
1640 // that it is not automatically included in the winner set (unless it
1641 // happens to be selected as a local winner). Vote-side eligibility is
1642 // enforced in getStakeContenderStatus.
1643 if (stakeContenderCache.getPollableContenders(prevblockhash, maxPollable,
1644 pollableContenders) > 0) {
1645 // Accept the highest ranking contender. This is a no-op if the highest
1646 // ranking contender is already the local winner.
1647 stakeContenderCache.accept(pollableContenders[0]);
1649 "Stake contender set as best contender: id %s at block "
1650 "%s (height %d)\n",
1651 pollableContenders[0].ToString(), prevblockhash.ToString(),
1652 prevblock->nHeight);
1653 return true;
1654 }
1655
1656 return false;
1657}
1658
1660 const CBlockIndex *pindex, const std::vector<CScript> &payoutScripts) {
1661 return stakeContenderCache.setWinners(pindex, payoutScripts);
1662}
1663
1664} // namespace avalanche
ArgsManager gArgs
Definition args.cpp:39
static constexpr PeerId NO_PEER
Definition node.h:15
uint32_t PeerId
Definition node.h:14
static constexpr size_t AVALANCHE_DEFAULT_CONFLICTING_PROOF_COOLDOWN
Conflicting proofs cooldown time default value in seconds.
Definition avalanche.h:21
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition args.cpp:494
Non-refcounted RAII wrapper for FILE*.
Definition streams.h:433
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition blockindex.h:25
int64_t GetBlockTime() const
Definition blockindex.h:159
BlockHash GetBlockHash() const
Definition blockindex.h:129
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition blockindex.h:38
void insert(Span< const uint8_t > vKey)
Definition bloom.cpp:215
bool contains(Span< const uint8_t > vKey) const
Definition bloom.cpp:249
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Fast randomness source.
Definition random.h:411
T * get()
Get allows to access the undelying pointer.
Definition rcu.h:170
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition validation.h:101
Result GetResult() const
Definition validation.h:122
std::string ToString() const
Definition validation.h:125
bool selectStakingRewardWinner(const CBlockIndex *pprev, std::vector< std::pair< ProofId, CScript > > &winners)
Deterministically select a list of payout scripts based on the proof set and the previous block hash.
std::vector< RemoteProof > getRemoteProofs(const NodeId nodeid) const
bool removeNode(NodeId nodeid)
bool setFinalized(PeerId peerid)
Latch on that this peer has a finalized proof.
bool dumpPeersToFile(const fs::path &dumpPath) const
RemoteProofSet remoteProofs
Remember which node sent which proof so we have an image of the proof set of our peers.
bool updateNextRequestTimeForResponse(NodeId nodeid, const Response &response)
bool isDangling(const ProofId &proofid) const
bool addNode(NodeId nodeid, const ProofId &proofid, size_t max_elements)
Node API.
bool unsetFlaky(const ProofId &proofid)
std::optional< bool > getRemotePresenceStatus(const ProofId &proofid) const
Get the presence remote status of a proof.
bool addNodeToPeer(const PeerSet::iterator &it)
bool exists(const ProofId &proofid) const
Return true if the (valid) proof exists, but only for non-dangling proofs.
PendingNodeSet pendingNodes
BlockHash rejectedContenderPrevBlockHash
bool verify() const
Perform consistency check on internal data structures.
bool hasRemoteProofStatus(const ProofId &proofid) const
std::optional< StakeContenderCacheInfo > getStakeContenderInfo(const StakeContenderId &contenderId) const
bool forPeer(const ProofId &proofid, Callable &&func) const
void clearRemoteProofs(NodeId nodeid)
void finalizeStakeContender(const StakeContenderId &contenderId, BlockHash &prevblockhash, std::vector< std::pair< ProofId, CScript > > &newWinners)
bool latchAvaproofsSent(NodeId nodeid)
Flag that a node did send its compact proofs.
void cleanupStakeContenders(const int requestedMinHeight)
Make some of the contender cache API available.
bool updateNextRequestTimeForPoll(NodeId nodeid, SteadyMilliseconds timeout, uint64_t round)
static constexpr int SELECT_PEER_MAX_RETRY
ProofIdSet m_unbroadcast_proofids
Track proof ids to broadcast.
bool loadPeersFromFile(const fs::path &dumpPath, std::unordered_set< ProofRef, SaltedProofHasher > &registeredProofs)
RejectionMode
Rejection mode.
void addUnbroadcastProof(const ProofId &proofid)
Proof broadcast API.
std::unordered_set< ProofRef, SaltedProofHasher > updatedBlockTip()
Update the peer set when a new block is connected.
void removeUnbroadcastProof(const ProofId &proofid)
void promoteStakeContendersToBlock(const CBlockIndex *pindex)
bool isBoundToPeer(const ProofId &proofid) const
bool setContenderStatusForLocalWinners(const CBlockIndex *prevblock, const std::vector< std::pair< ProofId, CScript > > winners, size_t maxPollable, std::vector< StakeContenderId > &pollableContenders)
ProofRadixTree shareableProofs
bool saveRemoteProof(const ProofId &proofid, const NodeId nodeid, const bool present)
bool getStakeContenderWinners(const BlockHash &prevblockhash, std::vector< std::pair< ProofId, CScript > > &winners) const
CRollingBloomFilter invalidProofs
Filter for proofs that are consensus-invalid or were recently invalidated by avalanche (finalized rej...
bool addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid, size_t max_elements)
uint64_t compact()
Trigger maintenance of internal data structures.
bool addRejectedContender(const ProofId &proofid, const BlockHash &prevblockhash)
Record a rejected stake contender for prevblockhash.
std::vector< Slot > slots
uint32_t totalPeersScore
Quorum management.
StakeContenderCache stakeContenderCache
bool hasAcceptedStakeWinner(const BlockHash &prevblockhash) const
void setInvalid(const ProofId &proofid)
int getStakeContenderStatus(const StakeContenderId &contenderId, BlockHash &prevblockhashout) const
bool isFlaky(const ProofId &proofid) const
ChainstateManager & chainman
bool isInvalid(const ProofId &proofid) const
std::unordered_set< ProofId, SaltedProofIdHasher > manualFlakyProofids
bool removePeer(const PeerId peerid)
Remove an existing peer.
bool isLocalProof(const ProofId &proofid) const
bool isImmature(const ProofId &proofid) const
bool rejectProof(const ProofId &proofid, RejectionMode mode=RejectionMode::DEFAULT)
RegistrationMode
Registration mode.
ProofPool conflictingProofPool
bool isStakingPreconsensusActivated() const
static constexpr size_t MAX_REMOTE_PROOFS
bool setFlaky(const ProofId &proofid)
void addStakeContender(const ProofRef &proof)
std::atomic< bool > needMoreNodes
Flag indicating that we failed to select a node and need to expand our node set.
PeerId selectPeer() const
Randomly select a peer to poll.
std::unordered_set< ProofId, SaltedProofIdHasher > rejectedContenderProofids
bool isInConflictingPool(const ProofId &proofid) const
bool isRemotelyPresentProof(const ProofId &proofid) const
static constexpr int SELECT_NODE_MAX_RETRY
void cleanupDanglingProofs(std::unordered_set< ProofRef, SaltedProofHasher > &registeredProofs)
void acceptStakeContender(const StakeContenderId &contenderId)
ProofRef getProof(const ProofId &proofid) const
bool registerProof(const ProofRef &proof, ProofRegistrationState &registrationState, RegistrationMode mode=RegistrationMode::DEFAULT)
void rejectStakeContender(const StakeContenderId &contenderId)
bool removeNodeFromPeer(const PeerSet::iterator &it, uint32_t count=1)
bool updateNextPossibleConflictTime(PeerId peerid, const std::chrono::seconds &nextTime)
Proof and Peer related API.
void moveToConflictingPool(const ProofContainer &proofs)
bool setStakeContenderWinners(const CBlockIndex *pindex, const std::vector< CScript > &payoutScripts)
@ DUPLICATED
Already in pool.
Definition proofpool.h:84
@ REJECTED
Rejected due to conflicts.
Definition proofpool.h:82
@ SUCCEED
Added successfully.
Definition proofpool.h:83
AddProofStatus addProofIfPreferred(const ProofRef &proof, ConflictingProofSet &conflictingProofs)
Attempt to add a proof to the pool.
Definition proofpool.cpp:58
size_t size() const
Definition proofpool.h:140
AddProofStatus addProofIfNoConflict(const ProofRef &proof, ConflictingProofSet &conflictingProofs)
Attempt to add a proof to the pool, and fail if there is a conflict on any UTXO.
Definition proofpool.cpp:30
size_t countProofs() const
bool removeProof(ProofId proofid)
Definition proofpool.cpp:83
void forEachProof(Callable &&func) const
Definition proofpool.h:123
ProofRef getProof(const ProofId &proofid) const
std::set< ProofRef, ConflictingProofComparator > ConflictingProofSet
Definition proofpool.h:87
ProofRef getLowestScoreProof() const
std::unordered_set< ProofRef, SaltedProofHasher > rescan(PeerManager &peerManager)
Definition proofpool.cpp:90
ConflictingProofSet getConflicts(const ProofRef &proof) const
Return proofs in this pool that share any UTXO with proof.
Definition proofpool.cpp:14
bool getWinners(const BlockHash &prevblockhash, std::vector< std::pair< ProofId, CScript > > &winners) const
bool accept(const StakeContenderId &contenderId)
Helpers to set avalanche state of a contender.
void cleanup(const int requestedMinHeight)
size_t getPollableContenders(const BlockHash &prevblockhash, size_t maxPollable, std::vector< StakeContenderId > &pollableContenders) const
Get the best ranking contenders, accepted contenders ranking first.
bool reject(const StakeContenderId &contenderId)
bool hasAcceptedWinner(const BlockHash &prevblockhash) const
True if any accepted contender is in the winner set for prevblockhash.
bool setWinners(const CBlockIndex *pindex, const std::vector< CScript > &payoutScripts)
Set proof(s) that should be treated as winners (already finalized).
bool add(const CBlockIndex *pindex, const ProofRef &proof, uint8_t status=StakeContenderStatus::UNKNOWN)
Add a proof to consider in staking rewards pre-consensus.
std::optional< StakeContenderCacheInfo > getContenderInfo(const StakeContenderId &contenderId) const
void promoteToBlock(const CBlockIndex *activeTip, std::function< bool(const ProofId &proofid)> const &shouldPromote)
Promote cache entries to a the active chain tip.
int getVoteStatus(const StakeContenderId &contenderId, BlockHash &prevblockhashout) const
Get contender acceptance state for avalanche voting.
bool finalize(const StakeContenderId &contenderId)
std::string ToString() const
Definition uint256.h:117
std::string GetHex() const
Definition uint256.cpp:10
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition fs.h:30
static const uint256 ZERO
Definition uint256.h:210
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
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
#define LogTrace(category,...)
Definition logging.h:448
#define LogDebug(category,...)
Definition logging.h:446
#define LogPrintf(...)
Definition logging.h:424
@ AVALANCHE
Definition logging.h:91
ProofRegistrationResult
static constexpr uint32_t AVALANCHE_MAX_IMMATURE_PROOFS
Maximum number of immature proofs the peer manager will accept from the network.
Definition peermanager.h:44
static bool isImmatureState(const ProofValidationState &state)
static constexpr uint64_t PEERS_DUMP_VERSION
PeerId selectPeerImpl(const std::vector< Slot > &slots, const uint64_t slot, const uint64_t max)
Internal methods that are exposed for testing purposes.
RCUPtr< const Proof > ProofRef
Definition proof.h:183
FILE * fopen(const fs::path &p, const char *mode)
Definition fs.cpp:30
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
Definition nodeid.h:15
Response response
A BlockHash is a unqiue identifier for a block.
Definition blockhash.h:13
RCUPtr< T > remove(const KeyType &key)
Remove an element from the tree.
Definition radix.h:180
RCUPtr< T > get(const KeyType &key)
Get the value corresponding to a key.
Definition radix.h:117
bool forEachLeaf(Callable &&func) const
Definition radix.h:143
bool insert(const RCUPtr< T > &value)
Insert a value into the tree.
Definition radix.h:111
Facility for using an uint256 as a radix tree key.
uint64_t last_round
Definition node.h:24
SteadyMilliseconds nextRequestTime
Definition node.h:22
bool avaproofsSent
Definition node.h:23
std::chrono::seconds registration_time
Definition peermanager.h:93
std::chrono::seconds nextPossibleConflictTime
Definition peermanager.h:94
uint32_t node_count
Definition peermanager.h:87
static constexpr auto DANGLING_TIMEOUT
Consider dropping the peer if no node is attached after this timeout expired.
uint32_t getScore() const
uint64_t getStop() const
Definition peermanager.h:73
uint64_t getStart() const
Definition peermanager.h:72
PeerId getPeerId() const
Definition peermanager.h:75
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...
#define LOCK(cs)
Definition sync.h:295
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:343
#define AssertLockHeld(cs)
Definition sync.h:146
static int count
#define NO_THREAD_SAFETY_ANALYSIS
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition time.cpp:80
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition time.h:33
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
assert(!tx.IsCoinBase())