Bitcoin ABC 0.31.1
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 auto &pview = peers.get<by_proofid>();
35 auto it = pview.find(proofid);
36 if (it == pview.end()) {
37 // If the node exists, it is actually updating its proof to an unknown
38 // one. In this case we need to remove it so it is not both active and
39 // pending at the same time.
40 removeNode(nodeid);
41 pendingNodes.emplace(proofid, nodeid);
42 return false;
43 }
44
45 return addOrUpdateNode(peers.project<0>(it), nodeid);
46}
47
48bool PeerManager::addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid) {
49 assert(it != peers.end());
50
51 const PeerId peerid = it->peerid;
52
53 auto nit = nodes.find(nodeid);
54 if (nit == nodes.end()) {
55 if (!nodes.emplace(nodeid, peerid).second) {
56 return false;
57 }
58 } else {
59 const PeerId oldpeerid = nit->peerid;
60 if (!nodes.modify(nit, [&](Node &n) { n.peerid = peerid; })) {
61 return false;
62 }
63
64 // We actually have this node already, we need to update it.
65 bool success = removeNodeFromPeer(peers.find(oldpeerid));
66 assert(success);
67 }
68
69 // Then increase the node counter, and create the slot if needed
70 bool success = addNodeToPeer(it);
71 assert(success);
72
73 // If the added node was in the pending set, remove it
74 pendingNodes.get<by_nodeid>().erase(nodeid);
75
76 // If the proof was in the dangling pool, remove it
77 const ProofId &proofid = it->getProofId();
78 if (danglingProofPool.getProof(proofid)) {
80 }
81
82 // We know for sure there is at least 1 node. Note that this can fail if
83 // there is more than 1, in this case it's a no-op.
84 shareableProofs.insert(it->proof);
85
86 return true;
87}
88
89bool PeerManager::addNodeToPeer(const PeerSet::iterator &it) {
90 assert(it != peers.end());
91 return peers.modify(it, [&](Peer &p) {
92 if (p.node_count++ > 0) {
93 // We are done.
94 return;
95 }
96
97 // We need to allocate this peer.
98 p.index = uint32_t(slots.size());
99 const uint32_t score = p.getScore();
100 const uint64_t start = slotCount;
101 slots.emplace_back(start, score, it->peerid);
102 slotCount = start + score;
103
104 // Add to our allocated score when we allocate a new peer in the slots
105 connectedPeersScore += score;
106 });
107}
108
110 // Remove all the remote proofs from this node
111 auto &remoteProofsView = remoteProofs.get<by_nodeid>();
112 auto [begin, end] = remoteProofsView.equal_range(nodeid);
113 remoteProofsView.erase(begin, end);
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 (!localProof || it->getProofId() != localProof->getId()) {
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 auto it = nodes.find(nodeid);
187 if (it == nodes.end()) {
188 return false;
189 }
190
191 return nodes.modify(it, [&](Node &n) { n.nextRequestTime = timeout; });
192}
193
195 auto it = nodes.find(nodeid);
196 if (it == nodes.end()) {
197 return false;
198 }
199
200 return !it->avaproofsSent &&
201 nodes.modify(it, [&](Node &n) { n.avaproofsSent = true; });
202}
203
204static bool isImmatureState(const ProofValidationState &state) {
206}
207
209 PeerId peerid, const std::chrono::seconds &nextTime) {
210 auto it = peers.find(peerid);
211 if (it == peers.end()) {
212 // No such peer
213 return false;
214 }
215
216 // Make sure we don't move the time in the past.
217 peers.modify(it, [&](Peer &p) {
219 std::max(p.nextPossibleConflictTime, nextTime);
220 });
221
222 return it->nextPossibleConflictTime == nextTime;
223}
224
226 auto it = peers.find(peerid);
227 if (it == peers.end()) {
228 // No such peer
229 return false;
230 }
231
232 peers.modify(it, [&](Peer &p) { p.hasFinalized = true; });
233
234 return true;
235}
236
237template <typename ProofContainer>
238void PeerManager::moveToConflictingPool(const ProofContainer &proofs) {
239 auto &peersView = peers.get<by_proofid>();
240 for (const ProofRef &proof : proofs) {
241 auto it = peersView.find(proof->getId());
242 if (it != peersView.end()) {
243 removePeer(it->peerid);
244 }
245
247 }
248}
249
251 ProofRegistrationState &registrationState,
252 RegistrationMode mode) {
253 assert(proof);
254
255 const ProofId &proofid = proof->getId();
256
257 auto invalidate = [&](ProofRegistrationResult result,
258 const std::string &message) {
259 return registrationState.Invalid(
260 result, message, strprintf("proofid: %s", proofid.ToString()));
261 };
262
263 if ((mode != RegistrationMode::FORCE_ACCEPT ||
264 !isInConflictingPool(proofid)) &&
265 exists(proofid)) {
266 // In default mode, we expect the proof to be unknown, i.e. in none of
267 // the pools.
268 // In forced accept mode, the proof can be in the conflicting pool.
270 "proof-already-registered");
271 }
272
273 if (danglingProofPool.getProof(proofid) &&
274 pendingNodes.count(proofid) == 0) {
275 // Don't attempt to register a proof that we already evicted because it
276 // was dangling, but rather attempt to retrieve an associated node.
277 needMoreNodes = true;
278 return invalidate(ProofRegistrationResult::DANGLING, "dangling-proof");
279 }
280
281 // Check the proof's validity.
282 ProofValidationState validationState;
283 if (!WITH_LOCK(cs_main, return proof->verify(stakeUtxoDustThreshold,
284 chainman, validationState))) {
285 if (isImmatureState(validationState)) {
289 // Adding this proof exceeds the immature pool limit, so evict
290 // the lowest scoring proof.
293 }
294
295 return invalidate(ProofRegistrationResult::IMMATURE,
296 "immature-proof");
297 }
298
299 if (validationState.GetResult() ==
302 "utxo-missing-or-spent");
303 }
304
305 // Reject invalid proof.
306 return invalidate(ProofRegistrationResult::INVALID, "invalid-proof");
307 }
308
309 auto now = GetTime<std::chrono::seconds>();
310 auto nextCooldownTimePoint =
311 now + std::chrono::seconds(gArgs.GetIntArg(
312 "-avalancheconflictingproofcooldown",
314
315 ProofPool::ConflictingProofSet conflictingProofs;
316 switch (validProofPool.addProofIfNoConflict(proof, conflictingProofs)) {
317 case ProofPool::AddProofStatus::REJECTED: {
318 if (mode != RegistrationMode::FORCE_ACCEPT) {
319 auto bestPossibleConflictTime = std::chrono::seconds(0);
320 auto &pview = peers.get<by_proofid>();
321 for (auto &conflictingProof : conflictingProofs) {
322 auto it = pview.find(conflictingProof->getId());
323 assert(it != pview.end());
324
325 // Search the most recent time over the peers
326 bestPossibleConflictTime = std::max(
327 bestPossibleConflictTime, it->nextPossibleConflictTime);
328
330 nextCooldownTimePoint);
331 }
332
333 if (bestPossibleConflictTime > now) {
334 // Cooldown not elapsed, reject the proof.
335 return invalidate(
337 "cooldown-not-elapsed");
338 }
339
340 // Give the proof a chance to replace the conflicting ones.
342 // If we have overridden other proofs due to conflict,
343 // remove the peers and attempt to move them to the
344 // conflicting pool.
345 moveToConflictingPool(conflictingProofs);
346
347 // Replacement is successful, continue to peer creation
348 break;
349 }
350
351 // Not the preferred proof, or replacement is not enabled
353 ProofPool::AddProofStatus::REJECTED
355 "rejected-proof")
357 "conflicting-utxos");
358 }
359
361
362 // Move the conflicting proofs from the valid pool to the
363 // conflicting pool
364 moveToConflictingPool(conflictingProofs);
365
366 auto status = validProofPool.addProofIfNoConflict(proof);
367 assert(status == ProofPool::AddProofStatus::SUCCEED);
368
369 break;
370 }
371 case ProofPool::AddProofStatus::DUPLICATED:
372 // If the proof was already in the pool, don't duplicate the peer.
374 "proof-already-registered");
375 case ProofPool::AddProofStatus::SUCCEED:
376 break;
377
378 // No default case, so the compiler can warn about missing cases
379 }
380
381 // At this stage we are going to create a peer so the proof should never
382 // exist in the conflicting pool, but use belt and suspenders.
384
385 // New peer means new peerid!
386 const PeerId peerid = nextPeerId++;
387
388 // We have no peer for this proof, time to create it.
389 auto inserted = peers.emplace(peerid, proof, nextCooldownTimePoint);
390 assert(inserted.second);
391
392 if (localProof && proof->getId() == localProof->getId()) {
393 // Add it to the shareable proofs even if there is no node, we are the
394 // node. Otherwise it will be inserted after a node is attached to the
395 // proof.
396 shareableProofs.insert(proof);
397 }
398
399 // Add to our registered score when adding to the peer list
400 totalPeersScore += proof->getScore();
401
402 // If there are nodes waiting for this proof, add them
403 auto &pendingNodesView = pendingNodes.get<by_proofid>();
404 auto range = pendingNodesView.equal_range(proofid);
405
406 // We want to update the nodes then remove them from the pending set. That
407 // will invalidate the range iterators, so we need to save the node ids
408 // first before we can loop over them.
409 std::vector<NodeId> nodeids;
410 nodeids.reserve(std::distance(range.first, range.second));
411 std::transform(range.first, range.second, std::back_inserter(nodeids),
412 [](const PendingNode &n) { return n.nodeid; });
413
414 for (const NodeId &nodeid : nodeids) {
415 addOrUpdateNode(inserted.first, nodeid);
416 }
417
419 addStakeContender(proof);
420 }
421
422 return true;
423}
424
426 if (isDangling(proofid) && mode == RejectionMode::INVALIDATE) {
428 return true;
429 }
430
431 if (!exists(proofid)) {
432 return false;
433 }
434
435 if (immatureProofPool.removeProof(proofid)) {
436 return true;
437 }
438
439 if (mode == RejectionMode::DEFAULT &&
441 // In default mode we keep the proof in the conflicting pool
442 return true;
443 }
444
445 if (mode == RejectionMode::INVALIDATE &&
447 // In invalidate mode we remove the proof completely
448 return true;
449 }
450
451 auto &pview = peers.get<by_proofid>();
452 auto it = pview.find(proofid);
453 assert(it != pview.end());
454
455 const ProofRef proof = it->proof;
456
457 if (!removePeer(it->peerid)) {
458 return false;
459 }
460
461 // If there was conflicting proofs, attempt to pull them back
462 for (const SignedStake &ss : proof->getStakes()) {
463 const ProofRef conflictingProof =
464 conflictingProofPool.getProof(ss.getStake().getUTXO());
465 if (!conflictingProof) {
466 continue;
467 }
468
469 conflictingProofPool.removeProof(conflictingProof->getId());
470 registerProof(conflictingProof);
471 }
472
473 if (mode == RejectionMode::DEFAULT) {
475 }
476
477 return true;
478}
479
481 std::unordered_set<ProofRef, SaltedProofHasher> &registeredProofs) {
482 registeredProofs.clear();
483 const auto now = GetTime<std::chrono::seconds>();
484
485 std::vector<ProofRef> newlyDanglingProofs;
486 for (const Peer &peer : peers) {
487 // If the peer is not our local proof, has been registered for some
488 // time and has no node attached, discard it.
489 if ((!localProof || peer.getProofId() != localProof->getId()) &&
490 peer.node_count == 0 &&
491 (peer.registration_time + Peer::DANGLING_TIMEOUT) <= now) {
492 // Check the remotes status to determine if we should set the proof
493 // as dangling. This prevents from dropping a proof on our own due
494 // to a network issue. If the remote presence status is inconclusive
495 // we assume our own position (missing = false).
496 if (!getRemotePresenceStatus(peer.getProofId()).value_or(false)) {
497 newlyDanglingProofs.push_back(peer.proof);
498 }
499 }
500 }
501
502 // Similarly, check if we have dangling proofs that could be pulled back
503 // because the network says so.
504 std::vector<ProofRef> previouslyDanglingProofs;
505 danglingProofPool.forEachProof([&](const ProofRef &proof) {
506 if (getRemotePresenceStatus(proof->getId()).value_or(false)) {
507 previouslyDanglingProofs.push_back(proof);
508 }
509 });
510 for (const ProofRef &proof : previouslyDanglingProofs) {
511 danglingProofPool.removeProof(proof->getId());
512 if (registerProof(proof)) {
513 registeredProofs.insert(proof);
514 }
515 }
516
517 for (const ProofRef &proof : newlyDanglingProofs) {
518 rejectProof(proof->getId(), RejectionMode::INVALIDATE);
520 // If the proof is added, it means there is no better conflicting
521 // dangling proof and this is not a duplicated, so it's worth
522 // printing a message to the log.
524 "Proof dangling for too long (no connected node): %s\n",
525 proof->getId().GetHex());
526 }
527 }
528
529 // If we have dangling proof, this is a good indicator that we need to
530 // request more nodes from our peers.
531 needMoreNodes = !newlyDanglingProofs.empty();
532}
533
535 for (int retry = 0; retry < SELECT_NODE_MAX_RETRY; retry++) {
536 const PeerId p = selectPeer();
537
538 // If we cannot find a peer, it may be due to the fact that it is
539 // unlikely due to high fragmentation, so compact and retry.
540 if (p == NO_PEER) {
541 compact();
542 continue;
543 }
544
545 // See if that peer has an available node.
546 auto &nview = nodes.get<next_request_time>();
547 auto it = nview.lower_bound(boost::make_tuple(p, SteadyMilliseconds()));
548 if (it != nview.end() && it->peerid == p &&
549 it->nextRequestTime <= Now<SteadyMilliseconds>()) {
550 return it->nodeid;
551 }
552 }
553
554 // We failed to find a node to query, flag this so we can request more
555 needMoreNodes = true;
556
557 return NO_NODE;
558}
559
560std::unordered_set<ProofRef, SaltedProofHasher> PeerManager::updatedBlockTip() {
561 std::vector<ProofId> invalidProofIds;
562 std::vector<ProofRef> newImmatures;
563
564 {
565 LOCK(cs_main);
566
567 for (const auto &p : peers) {
569 if (!p.proof->verify(stakeUtxoDustThreshold, chainman, state)) {
570 if (isImmatureState(state)) {
571 newImmatures.push_back(p.proof);
572 }
573 invalidProofIds.push_back(p.getProofId());
574
576 "Invalidating proof %s: verification failed (%s)\n",
577 p.proof->getId().GetHex(), state.ToString());
578 }
579 }
580
581 // Disable thread safety analysis here because it does not play nicely
582 // with the lambda
584 [&](const ProofRef &proof) NO_THREAD_SAFETY_ANALYSIS {
587 if (!proof->verify(stakeUtxoDustThreshold, chainman, state)) {
588 invalidProofIds.push_back(proof->getId());
589
590 LogPrint(
592 "Invalidating dangling proof %s: verification failed "
593 "(%s)\n",
594 proof->getId().GetHex(), state.ToString());
595 }
596 });
597 }
598
599 // Remove the invalid proofs before the immature rescan. This makes it
600 // possible to pull back proofs with utxos that conflicted with these
601 // invalid proofs.
602 for (const ProofId &invalidProofId : invalidProofIds) {
603 rejectProof(invalidProofId, RejectionMode::INVALIDATE);
604 }
605
606 auto registeredProofs = immatureProofPool.rescan(*this);
607
608 for (auto &p : newImmatures) {
610 }
611
612 return registeredProofs;
613}
614
616 ProofRef proof;
617
618 forPeer(proofid, [&](const Peer &p) {
619 proof = p.proof;
620 return true;
621 });
622
623 if (!proof) {
624 proof = conflictingProofPool.getProof(proofid);
625 }
626
627 if (!proof) {
628 proof = immatureProofPool.getProof(proofid);
629 }
630
631 return proof;
632}
633
634bool PeerManager::isBoundToPeer(const ProofId &proofid) const {
635 auto &pview = peers.get<by_proofid>();
636 return pview.find(proofid) != pview.end();
637}
638
639bool PeerManager::isImmature(const ProofId &proofid) const {
640 return immatureProofPool.getProof(proofid) != nullptr;
641}
642
643bool PeerManager::isInConflictingPool(const ProofId &proofid) const {
644 return conflictingProofPool.getProof(proofid) != nullptr;
645}
646
647bool PeerManager::isDangling(const ProofId &proofid) const {
648 return danglingProofPool.getProof(proofid) != nullptr;
649}
650
651void PeerManager::setInvalid(const ProofId &proofid) {
652 invalidProofs.insert(proofid);
653}
654
655bool PeerManager::isInvalid(const ProofId &proofid) const {
656 return invalidProofs.contains(proofid);
657}
658
661}
662
663bool PeerManager::saveRemoteProof(const ProofId &proofid, const NodeId nodeid,
664 const bool present) {
665 if (m_stakingPreConsensus && isBoundToPeer(proofid) &&
666 !isRemoteProof(proofid)) {
667 // If this is the first time this peer's proof becomes a remote proof of
668 // any node, ensure it is included in the contender cache. There is a
669 // special case where the contender cache can lose track of a proof if
670 // it is not saved as a remote proof before the next finalized block
671 // (triggering promotion, where non-remote cache entries are dropped).
672 // This does not happen in the hot path since receiving a proof
673 // immediately saves it as a remote, however it becomes more likely if
674 // the proof was loaded from a file (-persistavapeers) or added via RPC.
675 addStakeContender(getProof(proofid));
676 }
677
678 // Get how many proofs this node has announced
679 auto &remoteProofsByLastUpdate = remoteProofs.get<by_lastUpdate>();
680 auto [begin, end] = remoteProofsByLastUpdate.equal_range(nodeid);
681
682 // Limit the number of proofs a single node can save:
683 // - At least MAX_REMOTE_PROOFS
684 // - Up to 2x as much as we have
685 // The MAX_REMOTE_PROOFS minimum is there to ensure we don't overlimit at
686 // startup when we don't have proofs yet.
687 while (size_t(std::distance(begin, end)) >=
688 std::max(MAX_REMOTE_PROOFS, 2 * peers.size())) {
689 // Remove the proof with the oldest update time
690 begin = remoteProofsByLastUpdate.erase(begin);
691 }
692
693 auto it = remoteProofs.find(boost::make_tuple(proofid, nodeid));
694 if (it != remoteProofs.end()) {
695 remoteProofs.erase(it);
696 }
697
698 return remoteProofs
699 .emplace(RemoteProof{proofid, nodeid, GetTime<std::chrono::seconds>(),
700 present})
701 .second;
702}
703
704std::vector<RemoteProof>
706 std::vector<RemoteProof> nodeRemoteProofs;
707
708 auto &remoteProofsByLastUpdate = remoteProofs.get<by_lastUpdate>();
709 auto [begin, end] = remoteProofsByLastUpdate.equal_range(nodeid);
710
711 for (auto &it = begin; it != end; it++) {
712 nodeRemoteProofs.emplace_back(*it);
713 }
714
715 return nodeRemoteProofs;
716}
717
718bool PeerManager::isRemoteProof(const ProofId &proofid) const {
719 auto &view = remoteProofs.get<by_proofid>();
720 return view.count(proofid) > 0;
721}
722
723bool PeerManager::removePeer(const PeerId peerid) {
724 auto it = peers.find(peerid);
725 if (it == peers.end()) {
726 return false;
727 }
728
729 // Remove all nodes from this peer.
730 removeNodeFromPeer(it, it->node_count);
731
732 auto &nview = nodes.get<next_request_time>();
733
734 // Add the nodes to the pending set
735 auto range = nview.equal_range(peerid);
736 for (auto &nit = range.first; nit != range.second; ++nit) {
737 pendingNodes.emplace(it->getProofId(), nit->nodeid);
738 };
739
740 // Remove nodes associated with this peer, unless their timeout is still
741 // active. This ensure that we don't overquery them in case they are
742 // subsequently added to another peer.
743 nview.erase(
744 nview.lower_bound(boost::make_tuple(peerid, SteadyMilliseconds())),
745 nview.upper_bound(
746 boost::make_tuple(peerid, Now<SteadyMilliseconds>())));
747
748 // Release UTXOs attached to this proof.
749 validProofPool.removeProof(it->getProofId());
750
751 // If there were nodes attached, remove from the radix tree as well
752 auto removed = shareableProofs.remove(Uint256RadixKey(it->getProofId()));
753
754 m_unbroadcast_proofids.erase(it->getProofId());
755
756 // Remove the peer from the PeerSet and remove its score from the registered
757 // score total.
758 assert(totalPeersScore >= it->getScore());
759 totalPeersScore -= it->getScore();
760 peers.erase(it);
761 return true;
762}
763
765 if (slots.empty() || slotCount == 0) {
766 return NO_PEER;
767 }
768
769 const uint64_t max = slotCount;
770 for (int retry = 0; retry < SELECT_PEER_MAX_RETRY; retry++) {
771 size_t i = selectPeerImpl(slots, GetRand(max), max);
772 if (i != NO_PEER) {
773 return i;
774 }
775 }
776
777 return NO_PEER;
778}
779
781 // There is nothing to compact.
782 if (fragmentation == 0) {
783 return 0;
784 }
785
786 std::vector<Slot> newslots;
787 newslots.reserve(peers.size());
788
789 uint64_t prevStop = 0;
790 uint32_t i = 0;
791 for (auto it = peers.begin(); it != peers.end(); it++) {
792 if (it->node_count == 0) {
793 continue;
794 }
795
796 newslots.emplace_back(prevStop, it->getScore(), it->peerid);
797 prevStop = slots[i].getStop();
798 if (!peers.modify(it, [&](Peer &p) { p.index = i++; })) {
799 return 0;
800 }
801 }
802
803 slots = std::move(newslots);
804
805 const uint64_t saved = slotCount - prevStop;
806 slotCount = prevStop;
807 fragmentation = 0;
808
809 return saved;
810}
811
813 uint64_t prevStop = 0;
814 uint32_t scoreFromSlots = 0;
815 for (size_t i = 0; i < slots.size(); i++) {
816 const Slot &s = slots[i];
817
818 // Slots must be in correct order.
819 if (s.getStart() < prevStop) {
820 return false;
821 }
822
823 prevStop = s.getStop();
824
825 // If this is a dead slot, then nothing more needs to be checked.
826 if (s.getPeerId() == NO_PEER) {
827 continue;
828 }
829
830 // We have a live slot, verify index.
831 auto it = peers.find(s.getPeerId());
832 if (it == peers.end() || it->index != i) {
833 return false;
834 }
835
836 // Accumulate score across slots
837 scoreFromSlots += slots[i].getScore();
838 }
839
840 // Score across slots must be the same as our allocated score
841 if (scoreFromSlots != connectedPeersScore) {
842 return false;
843 }
844
845 uint32_t scoreFromAllPeers = 0;
846 uint32_t scoreFromPeersWithNodes = 0;
847
848 std::unordered_set<COutPoint, SaltedOutpointHasher> peersUtxos;
849 for (const auto &p : peers) {
850 // Accumulate the score across peers to compare with total known score
851 scoreFromAllPeers += p.getScore();
852
853 // A peer should have a proof attached
854 if (!p.proof) {
855 return false;
856 }
857
858 // Check proof pool consistency
859 for (const auto &ss : p.proof->getStakes()) {
860 const COutPoint &outpoint = ss.getStake().getUTXO();
861 auto proof = validProofPool.getProof(outpoint);
862
863 if (!proof) {
864 // Missing utxo
865 return false;
866 }
867 if (proof != p.proof) {
868 // Wrong proof
869 return false;
870 }
871
872 if (!peersUtxos.emplace(outpoint).second) {
873 // Duplicated utxo
874 return false;
875 }
876 }
877
878 // Count node attached to this peer.
879 const auto count_nodes = [&]() {
880 size_t count = 0;
881 auto &nview = nodes.get<next_request_time>();
882 auto begin = nview.lower_bound(
883 boost::make_tuple(p.peerid, SteadyMilliseconds()));
884 auto end = nview.upper_bound(
885 boost::make_tuple(p.peerid + 1, SteadyMilliseconds()));
886
887 for (auto it = begin; it != end; ++it) {
888 count++;
889 }
890
891 return count;
892 };
893
894 if (p.node_count != count_nodes()) {
895 return false;
896 }
897
898 // If there are no nodes attached to this peer, then we are done.
899 if (p.node_count == 0) {
900 continue;
901 }
902
903 scoreFromPeersWithNodes += p.getScore();
904 // The index must point to a slot refering to this peer.
905 if (p.index >= slots.size() || slots[p.index].getPeerId() != p.peerid) {
906 return false;
907 }
908
909 // If the score do not match, same thing.
910 if (slots[p.index].getScore() != p.getScore()) {
911 return false;
912 }
913
914 // Check the proof is in the radix tree only if there are nodes attached
915 if (((localProof && p.getProofId() == localProof->getId()) ||
916 p.node_count > 0) &&
917 shareableProofs.get(p.getProofId()) == nullptr) {
918 return false;
919 }
920 if (p.node_count == 0 &&
921 shareableProofs.get(p.getProofId()) != nullptr) {
922 return false;
923 }
924 }
925
926 // Check our accumulated scores against our registred and allocated scores
927 if (scoreFromAllPeers != totalPeersScore) {
928 return false;
929 }
930 if (scoreFromPeersWithNodes != connectedPeersScore) {
931 return false;
932 }
933
934 // We checked the utxo consistency for all our peers utxos already, so if
935 // the pool size differs from the expected one there are dangling utxos.
936 if (validProofPool.size() != peersUtxos.size()) {
937 return false;
938 }
939
940 // Check there is no dangling proof in the radix tree
942 return isBoundToPeer(pLeaf->getId());
943 });
944}
945
946PeerId selectPeerImpl(const std::vector<Slot> &slots, const uint64_t slot,
947 const uint64_t max) {
948 assert(slot <= max);
949
950 size_t begin = 0, end = slots.size();
951 uint64_t bottom = 0, top = max;
952
953 // Try to find the slot using dichotomic search.
954 while ((end - begin) > 8) {
955 // The slot we picked in not allocated.
956 if (slot < bottom || slot >= top) {
957 return NO_PEER;
958 }
959
960 // Guesstimate the position of the slot.
961 size_t i = begin + ((slot - bottom) * (end - begin) / (top - bottom));
962 assert(begin <= i && i < end);
963
964 // We have a match.
965 if (slots[i].contains(slot)) {
966 return slots[i].getPeerId();
967 }
968
969 // We undershooted.
970 if (slots[i].precedes(slot)) {
971 begin = i + 1;
972 if (begin >= end) {
973 return NO_PEER;
974 }
975
976 bottom = slots[begin].getStart();
977 continue;
978 }
979
980 // We overshooted.
981 if (slots[i].follows(slot)) {
982 end = i;
983 top = slots[end].getStart();
984 continue;
985 }
986
987 // We have an unalocated slot.
988 return NO_PEER;
989 }
990
991 // Enough of that nonsense, let fallback to linear search.
992 for (size_t i = begin; i < end; i++) {
993 // We have a match.
994 if (slots[i].contains(slot)) {
995 return slots[i].getPeerId();
996 }
997 }
998
999 // We failed to find a slot, retry.
1000 return NO_PEER;
1001}
1002
1004 // The proof should be bound to a peer
1005 if (isBoundToPeer(proofid)) {
1006 m_unbroadcast_proofids.insert(proofid);
1007 }
1008}
1009
1011 m_unbroadcast_proofids.erase(proofid);
1012}
1013
1015 const CBlockIndex *pprev,
1016 std::vector<std::pair<ProofId, CScript>> &winners) {
1017 if (!pprev) {
1018 return false;
1019 }
1020
1021 // Don't select proofs that have not been known for long enough, i.e. at
1022 // least since twice the dangling proof cleanup timeout before the last
1023 // block time, so we're sure to not account for proofs more recent than the
1024 // previous block or lacking node connected.
1025 // The previous block time is capped to now for the unlikely event the
1026 // previous block time is in the future.
1027 auto registrationDelay = std::chrono::duration_cast<std::chrono::seconds>(
1029 auto maxRegistrationDelay =
1030 std::chrono::duration_cast<std::chrono::seconds>(
1032 auto minRegistrationDelay =
1033 std::chrono::duration_cast<std::chrono::seconds>(
1035
1036 const int64_t refTime = std::min(pprev->GetBlockTime(), GetTime());
1037
1038 const int64_t targetRegistrationTime = refTime - registrationDelay.count();
1039 const int64_t maxRegistrationTime = refTime - minRegistrationDelay.count();
1040 const int64_t minRegistrationTime = refTime - maxRegistrationDelay.count();
1041
1042 const BlockHash prevblockhash = pprev->GetBlockHash();
1043
1044 std::vector<ProofRef> selectedProofs;
1045 ProofRef firstCompliantProof = ProofRef();
1046 while (selectedProofs.size() < peers.size()) {
1047 double bestRewardRank = std::numeric_limits<double>::max();
1048 ProofRef selectedProof = ProofRef();
1049 int64_t selectedProofRegistrationTime{0};
1050 StakeContenderId bestRewardHash;
1051
1052 for (const Peer &peer : peers) {
1053 if (!peer.proof) {
1054 // Should never happen, continue
1055 continue;
1056 }
1057
1058 if (!peer.hasFinalized ||
1059 peer.registration_time.count() >= maxRegistrationTime) {
1060 continue;
1061 }
1062
1063 if (std::find_if(selectedProofs.begin(), selectedProofs.end(),
1064 [&peer](const ProofRef &proof) {
1065 return peer.getProofId() == proof->getId();
1066 }) != selectedProofs.end()) {
1067 continue;
1068 }
1069
1070 StakeContenderId proofRewardHash(prevblockhash, peer.getProofId());
1071 if (proofRewardHash == uint256::ZERO) {
1072 // This either the result of an incredibly unlikely lucky hash,
1073 // or a the hash is getting abused. In this case, skip the
1074 // proof.
1075 LogPrintf(
1076 "Staking reward hash has a suspicious value of zero for "
1077 "proof %s and blockhash %s, skipping\n",
1078 peer.getProofId().ToString(), prevblockhash.ToString());
1079 continue;
1080 }
1081
1082 double proofRewardRank =
1083 proofRewardHash.ComputeProofRewardRank(peer.getScore());
1084 // If selectedProof is nullptr, this means that bestRewardRank is
1085 // MAX_DOUBLE so the comparison will always select this proof as the
1086 // preferred one. As a consequence it is safe to use 0 as a proofid.
1088 proofRewardHash, proofRewardRank, peer.getProofId(),
1089 bestRewardHash, bestRewardRank,
1090 selectedProof ? selectedProof->getId()
1091 : ProofId(uint256::ZERO))) {
1092 bestRewardRank = proofRewardRank;
1093 selectedProof = peer.proof;
1094 selectedProofRegistrationTime = peer.registration_time.count();
1095 bestRewardHash = proofRewardHash;
1096 }
1097 }
1098
1099 if (!selectedProof) {
1100 // No winner
1101 break;
1102 }
1103
1104 if (!firstCompliantProof &&
1105 selectedProofRegistrationTime < targetRegistrationTime) {
1106 firstCompliantProof = selectedProof;
1107 }
1108
1109 selectedProofs.push_back(selectedProof);
1110
1111 if (selectedProofRegistrationTime < minRegistrationTime &&
1112 !isFlaky(selectedProof->getId())) {
1113 break;
1114 }
1115 }
1116
1117 winners.clear();
1118
1119 if (!firstCompliantProof) {
1120 return false;
1121 }
1122
1123 winners.reserve(selectedProofs.size());
1124
1125 // Find the winner
1126 for (const ProofRef &proof : selectedProofs) {
1127 if (proof->getId() == firstCompliantProof->getId()) {
1128 winners.push_back({proof->getId(), proof->getPayoutScript()});
1129 }
1130 }
1131 // Add the others (if any) after the winner
1132 for (const ProofRef &proof : selectedProofs) {
1133 if (proof->getId() != firstCompliantProof->getId()) {
1134 winners.push_back({proof->getId(), proof->getPayoutScript()});
1135 }
1136 }
1137
1138 return true;
1139}
1140
1141bool PeerManager::setFlaky(const ProofId &proofid) {
1142 return manualFlakyProofids.insert(proofid).second;
1143}
1144
1145bool PeerManager::unsetFlaky(const ProofId &proofid) {
1146 return manualFlakyProofids.erase(proofid) > 0;
1147}
1148
1149bool PeerManager::isFlaky(const ProofId &proofid) const {
1150 if (localProof && proofid == localProof->getId()) {
1151 return false;
1152 }
1153
1154 if (manualFlakyProofids.count(proofid) > 0) {
1155 return true;
1156 }
1157
1158 // If we are missing connection to this proof, consider flaky
1159 if (forPeer(proofid,
1160 [](const Peer &peer) { return peer.node_count == 0; })) {
1161 return true;
1162 }
1163
1164 auto &remoteProofsByNodeId = remoteProofs.get<by_nodeid>();
1165 auto &nview = nodes.get<next_request_time>();
1166
1167 std::unordered_map<PeerId, std::unordered_set<ProofId, SaltedProofIdHasher>>
1168 missing_per_peer;
1169
1170 // Construct a set of missing proof ids per peer
1171 double total_score{0};
1172 for (const Peer &peer : peers) {
1173 const PeerId peerid = peer.peerid;
1174
1175 total_score += peer.getScore();
1176
1177 auto nodes_range = nview.equal_range(peerid);
1178 for (auto &nit = nodes_range.first; nit != nodes_range.second; ++nit) {
1179 auto proofs_range = remoteProofsByNodeId.equal_range(nit->nodeid);
1180 for (auto &proofit = proofs_range.first;
1181 proofit != proofs_range.second; ++proofit) {
1182 if (!proofit->present) {
1183 missing_per_peer[peerid].insert(proofit->proofid);
1184 }
1185 }
1186 };
1187 }
1188
1189 double missing_score{0};
1190
1191 // Now compute a score for the missing proof
1192 for (const auto &[peerid, missingProofs] : missing_per_peer) {
1193 if (missingProofs.size() > 3) {
1194 // Ignore peers with too many missing proofs
1195 continue;
1196 }
1197
1198 auto pit = peers.find(peerid);
1199 if (pit == peers.end()) {
1200 // Peer not found
1201 continue;
1202 }
1203
1204 if (missingProofs.count(proofid) > 0) {
1205 missing_score += pit->getScore();
1206 }
1207 }
1208
1209 return (missing_score / total_score) > 0.3;
1210}
1211
1212std::optional<bool>
1214 auto &remoteProofsView = remoteProofs.get<by_proofid>();
1215 auto [begin, end] = remoteProofsView.equal_range(proofid);
1216
1217 if (begin == end) {
1218 // No remote registered anything yet, we are on our own
1219 return std::nullopt;
1220 }
1221
1222 double total_score{0};
1223 double present_score{0};
1224 double missing_score{0};
1225
1226 for (auto it = begin; it != end; it++) {
1227 auto nit = nodes.find(it->nodeid);
1228 if (nit == nodes.end()) {
1229 // No such node
1230 continue;
1231 }
1232
1233 const PeerId peerid = nit->peerid;
1234
1235 auto pit = peers.find(peerid);
1236 if (pit == peers.end()) {
1237 // Peer not found
1238 continue;
1239 }
1240
1241 uint32_t node_count = pit->node_count;
1242 if (localProof && pit->getProofId() == localProof->getId()) {
1243 // If that's our local proof, account for ourself
1244 ++node_count;
1245 }
1246
1247 if (node_count == 0) {
1248 // should never happen
1249 continue;
1250 }
1251
1252 const double score = double(pit->getScore()) / node_count;
1253
1254 total_score += score;
1255 if (it->present) {
1256 present_score += score;
1257 } else {
1258 missing_score += score;
1259 }
1260 }
1261
1262 if (localProof) {
1263 auto &peersByProofid = peers.get<by_proofid>();
1264
1265 // Do we have a node connected for that proof ?
1266 bool present = false;
1267 auto pit = peersByProofid.find(proofid);
1268 if (pit != peersByProofid.end()) {
1269 present = pit->node_count > 0;
1270 }
1271
1272 pit = peersByProofid.find(localProof->getId());
1273 if (pit != peersByProofid.end()) {
1274 // Also divide by node_count, we can have several nodes even for our
1275 // local proof.
1276 const double score =
1277 double(pit->getScore()) / (1 + pit->node_count);
1278
1279 total_score += score;
1280 if (present) {
1281 present_score += score;
1282 } else {
1283 missing_score += score;
1284 }
1285 }
1286 }
1287
1288 if (present_score / total_score > 0.55) {
1289 return std::make_optional(true);
1290 }
1291
1292 if (missing_score / total_score > 0.55) {
1293 return std::make_optional(false);
1294 }
1295
1296 return std::nullopt;
1297}
1298
1299bool PeerManager::dumpPeersToFile(const fs::path &dumpPath) const {
1300 try {
1301 const fs::path dumpPathTmp = dumpPath + ".new";
1302 FILE *filestr = fsbridge::fopen(dumpPathTmp, "wb");
1303 if (!filestr) {
1304 return false;
1305 }
1306
1307 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
1308 file << PEERS_DUMP_VERSION;
1309 file << uint64_t(peers.size());
1310 for (const Peer &peer : peers) {
1311 file << peer.proof;
1312 file << peer.hasFinalized;
1313 file << int64_t(peer.registration_time.count());
1314 file << int64_t(peer.nextPossibleConflictTime.count());
1315 }
1316
1317 if (!FileCommit(file.Get())) {
1318 throw std::runtime_error(strprintf("Failed to commit to file %s",
1319 PathToString(dumpPathTmp)));
1320 }
1321 file.fclose();
1322
1323 if (!RenameOver(dumpPathTmp, dumpPath)) {
1324 throw std::runtime_error(strprintf("Rename failed from %s to %s",
1325 PathToString(dumpPathTmp),
1326 PathToString(dumpPath)));
1327 }
1328 } catch (const std::exception &e) {
1329 LogPrint(BCLog::AVALANCHE, "Failed to dump the avalanche peers: %s.\n",
1330 e.what());
1331 return false;
1332 }
1333
1334 LogPrint(BCLog::AVALANCHE, "Successfully dumped %d peers to %s.\n",
1335 peers.size(), PathToString(dumpPath));
1336
1337 return true;
1338}
1339
1341 const fs::path &dumpPath,
1342 std::unordered_set<ProofRef, SaltedProofHasher> &registeredProofs) {
1343 registeredProofs.clear();
1344
1345 FILE *filestr = fsbridge::fopen(dumpPath, "rb");
1346 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
1347 if (file.IsNull()) {
1349 "Failed to open avalanche peers file from disk.\n");
1350 return false;
1351 }
1352
1353 try {
1354 uint64_t version;
1355 file >> version;
1356
1357 if (version != PEERS_DUMP_VERSION) {
1359 "Unsupported avalanche peers file version.\n");
1360 return false;
1361 }
1362
1363 uint64_t numPeers;
1364 file >> numPeers;
1365
1366 auto &peersByProofId = peers.get<by_proofid>();
1367
1368 for (uint64_t i = 0; i < numPeers; i++) {
1369 ProofRef proof;
1370 bool hasFinalized;
1371 int64_t registrationTime;
1372 int64_t nextPossibleConflictTime;
1373
1374 file >> proof;
1375 file >> hasFinalized;
1376 file >> registrationTime;
1377 file >> nextPossibleConflictTime;
1378
1379 if (registerProof(proof)) {
1380 auto it = peersByProofId.find(proof->getId());
1381 if (it == peersByProofId.end()) {
1382 // Should never happen
1383 continue;
1384 }
1385
1386 // We don't modify any key so we don't need to rehash.
1387 // If the modify fails, it means we don't get the full benefit
1388 // from the file but we still added our peer to the set. The
1389 // non-overridden fields will be set the normal way.
1390 peersByProofId.modify(it, [&](Peer &p) {
1391 p.hasFinalized = hasFinalized;
1393 std::chrono::seconds{registrationTime};
1395 std::chrono::seconds{nextPossibleConflictTime};
1396 });
1397
1398 registeredProofs.insert(proof);
1399 }
1400 }
1401 } catch (const std::exception &e) {
1403 "Failed to read the avalanche peers file data on disk: %s.\n",
1404 e.what());
1405 return false;
1406 }
1407
1408 return true;
1409}
1410
1411void PeerManager::cleanupStakeContenders(const int requestedMinHeight) {
1412 stakeContenderCache.cleanup(requestedMinHeight);
1413}
1414
1416 const CBlockIndex *tip = WITH_LOCK(cs_main, return chainman.ActiveTip());
1417 stakeContenderCache.add(tip, proof);
1418
1419 const BlockHash blockhash = tip->GetBlockHash();
1420 const ProofId &proofid = proof->getId();
1422 "Cached stake contender with proofid %s, payout %s at block "
1423 "%s (height %d) with id %s\n",
1424 proofid.ToString(), HexStr(proof->getPayoutScript()),
1425 blockhash.ToString(), tip->nHeight,
1426 StakeContenderId(blockhash, proofid).ToString());
1427}
1428
1430 BlockHash &prevblockhashout) const {
1431 return stakeContenderCache.getVoteStatus(contenderId, prevblockhashout);
1432}
1433
1435 stakeContenderCache.accept(contenderId);
1436}
1437
1439 const StakeContenderId &contenderId, BlockHash &prevblockhash,
1440 std::vector<std::pair<ProofId, CScript>> &newWinners) {
1441 stakeContenderCache.finalize(contenderId);
1442
1443 // Get block hash related to this contender. We should not assume the
1444 // current chain tip is the block this contender is a winner for.
1445 getStakeContenderStatus(contenderId, prevblockhash);
1446
1447 // Calculate the new winners for this block
1448 stakeContenderCache.getWinners(prevblockhash, newWinners);
1449}
1450
1452 stakeContenderCache.reject(contenderId);
1453}
1454
1456 stakeContenderCache.promoteToBlock(pindex, [&](const ProofId &proofid) {
1457 return isRemoteProof(proofid) &&
1458 (isBoundToPeer(proofid) || isDangling(proofid));
1459 });
1460}
1461
1463 const CBlockIndex *prevblock,
1464 const std::vector<std::pair<ProofId, CScript>> winners, size_t maxPollable,
1465 std::vector<StakeContenderId> &pollableContenders) {
1466 const BlockHash prevblockhash = prevblock->GetBlockHash();
1467 // Set status for local winners
1468 for (const auto &winner : winners) {
1469 const StakeContenderId contenderId(prevblockhash, winner.first);
1470 stakeContenderCache.finalize(contenderId);
1472 "Stake contender set as local winner: proofid %s, payout "
1473 "%s at block %s (height %d) with id %s\n",
1474 winner.first.ToString(), HexStr(winner.second),
1475 prevblockhash.ToString(), prevblock->nHeight,
1476 contenderId.ToString());
1477 }
1478
1479 // Treat the highest ranking contender similarly to local winners except
1480 // that it is not automatically included in the winner set (unless it
1481 // happens to be selected as a local winner).
1482 if (stakeContenderCache.getPollableContenders(prevblockhash, maxPollable,
1483 pollableContenders) > 0) {
1484 // Accept the highest ranking contender. This is a no-op if the highest
1485 // ranking contender is already the local winner.
1486 stakeContenderCache.accept(pollableContenders[0]);
1488 "Stake contender set as best contender: id %s at block "
1489 "%s (height %d)\n",
1490 pollableContenders[0].ToString(),
1491 prevblockhash.ToString(), prevblock->nHeight);
1492 return true;
1493 }
1494
1495 return false;
1496}
1497
1499 const CBlockIndex *pindex, const std::vector<CScript> &payoutScripts) {
1500 return stakeContenderCache.setWinners(pindex, payoutScripts);
1501}
1502
1503} // namespace avalanche
ArgsManager gArgs
Definition: args.cpp:38
static constexpr PeerId NO_PEER
Definition: node.h:16
uint32_t PeerId
Definition: node.h:15
static constexpr size_t AVALANCHE_DEFAULT_CONFLICTING_PROOF_COOLDOWN
Conflicting proofs cooldown time default value in seconds.
Definition: avalanche.h:28
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:526
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:570
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:567
int fclose()
Definition: streams.h:541
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:179
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
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())
Definition: validation.h:1398
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.
uint32_t connectedPeersScore
Definition: peermanager.h:239
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.
Definition: peermanager.h:283
bool isDangling(const ProofId &proofid) const
bool updateNextRequestTime(NodeId nodeid, SteadyMilliseconds timeout)
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)
Definition: peermanager.cpp:89
bool exists(const ProofId &proofid) const
Return true if the (valid) proof exists, but only for non-dangling proofs.
Definition: peermanager.h:411
bool isRemoteProof(const ProofId &proofid) const
PendingNodeSet pendingNodes
Definition: peermanager.h:225
bool verify() const
Perform consistency check on internal data structures.
bool forPeer(const ProofId &proofid, Callable &&func) const
Definition: peermanager.h:419
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 addNode(NodeId nodeid, const ProofId &proofid)
Node API.
Definition: peermanager.cpp:33
static constexpr int SELECT_PEER_MAX_RETRY
Definition: peermanager.h:227
ProofIdSet m_unbroadcast_proofids
Track proof ids to broadcast.
Definition: peermanager.h:233
bool loadPeersFromFile(const fs::path &dumpPath, std::unordered_set< ProofRef, SaltedProofHasher > &registeredProofs)
RejectionMode
Rejection mode.
Definition: peermanager.h:399
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
Definition: peermanager.h:191
bool saveRemoteProof(const ProofId &proofid, const NodeId nodeid, const bool present)
CRollingBloomFilter invalidProofs
Filter for proofs that are consensus-invalid or were recently invalidated by avalanche (finalized rej...
Definition: peermanager.h:297
uint64_t compact()
Trigger maintenance of internal data structures.
std::vector< Slot > slots
Definition: peermanager.h:163
uint32_t totalPeersScore
Quorum management.
Definition: peermanager.h:238
ProofPool danglingProofPool
Definition: peermanager.h:188
StakeContenderCache stakeContenderCache
Definition: peermanager.h:301
void setInvalid(const ProofId &proofid)
int getStakeContenderStatus(const StakeContenderId &contenderId, BlockHash &prevblockhashout) const
bool isFlaky(const ProofId &proofid) const
ChainstateManager & chainman
Definition: peermanager.h:243
bool isInvalid(const ProofId &proofid) const
std::unordered_set< ProofId, SaltedProofIdHasher > manualFlakyProofids
Definition: peermanager.h:299
bool removePeer(const PeerId peerid)
Remove an existing peer.
const bool m_stakingPreConsensus
Definition: peermanager.h:245
bool isImmature(const ProofId &proofid) const
bool addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid)
Definition: peermanager.cpp:48
bool rejectProof(const ProofId &proofid, RejectionMode mode=RejectionMode::DEFAULT)
ProofPool immatureProofPool
Definition: peermanager.h:187
RegistrationMode
Registration mode.
Definition: peermanager.h:376
ProofPool conflictingProofPool
Definition: peermanager.h:186
static constexpr size_t MAX_REMOTE_PROOFS
Definition: peermanager.h:304
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.
Definition: peermanager.h:211
PeerId selectPeer() const
Randomly select a peer to poll.
bool isInConflictingPool(const ProofId &proofid) const
static constexpr int SELECT_NODE_MAX_RETRY
Definition: peermanager.h:228
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)
AddProofStatus addProofIfPreferred(const ProofRef &proof, ConflictingProofSet &conflictingProofs)
Attempt to add a proof to the pool.
Definition: proofpool.cpp:54
size_t size() const
Definition: proofpool.h:135
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:13
size_t countProofs() const
Definition: proofpool.cpp:129
bool removeProof(ProofId proofid)
Definition: proofpool.cpp:79
void forEachProof(Callable &&func) const
Definition: proofpool.h:118
ProofRef getProof(const ProofId &proofid) const
Definition: proofpool.cpp:112
std::set< ProofRef, ConflictingProofComparator > ConflictingProofSet
Definition: proofpool.h:88
ProofRef getLowestScoreProof() const
Definition: proofpool.cpp:123
std::unordered_set< ProofRef, SaltedProofHasher > rescan(PeerManager &peerManager)
Definition: proofpool.cpp:86
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 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.
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:80
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:134
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
bool RenameOver(fs::path src, fs::path dest)
Definition: fs_helpers.cpp:272
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:125
#define LogPrintLevel(category, level,...)
Definition: logging.h:247
#define LogPrint(category,...)
Definition: logging.h:238
#define LogPrintf(...)
Definition: logging.h:227
@ AVALANCHE
Definition: logging.h:62
ProofRegistrationResult
Definition: peermanager.h:145
static constexpr uint32_t AVALANCHE_MAX_IMMATURE_PROOFS
Maximum number of immature proofs the peer manager will accept from the network.
Definition: peermanager.h:46
static bool isImmatureState(const ProofValidationState &state)
static constexpr uint64_t PEERS_DUMP_VERSION
Definition: peermanager.cpp:31
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:186
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
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
int64_t NodeId
Definition: nodeid.h:10
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition: random.h:85
@ SER_DISK
Definition: serialize.h:153
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:100
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:181
RCUPtr< T > get(const KeyType &key)
Get the value corresponding to a key.
Definition: radix.h:118
bool forEachLeaf(Callable &&func) const
Definition: radix.h:144
bool insert(const RCUPtr< T > &value)
Insert a value into the tree.
Definition: radix.h:112
Facility for using an uint256 as a radix tree key.
SteadyMilliseconds nextRequestTime
Definition: node.h:23
bool avaproofsSent
Definition: node.h:24
std::chrono::seconds registration_time
Definition: peermanager.h:95
std::chrono::seconds nextPossibleConflictTime
Definition: peermanager.h:96
uint32_t node_count
Definition: peermanager.h:89
static constexpr auto DANGLING_TIMEOUT
Consider dropping the peer if no node is attached after this timeout expired.
Definition: peermanager.h:102
uint32_t index
Definition: peermanager.h:88
uint32_t getScore() const
Definition: peermanager.h:111
ProofRef proof
Definition: peermanager.h:91
uint64_t getStop() const
Definition: peermanager.h:75
uint64_t getStart() const
Definition: peermanager.h:74
PeerId getPeerId() const
Definition: peermanager.h:77
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:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
static int count
Definition: tests.c:31
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:58
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:109
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition: time.h:31
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())