34 size_t max_elements) {
35 auto &pview =
peers.get<by_proofid>();
36 auto it = pview.find(proofid);
37 if (it == pview.end()) {
50 size_t max_elements) {
53 const PeerId peerid = it->peerid;
55 auto nit =
nodes.find(nodeid);
56 if (nit ==
nodes.end()) {
57 if (!
nodes.emplace(nodeid, peerid, max_elements).second) {
61 const PeerId oldpeerid = nit->peerid;
62 if (!
nodes.modify(nit, [&](
Node &n) { n.peerid = peerid; })) {
79 const ProofId &proofid = it->getProofId();
101 const uint32_t score = p.
getScore();
103 slots.emplace_back(start, score, it->peerid);
120 auto it =
nodes.find(nodeid);
121 if (it ==
nodes.end()) {
125 const PeerId peerid = it->peerid;
140 if (it ==
peers.end()) {
144 assert(count <= it->node_count);
150 const uint32_t new_count = it->node_count -
count;
151 if (!
peers.modify(it, [&](
Peer &p) { p.node_count = new_count; })) {
168 const size_t i = it->index;
173 if (i + 1 ==
slots.size()) {
187 auto it =
nodes.find(nodeid);
188 if (it ==
nodes.end()) {
200 auto it =
nodes.find(nodeid);
201 if (it ==
nodes.end()) {
205 if (it->last_round >
response.getRound()) {
210 auto timeout = Now<SteadyMilliseconds>() +
211 std::chrono::milliseconds(
response.getCooldown());
220 auto it =
nodes.find(nodeid);
221 if (it ==
nodes.end()) {
225 return !it->avaproofsSent &&
234 PeerId peerid,
const std::chrono::seconds &nextTime) {
235 auto it =
peers.find(peerid);
236 if (it ==
peers.end()) {
247 return it->nextPossibleConflictTime == nextTime;
251 auto it =
peers.find(peerid);
252 if (it ==
peers.end()) {
262template <
typename ProofContainer>
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()) {
280 const ProofId &proofid = proof->getId();
283 const std::string &message) {
284 return registrationState.
Invalid(
295 "proof-already-registered");
327 "utxo-missing-or-spent");
344 auto now = GetTime<std::chrono::seconds>();
345 auto nextCooldownTimePoint =
347 "-avalancheconflictingproofcooldown",
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());
361 bestPossibleConflictTime = std::max(
362 bestPossibleConflictTime, it->nextPossibleConflictTime);
365 nextCooldownTimePoint);
368 if (bestPossibleConflictTime > now) {
372 "cooldown-not-elapsed");
392 "conflicting-utxos");
409 "proof-already-registered");
423 const ProofId &conflictingProofId = conflicting->getId();
426 "Evicted dangling proof %s due to conflict with peer proof "
435 auto inserted =
peers.emplace(peerid, proof, nextCooldownTimePoint);
450 auto range = pendingNodesView.equal_range(proofid);
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),
460 return std::make_pair(n.nodeid, n.max_elements);
463 for (
const auto &[nodeid, max_elements] : nodeids_and_max_elements) {
500 auto &pview =
peers.get<by_proofid>();
501 auto it = pview.find(proofid);
502 assert(it != pview.end());
514 if (!conflictingProof) {
530 std::unordered_set<ProofRef, SaltedProofHasher> ®isteredProofs) {
531 registeredProofs.clear();
532 const auto now = GetTime<std::chrono::seconds>();
534 std::vector<ProofRef> newlyDanglingProofs;
538 if (!
isLocalProof(peer.getProofId()) && peer.node_count == 0 &&
545 newlyDanglingProofs.push_back(peer.proof);
552 std::vector<ProofRef> previouslyDanglingProofs;
555 previouslyDanglingProofs.push_back(proof);
558 for (
const ProofRef &proof : previouslyDanglingProofs) {
561 registeredProofs.insert(proof);
565 for (
const ProofRef &proof : newlyDanglingProofs) {
582 "Proof dangling for too long (no connected node): %s\n",
583 proof->getId().GetHex());
606 if (it != nview.end() && it->peerid == p &&
607 it->nextRequestTime <= Now<SteadyMilliseconds>()) {
619 std::vector<ProofId> invalidProofIds;
620 std::vector<ProofRef> newImmatures;
625 for (
const auto &p :
peers) {
629 newImmatures.push_back(p.proof);
631 invalidProofIds.push_back(p.getProofId());
634 "Invalidating proof %s: verification failed (%s)\n",
635 p.proof->getId().GetHex(), state.
ToString());
646 invalidProofIds.push_back(proof->getId());
650 "Invalidating dangling proof %s: verification failed "
652 proof->getId().GetHex(), state.
ToString());
660 for (
const ProofId &invalidProofId : invalidProofIds) {
666 for (
auto &p : newImmatures) {
670 return registeredProofs;
693 auto &pview =
peers.
get<by_proofid>();
694 return pview.find(proofid) != pview.end();
722 const bool present) {
737 auto &remoteProofsByLastUpdate =
remoteProofs.get<by_lastUpdate>();
738 auto [begin, end] = remoteProofsByLastUpdate.equal_range(nodeid);
745 while (
size_t(std::distance(begin, end)) >=
748 begin = remoteProofsByLastUpdate.erase(begin);
751 auto it =
remoteProofs.find(boost::make_tuple(proofid, nodeid));
757 .emplace(
RemoteProof{proofid, nodeid, GetTime<std::chrono::seconds>(),
762std::vector<RemoteProof>
764 std::vector<RemoteProof> nodeRemoteProofs;
766 auto &remoteProofsByLastUpdate =
remoteProofs.get<by_lastUpdate>();
767 auto [begin, end] = remoteProofsByLastUpdate.equal_range(nodeid);
769 for (
auto &it = begin; it != end; it++) {
770 nodeRemoteProofs.emplace_back(*it);
773 return nodeRemoteProofs;
778 return view.count(proofid) > 0;
783 auto [begin, end] = view.equal_range(proofid);
784 return std::any_of(begin, end, [](
const auto &remoteProof) {
785 return remoteProof.present;
791 auto [begin, end] = remoteProofsView.equal_range(nodeid);
792 remoteProofsView.erase(begin, end);
796 auto it =
peers.find(peerid);
797 if (it ==
peers.end()) {
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);
818 boost::make_tuple(peerid, Now<SteadyMilliseconds>())));
859 std::vector<Slot> newslots;
860 newslots.reserve(
peers.size());
862 uint64_t prevStop = 0;
864 for (
auto it =
peers.begin(); it !=
peers.end(); it++) {
865 if (it->node_count == 0) {
869 newslots.emplace_back(prevStop, it->getScore(), it->peerid);
870 prevStop = newslots.back().getStop();
871 if (!
peers.modify(it, [&](
Peer &p) { p.index = i++; })) {
876 slots = std::move(newslots);
878 const uint64_t saved =
slotCount - prevStop;
886 uint64_t prevStop = 0;
887 uint32_t scoreFromSlots = 0;
888 for (
size_t i = 0; i <
slots.size(); i++) {
905 if (it ==
peers.end() || it->index != i) {
910 scoreFromSlots +=
slots[i].getScore();
918 uint32_t scoreFromAllPeers = 0;
919 uint32_t scoreFromPeersWithNodes = 0;
921 std::unordered_set<COutPoint, SaltedOutpointHasher> peersUtxos;
922 for (
const auto &p :
peers) {
924 scoreFromAllPeers += p.getScore();
932 for (
const auto &ss : p.proof->getStakes()) {
933 const COutPoint &outpoint = ss.getStake().getUTXO();
940 if (proof != p.proof) {
945 if (!peersUtxos.emplace(outpoint).second) {
952 const auto count_nodes = [&]() {
955 auto begin = nview.lower_bound(
957 auto end = nview.upper_bound(
960 for (
auto it = begin; it != end; ++it) {
967 if (p.node_count != count_nodes()) {
972 if (p.node_count == 0) {
976 scoreFromPeersWithNodes += p.getScore();
978 if (p.index >=
slots.size() ||
slots[p.index].getPeerId() != p.peerid) {
983 if (
slots[p.index].getScore() != p.getScore()) {
988 if ((
isLocalProof(p.getProofId()) || p.node_count > 0) &&
992 if (p.node_count == 0 &&
1019 const uint64_t max) {
1022 size_t begin = 0, end = slots.size();
1023 uint64_t bottom = 0, top = max;
1026 while ((end - begin) > 8) {
1028 if (slot < bottom || slot >= top) {
1033 size_t i = begin + ((slot - bottom) * (end - begin) / (top - bottom));
1034 assert(begin <= i && i < end);
1037 if (slots[i].contains(slot)) {
1038 return slots[i].getPeerId();
1042 if (slots[i].precedes(slot)) {
1048 bottom = slots[begin].getStart();
1053 if (slots[i].follows(slot)) {
1055 top = slots[end].getStart();
1064 for (
size_t i = begin; i < end; i++) {
1066 if (slots[i].contains(slot)) {
1067 return slots[i].getPeerId();
1088 std::vector<std::pair<ProofId, CScript>> &winners) {
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>(
1118 const int64_t targetRegistrationTime = refTime - registrationDelay.count();
1119 const int64_t maxRegistrationTime = refTime - minRegistrationDelay.count();
1120 const int64_t minRegistrationTime = refTime - maxRegistrationDelay.count();
1122 std::vector<ProofRef> selectedProofs;
1124 while (selectedProofs.size() <
peers.size()) {
1125 double bestRewardRank = std::numeric_limits<double>::max();
1127 int64_t selectedProofRegistrationTime{0};
1136 if (!peer.hasFinalized ||
1137 peer.registration_time.count() >= maxRegistrationTime) {
1141 if (std::find_if(selectedProofs.begin(), selectedProofs.end(),
1143 return peer.getProofId() == proof->getId();
1144 }) != selectedProofs.end()) {
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());
1160 double proofRewardRank =
1166 proofRewardHash, proofRewardRank, peer.getProofId(),
1167 bestRewardHash, bestRewardRank,
1168 selectedProof ? selectedProof->getId()
1170 bestRewardRank = proofRewardRank;
1171 selectedProof = peer.proof;
1172 selectedProofRegistrationTime = peer.registration_time.count();
1173 bestRewardHash = proofRewardHash;
1177 if (!selectedProof) {
1182 if (!firstCompliantProof &&
1183 selectedProofRegistrationTime < targetRegistrationTime) {
1184 firstCompliantProof = selectedProof;
1187 selectedProofs.push_back(selectedProof);
1189 if (selectedProofRegistrationTime < minRegistrationTime &&
1190 !
isFlaky(selectedProof->getId()) &&
1198 if (!firstCompliantProof) {
1202 winners.reserve(selectedProofs.size());
1205 for (
const ProofRef &proof : selectedProofs) {
1206 if (proof->getId() == firstCompliantProof->getId()) {
1207 winners.push_back({proof->getId(), proof->getPayoutScript()});
1211 for (
const ProofRef &proof : selectedProofs) {
1212 if (proof->getId() != firstCompliantProof->getId()) {
1213 winners.push_back({proof->getId(), proof->getPayoutScript()});
1257 auto &remoteProofsByNodeId =
remoteProofs.get<by_nodeid>();
1260 std::unordered_map<PeerId, std::unordered_set<ProofId, SaltedProofIdHasher>>
1264 double total_score{0};
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);
1282 double missing_score{0};
1285 for (
const auto &[peerid, missingProofs] : missing_per_peer) {
1286 if (missingProofs.size() > 3) {
1291 auto pit =
peers.find(peerid);
1292 if (pit ==
peers.end()) {
1297 if (missingProofs.count(proofid) > 0) {
1298 missing_score += pit->getScore();
1302 return (missing_score / total_score) > 0.3;
1312 auto [begin, end] = remoteProofsView.equal_range(proofid);
1316 return std::nullopt;
1319 double total_score{0};
1320 double present_score{0};
1321 double missing_score{0};
1323 for (
auto it = begin; it != end; it++) {
1324 auto nit =
nodes.find(it->nodeid);
1325 if (nit ==
nodes.end()) {
1330 const PeerId peerid = nit->peerid;
1332 auto pit =
peers.find(peerid);
1333 if (pit ==
peers.end()) {
1338 uint32_t node_count = pit->node_count;
1344 if (node_count == 0) {
1349 const double score = double(pit->getScore()) / node_count;
1351 total_score += score;
1353 present_score += score;
1355 missing_score += score;
1360 auto &peersByProofid =
peers.get<by_proofid>();
1363 bool present =
false;
1364 auto pit = peersByProofid.find(proofid);
1365 if (pit != peersByProofid.end()) {
1366 present = pit->node_count > 0;
1369 pit = peersByProofid.find(
localProof->getId());
1370 if (pit != peersByProofid.end()) {
1373 const double score =
1374 double(pit->getScore()) / (1 + pit->node_count);
1376 total_score += score;
1378 present_score += score;
1380 missing_score += score;
1385 if (present_score / total_score > 0.55) {
1386 return std::make_optional(
true);
1389 if (missing_score / total_score > 0.55) {
1390 return std::make_optional(
false);
1393 return std::nullopt;
1398 const fs::path dumpPathTmp = dumpPath +
".new";
1406 file << uint64_t(
peers.size());
1409 file << peer.hasFinalized;
1410 file << int64_t(peer.registration_time.count());
1411 file << int64_t(peer.nextPossibleConflictTime.count());
1415 throw std::runtime_error(
strprintf(
"Failed to commit to file %s",
1416 PathToString(dumpPathTmp)));
1421 throw std::runtime_error(
strprintf(
"Rename failed from %s to %s",
1422 PathToString(dumpPathTmp),
1423 PathToString(dumpPath)));
1425 }
catch (
const std::exception &e) {
1432 peers.size(), PathToString(dumpPath));
1439 std::unordered_set<ProofRef, SaltedProofHasher> ®isteredProofs) {
1440 registeredProofs.clear();
1444 if (file.IsNull()) {
1446 "Failed to open avalanche peers file from disk.\n");
1456 "Unsupported avalanche peers file version.\n");
1463 auto &peersByProofId =
peers.get<by_proofid>();
1465 for (uint64_t i = 0; i < numPeers; i++) {
1468 int64_t registrationTime;
1469 int64_t nextPossibleConflictTime;
1472 file >> hasFinalized;
1473 file >> registrationTime;
1474 file >> nextPossibleConflictTime;
1477 auto it = peersByProofId.find(proof->getId());
1478 if (it == peersByProofId.end()) {
1487 peersByProofId.modify(it, [&](
Peer &p) {
1490 std::chrono::seconds{registrationTime};
1492 std::chrono::seconds{nextPossibleConflictTime};
1495 registeredProofs.insert(proof);
1498 }
catch (
const std::exception &e) {
1500 "Failed to read the avalanche peers file data on disk: %s.\n",
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",
1533 prevblockhashout = contender->prevblockhash;
1534 if (contender->voteStatus != 0) {
1535 return contender->voteStatus;
1538 const ProofId &proofid = contender->proofid;
1554 auto &pview =
peers.get<by_proofid>();
1555 auto it = pview.find(proofid);
1556 if (it == pview.end() || !it->hasFinalized) {
1560 const int64_t refTime = std::min(contender->prevblocktime,
GetTime());
1561 const int64_t targetRegistrationTime =
1562 refTime - std::chrono::duration_cast<std::chrono::seconds>(
1565 if (it->registration_time.count() >= targetRegistrationTime) {
1580 std::vector<std::pair<ProofId, CScript>> &newWinners) {
1595std::optional<StakeContenderCacheInfo>
1606 std::vector<std::pair<ProofId, CScript>> &winners)
const {
1624 const std::vector<std::pair<ProofId, CScript>> winners,
size_t maxPollable,
1625 std::vector<StakeContenderId> &pollableContenders) {
1628 for (
const auto &winner : winners) {
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),
1644 pollableContenders) > 0) {
1649 "Stake contender set as best contender: id %s at block "
1651 pollableContenders[0].ToString(), prevblockhash.
ToString(),
1660 const CBlockIndex *pindex,
const std::vector<CScript> &payoutScripts) {
static constexpr PeerId NO_PEER
static constexpr size_t AVALANCHE_DEFAULT_CONFLICTING_PROOF_COOLDOWN
Conflicting proofs cooldown time default value in seconds.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Non-refcounted RAII wrapper for FILE*.
The block chain is a tree shaped structure starting with the genesis block at the root,...
int64_t GetBlockTime() const
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
void insert(Span< const uint8_t > vKey)
bool contains(Span< const uint8_t > vKey) const
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
T * get()
Get allows to access the undelying pointer.
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
std::string ToString() const
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
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 > ®isteredProofs)
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.
ProofPool danglingProofPool
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
void clearRejectedContenders()
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)
ProofPool immatureProofPool
Amount stakeUtxoDustThreshold
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 > ®isteredProofs)
void acceptStakeContender(const StakeContenderId &contenderId)
ProofRef getProof(const ProofId &proofid) const
bool registerProof(const ProofRef &proof, ProofRegistrationState ®istrationState, 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.
@ REJECTED
Rejected due to conflicts.
@ SUCCEED
Added successfully.
AddProofStatus addProofIfPreferred(const ProofRef &proof, ConflictingProofSet &conflictingProofs)
Attempt to add a proof to the pool.
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.
size_t countProofs() const
bool removeProof(ProofId proofid)
void forEachProof(Callable &&func) const
ProofRef getProof(const ProofId &proofid) const
std::set< ProofRef, ConflictingProofComparator > ConflictingProofSet
ProofRef getLowestScoreProof() const
std::unordered_set< ProofRef, SaltedProofHasher > rescan(PeerManager &peerManager)
ConflictingProofSet getConflicts(const ProofRef &proof) const
Return proofs in this pool that share any UTXO with proof.
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
std::string GetHex() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
static const uint256 ZERO
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
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.
#define LogTrace(category,...)
#define LogDebug(category,...)
static constexpr uint32_t AVALANCHE_MAX_IMMATURE_PROOFS
Maximum number of immature proofs the peer manager will accept from the network.
@ INVALID_PROOF_SIGNATURE
@ INVALID_STAKE_SIGNATURE
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
FILE * fopen(const fs::path &p, const char *mode)
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
A BlockHash is a unqiue identifier for a block.
RCUPtr< T > remove(const KeyType &key)
Remove an element from the tree.
RCUPtr< T > get(const KeyType &key)
Get the value corresponding to a key.
bool forEachLeaf(Callable &&func) const
bool insert(const RCUPtr< T > &value)
Insert a value into the tree.
Facility for using an uint256 as a radix tree key.
SteadyMilliseconds nextRequestTime
std::chrono::seconds registration_time
std::chrono::seconds nextPossibleConflictTime
static constexpr auto DANGLING_TIMEOUT
Consider dropping the peer if no node is attached after this timeout expired.
uint32_t getScore() const
uint64_t getStart() const
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 WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
#define NO_THREAD_SAFETY_ANALYSIS
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds