// Copyright (c) 2018-2025 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_EVO_DETERMINISTICMNS_H #define BITCOIN_EVO_DETERMINISTICMNS_H #include #include #include #include #include #include #include #include #include // IWYU pragma: export #include #include #include #include #include #include #include #include #include #include #include #include #include class CBlock; class CBlockIndex; class CCoinsViewCache; class ChainstateManager; namespace kernel { class Notifications; } // namespace kernel namespace node { class BlockManager; } // namespace node class CEvoDB; class CSimplifiedMNList; class CSimplifiedMNListEntry; class CMasternodeMetaMan; class CSpecialTxProcessor; struct RPCResult; class CDeterministicMN { private: uint64_t internalId{std::numeric_limits::max()}; public: uint256 proTxHash; COutPoint collateralOutpoint; uint16_t nOperatorReward{0}; MnType nType{MnType::Regular}; std::shared_ptr pdmnState; CDeterministicMN() = delete; // no default constructor, must specify internalId explicit CDeterministicMN(uint64_t _internalId, MnType mnType = MnType::Regular) : internalId(_internalId), nType(mnType) { // only non-initial values assert(_internalId != std::numeric_limits::max()); } template CDeterministicMN(deserialize_type, Stream& s) { s >> *this; } SERIALIZE_METHODS(CDeterministicMN, obj) { READWRITE(obj.proTxHash); READWRITE(VARINT(obj.internalId)); READWRITE(obj.collateralOutpoint); READWRITE(obj.nOperatorReward); READWRITE(obj.pdmnState); READWRITE(obj.nType); } [[nodiscard]] bool HasInternalId() const { return internalId != std::numeric_limits::max(); } [[nodiscard]] uint64_t GetInternalId() const; [[nodiscard]] CSimplifiedMNListEntry to_sml_entry() const; [[nodiscard]] std::string ToString() const; [[nodiscard]] static RPCResult GetJsonHelp(const std::string& key, bool optional); [[nodiscard]] UniValue ToJson() const; }; class CDeterministicMNListDiff; template void SerializeImmerMap(Stream& os, const immer::map& m) { WriteCompactSize(os, m.size()); for (typename immer::map::const_iterator mi = m.begin(); mi != m.end(); ++mi) Serialize(os, (*mi)); } template void UnserializeImmerMap(Stream& is, immer::map& m) { m = immer::map(); unsigned int nSize = ReadCompactSize(is); for (unsigned int i = 0; i < nSize; i++) { std::pair item; Unserialize(is, item); m = m.set(item.first, item.second); } } // For some reason the compiler is not able to choose the correct Serialize/Deserialize methods without a specialized // version of SerReadWrite. It otherwise always chooses the version that calls a.Serialize() template inline void SerReadWrite(Stream& s, const immer::map& m, ActionSerialize ser_action) { ::SerializeImmerMap(s, m); } template inline void SerReadWrite(Stream& s, immer::map& obj, ActionUnserialize ser_action) { ::UnserializeImmerMap(s, obj); } //! An operator key together with the encoding it is registered under. Uniqueness is per //! encoding: the same key under legacy and under basic occupies two slots. using OperatorKeySlot = BLSEncoded; class CDeterministicMNList { private: struct ImmerHasher { size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); } }; public: using MnMap = immer::map; using MnInternalIdMap = immer::map; using MnUniquePropertyMap = immer::map, ImmerHasher>; using MnHashSet = immer::set; struct Counts { size_t m_total_evo{0}; size_t m_total_mn{0}; size_t m_total_weighted{0}; size_t m_valid_evo{0}; size_t m_valid_mn{0}; size_t m_valid_weighted{0}; [[nodiscard]] size_t total() const { return m_total_mn + m_total_evo; } [[nodiscard]] size_t enabled() const { return m_valid_mn + m_valid_evo; } }; private: uint256 blockHash; int nHeight{-1}; uint32_t nTotalRegisteredCount{0}; MnMap mnMap; MnInternalIdMap mnInternalIdMap; // map of unique properties like address and keys // we keep track of this as checking for duplicates would otherwise be painfully slow MnUniquePropertyMap mnUniquePropertyMap; // Derived from mnMap by AddMN, UpdateMN and RemoveMN: masternodes whose registration is not // confirmed yet, non-banned masternodes carrying a PoSe penalty, and masternodes with // consecutive payments. The per-block confirmation, penalty decay and payment counter // reset walk only these instead of the whole list. MnHashSet m_unconfirmed; MnHashSet m_penalized; MnHashSet m_consecutively_paid; // This SML could be null // This cache is used to improve performance and meant to be reused // for multiple CDeterministicMNList until mnMap is actually changed. // Calls of AddMN, RemoveMN and (in some cases) UpdateMN reset this cache; // it happens also for indirect calls such as ApplyDiff // Thread safety: Protected by its own mutex for thread-safe access mutable Mutex m_cached_sml_mutex; mutable std::shared_ptr m_cached_sml GUARDED_BY(m_cached_sml_mutex); // Private helper method to invalidate SML cache void InvalidateSMLCache() EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex) { LOCK(m_cached_sml_mutex); m_cached_sml = nullptr; } public: CDeterministicMNList() = default; explicit CDeterministicMNList(const uint256& _blockHash, int _height, uint32_t _totalRegisteredCount) : blockHash(_blockHash), nHeight(_height), nTotalRegisteredCount(_totalRegisteredCount) { assert(nHeight >= 0); } // Copy constructor CDeterministicMNList(const CDeterministicMNList& other) : blockHash(other.blockHash), nHeight(other.nHeight), nTotalRegisteredCount(other.nTotalRegisteredCount), mnMap(other.mnMap), mnInternalIdMap(other.mnInternalIdMap), mnUniquePropertyMap(other.mnUniquePropertyMap), m_unconfirmed(other.m_unconfirmed), m_penalized(other.m_penalized), m_consecutively_paid(other.m_consecutively_paid) { LOCK(other.m_cached_sml_mutex); m_cached_sml = other.m_cached_sml; } // Assignment operator CDeterministicMNList& operator=(const CDeterministicMNList& other) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex, !other.m_cached_sml_mutex) { if (this != &other) { blockHash = other.blockHash; nHeight = other.nHeight; nTotalRegisteredCount = other.nTotalRegisteredCount; mnMap = other.mnMap; mnInternalIdMap = other.mnInternalIdMap; mnUniquePropertyMap = other.mnUniquePropertyMap; m_unconfirmed = other.m_unconfirmed; m_penalized = other.m_penalized; m_consecutively_paid = other.m_consecutively_paid; LOCK2(m_cached_sml_mutex, other.m_cached_sml_mutex); m_cached_sml = other.m_cached_sml; } return *this; } template inline void SerializationOpBase(Stream& s, Operation ser_action) { READWRITE(blockHash); READWRITE(nHeight); READWRITE(nTotalRegisteredCount); } template void Serialize(Stream& s) const { const_cast(this)->SerializationOpBase(s, ActionSerialize()); // Serialize the map as a vector WriteCompactSize(s, mnMap.size()); for (const auto& [_, dmn] : mnMap) { s << *dmn; } } template void Unserialize(Stream& s) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex) { Clear(); SerializationOpBase(s, ActionUnserialize()); for (size_t to_read = ReadCompactSize(s); to_read > 0; --to_read) { AddMN(std::make_shared(deserialize, s), /*fBumpTotalCount=*/false); } } void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex) { blockHash = uint256{}; nHeight = -1; nTotalRegisteredCount = 0; mnMap = MnMap(); mnUniquePropertyMap = MnUniquePropertyMap(); mnInternalIdMap = MnInternalIdMap(); m_unconfirmed = MnHashSet(); m_penalized = MnHashSet(); m_consecutively_paid = MnHashSet(); InvalidateSMLCache(); } [[nodiscard]] size_t GetAllMNsCount() const { return mnMap.size(); } [[nodiscard]] Counts GetCounts() const { Counts ret; for (const auto& [_, dmn] : mnMap) { const bool is_evo = dmn->nType == MnType::Evo; const bool is_valid = !dmn->pdmnState->IsBanned(); const auto weight = GetMnType(dmn->nType).voting_weight; if (is_evo) { ret.m_total_evo++; if (is_valid) { ret.m_valid_evo++; } } else { ret.m_total_mn++; if (is_valid) { ret.m_valid_mn++; } } if (is_valid) { ret.m_valid_weighted += weight; } ret.m_total_weighted += weight; } return ret; } /** * Execute a callback on all masternodes in the mnList. This will pass a reference * of each masternode to the callback function. This should be preferred over ForEachMNShared. * @param onlyValid Run on all masternodes, or only "valid" (not banned) masternodes * @param cb callback to execute */ template void ForEachMN(bool onlyValid, Callback&& cb) const { for (const auto& p : mnMap) { if (!onlyValid || !p.second->pdmnState->IsBanned()) { cb(*p.second); } } } /** * Prefer ForEachMN. Execute a callback on all masternodes in the mnList. * This will pass a non-null shared_ptr of each masternode to the callback function. * Use this function only when a shared_ptr is needed in order to take shared ownership. * @param onlyValid Run on all masternodes, or only "valid" (not banned) masternodes * @param cb callback to execute */ template void ForEachMNShared(bool onlyValid, Callback&& cb) const { for (const auto& p : mnMap) { if (!onlyValid || !p.second->pdmnState->IsBanned()) { cb(p.second); } } } /** * Masternodes with a positive nConsecutivePayments. */ [[nodiscard]] std::vector GetConsecutivelyPaidMNs() const; /** * Execute a callback on every masternode whose registration is not confirmed yet. */ template void ForEachUnconfirmedMN(Callback&& cb) const { for (const auto& proTxHash : m_unconfirmed) { const auto* dmn = mnMap.find(proTxHash); assert(dmn != nullptr); cb(**dmn); } } [[nodiscard]] const uint256& GetBlockHash() const { return blockHash; } void SetBlockHash(const uint256& _blockHash) { blockHash = _blockHash; } [[nodiscard]] int GetHeight() const { assert(nHeight >= 0); return nHeight; } /** Snapshot hashing also covers the pre-DIP3 default list (height -1). */ [[nodiscard]] int GetHeightForSnapshotCodec() const noexcept { return nHeight; } void SetHeight(int _height) { assert(_height >= 0); nHeight = _height; } [[nodiscard]] uint32_t GetTotalRegisteredCount() const { return nTotalRegisteredCount; } [[nodiscard]] bool IsMNValid(const uint256& proTxHash) const; [[nodiscard]] bool IsMNPoSeBanned(const uint256& proTxHash) const; [[nodiscard]] bool HasMN(const uint256& proTxHash) const { return GetMN(proTxHash) != nullptr; } [[nodiscard]] bool HasMNByCollateral(const COutPoint& collateralOutpoint) const { return GetMNByCollateral(collateralOutpoint) != nullptr; } [[nodiscard]] bool HasValidMNByCollateral(const COutPoint& collateralOutpoint) const { return GetValidMNByCollateral(collateralOutpoint) != nullptr; } [[nodiscard]] CDeterministicMNCPtr GetMN(const uint256& proTxHash) const; [[nodiscard]] CDeterministicMNCPtr GetValidMN(const uint256& proTxHash) const; [[nodiscard]] CDeterministicMNCPtr GetMNByOperatorKey(const CBLSPublicKey& pubKey) const; [[nodiscard]] CDeterministicMNCPtr GetMNByCollateral(const COutPoint& collateralOutpoint) const; [[nodiscard]] CDeterministicMNCPtr GetValidMNByCollateral(const COutPoint& collateralOutpoint) const; [[nodiscard]] CDeterministicMNCPtr GetMNByService(const CService& service) const; [[nodiscard]] CDeterministicMNCPtr GetMNByInternalId(uint64_t internalId) const; [[nodiscard]] CDeterministicMNCPtr GetMNPayee(gsl::not_null pindexPrev) const; /** * Calculates the projected MN payees for the next *count* blocks. The result is not guaranteed to be correct * as PoSe banning might occur later * @param nCount the number of payees to return. "nCount = max()"" means "all", use it to avoid calling GetCounts twice. */ [[nodiscard]] std::vector GetProjectedMNPayees(gsl::not_null pindexPrev, int nCount = std::numeric_limits::max()) const; /** * Calculates CSimplifiedMNList for current list and cache it * Thread safety: Uses internal mutex for thread-safe cache access */ gsl::not_null> to_sml() const EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); /** * Calculates the maximum penalty which is allowed at the height of this MN list. It is dynamic and might change * for every block. */ [[nodiscard]] int CalcMaxPoSePenalty() const; /** * Returns a the given percentage from the max penalty for this MN list. Always use this method to calculate the * value later passed to PoSePunish. The percentage should be high enough to take per-block penalty decreasing for MNs * into account. This means, if you want to accept 2 failures per payment cycle, you should choose a percentage that * is higher then 50%, e.g. 66%. */ [[nodiscard]] int CalcPenalty(int percent) const; /** * Punishes a MN for misbehavior. If the resulting penalty score of the MN reaches the max penalty, it is banned. * Penalty scores are only increased when the MN is not already banned, which means that after banning the penalty * might appear lower then the current max penalty, while the MN is still banned. */ void PoSePunish(const uint256& proTxHash, int penalty, bool debugLogs) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); void DecreaseScores() EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); /** * Decrease penalty score of MN by 1. * Only allowed on non-banned MNs. */ void PoSeDecrease(const CDeterministicMN& dmn) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); [[nodiscard]] CDeterministicMNListDiff BuildDiff(const CDeterministicMNList& to) const; /** * Apply Diff modifies current object. * It is more efficient than creating a copy due to heavy copy constructor. * Calculating for old block may require up to {DISK_SNAPSHOT_PERIOD} object copy & destroy. */ void ApplyDiff(gsl::not_null pindex, const CDeterministicMNListDiff& diff) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); /** Reconstruct an older MN list referenced by quorum/rotation data, starting from the snapshot's full base list * or a previously reconstructed historical list, without dereferencing block data. */ void ApplyDiffForSnapshot(const uint256& block_hash, int height, uint32_t total_registered_count, const CDeterministicMNListDiff& diff) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); void AddMN(const CDeterministicMNCPtr& dmn, bool fBumpTotalCount = true) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); void UpdateMN(const CDeterministicMN& oldDmn, const std::shared_ptr& pdmnState) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); void UpdateMN(const uint256& proTxHash, const std::shared_ptr& pdmnState) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); void UpdateMN(const CDeterministicMN& oldDmn, const CDeterministicMNStateDiff& stateDiff) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); void RemoveMN(const uint256& proTxHash) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); template [[nodiscard]] bool HasUniqueProperty(const T& v) const { return mnUniquePropertyMap.count(GetUniquePropertyHash(v)) != 0; } template [[nodiscard]] CDeterministicMNCPtr GetUniquePropertyMN(const T& v) const { auto p = mnUniquePropertyMap.find(GetUniquePropertyHash(v)); if (!p) { return nullptr; } return GetMN(p->first); } /** * Is this operator public key already held by a masternode other than `self`, under *either* BLS * encoding? * * mnUniquePropertyMap is keyed by the hash of an operator key's bytes under one scheme. The * same point occupies a different slot under the other scheme, so a single lookup sees only * one of them. There are exactly two schemes, so probing both is O(1) rather than a scan. * * Both slots are probed even when one resolves to `self`: where a cross-scheme duplicate pair * already exists, returning early on a self-match would miss the other member. * * Pass uint256() as `self` to exclude nothing. An invalid pubkey is never considered held: * it is rejected up front rather than relying on the map never containing a null entry. */ [[nodiscard]] bool HasOperatorKeyUnderAnyScheme(const CBLSPublicKey& pubkey, const uint256& self) const { if (!pubkey.IsValid()) return false; CBLSLazyPublicKey wrapped; wrapped.Set(pubkey); for (const BLSScheme scheme : {BLSScheme::Legacy, BLSScheme::Basic}) { // NOLINT(bls-legacy-scheme) const OperatorKeySlot slot{wrapped, scheme}; if (!HasUniqueProperty(slot)) continue; const auto holder = GetUniquePropertyMN(slot); if (holder && holder->proTxHash != self) return true; } return false; } // Compare two masternode lists for equality, ignoring non-deterministic members. // Non-deterministic members (nTotalRegisteredCount, internalId) can differ between // nodes due to different sync histories, but don't affect consensus validity. bool IsEqual(const CDeterministicMNList& rhs) const { // Compare deterministic metadata if (blockHash != rhs.blockHash || nHeight != rhs.nHeight || mnUniquePropertyMap != rhs.mnUniquePropertyMap) { return false; } // Compare map sizes (actual entries compared below) // Note: Not comparing nTotalRegisteredCount (non-deterministic) if (mnMap.size() != rhs.mnMap.size() || mnInternalIdMap.size() != rhs.mnInternalIdMap.size()) { return false; } // Compare each masternode entry for (const auto& [proTxHash, dmn] : mnMap) { auto dmn_rhs = rhs.mnMap.find(proTxHash); if (dmn_rhs == nullptr) { return false; } // Compare deterministic masternode fields // Note: Not comparing internalId (non-deterministic) if (dmn->proTxHash != dmn_rhs->get()->proTxHash || dmn->collateralOutpoint != dmn_rhs->get()->collateralOutpoint || dmn->nOperatorReward != dmn_rhs->get()->nOperatorReward || dmn->nType != dmn_rhs->get()->nType || // Use SerializeHash for pdmnState to avoid enumerating all state fields SerializeHash(*dmn->pdmnState) != SerializeHash(*dmn_rhs->get()->pdmnState)) { return false; } } return true; } private: template [[nodiscard]] static uint256 GetUniquePropertyHash(const T& v) { #define DMNL_NO_TEMPLATE(name) \ static_assert(!std::is_same_v, name>, "GetUniquePropertyHash cannot be templated against " #name) DMNL_NO_TEMPLATE(CBLSPublicKey); DMNL_NO_TEMPLATE(CBLSLazyPublicKey); DMNL_NO_TEMPLATE(ExtNetInfo); DMNL_NO_TEMPLATE(MnNetInfo); DMNL_NO_TEMPLATE(NetInfoEntry); DMNL_NO_TEMPLATE(NetInfoInterface); DMNL_NO_TEMPLATE(std::shared_ptr); #undef DMNL_NO_TEMPLATE if constexpr (std::is_same_v, CService>) { // Special handling is required if we're using addresses that can only be (de)serialized using // ADDRv2. Without this step, the address gets truncated, the hashmap gets contaminated with // an invalid entry and subsequent attempts at registering ADDRv2 entries get blocked. We cannot // apply this treatment ADDRv1 compatible addresses for backwards compatibility with the existing map. const auto& ser_params{v.IsAddrV1Compatible() ? CNetAddr::V1 : CNetAddr::V2}; return ::SerializeHash(ser_params(v)); } else { return ::SerializeHash(v); } } [[nodiscard]] static uint256 GetUniquePropertyHash(const OperatorKeySlot& slot) { // Hash of the 48 key bytes under slot.scheme: GetHash writes those bytes to // a HashWriter, matching SerializeHash of the key // serialized under that scheme. return slot.GetHash(); } template [[nodiscard]] static bool IsNullUniqueProperty(const T& value) { return value == T{}; } [[nodiscard]] static bool IsNullUniqueProperty(const OperatorKeySlot& slot) { return slot.obj == CBLSLazyPublicKey(); } template [[nodiscard]] static bool SameUniqueProperty(const T& a, const T& b) { return a == b; } [[nodiscard]] static bool SameUniqueProperty(const OperatorKeySlot& a, const OperatorKeySlot& b) { return GetUniquePropertyHash(a) == GetUniquePropertyHash(b); } template [[nodiscard]] bool AddUniqueProperty(const CDeterministicMN& dmn, const T& v) { if (IsNullUniqueProperty(v)) { return false; } auto hash = GetUniquePropertyHash(v); auto oldEntry = mnUniquePropertyMap.find(hash); if (oldEntry != nullptr && oldEntry->first != dmn.proTxHash) { return false; } std::pair newEntry(dmn.proTxHash, 1); if (oldEntry != nullptr) { newEntry.second = oldEntry->second + 1; } mnUniquePropertyMap = mnUniquePropertyMap.set(hash, newEntry); return true; } template [[nodiscard]] bool DeleteUniqueProperty(const CDeterministicMN& dmn, const T& oldValue) { if (IsNullUniqueProperty(oldValue)) { return false; } auto oldHash = GetUniquePropertyHash(oldValue); auto p = mnUniquePropertyMap.find(oldHash); if (p == nullptr || p->first != dmn.proTxHash) { return false; } if (p->second == 1) { mnUniquePropertyMap = mnUniquePropertyMap.erase(oldHash); } else { mnUniquePropertyMap = mnUniquePropertyMap.set(oldHash, std::make_pair(dmn.proTxHash, p->second - 1)); } return true; } template [[nodiscard]] bool UpdateUniqueProperty(const CDeterministicMN& dmn, const T& oldValue, const T& newValue) { if (SameUniqueProperty(oldValue, newValue)) { return true; } if (!IsNullUniqueProperty(oldValue) && !DeleteUniqueProperty(dmn, oldValue)) { return false; } if (!IsNullUniqueProperty(newValue) && !AddUniqueProperty(dmn, newValue)) { return false; } return true; } friend bool operator==(const CDeterministicMNList& a, const CDeterministicMNList& b) { return a.blockHash == b.blockHash && a.nHeight == b.nHeight && a.nTotalRegisteredCount == b.nTotalRegisteredCount && a.mnMap == b.mnMap && a.mnInternalIdMap == b.mnInternalIdMap && a.mnUniquePropertyMap == b.mnUniquePropertyMap; } }; class CDeterministicMNListDiff { public: int nHeight{-1}; //memory only std::vector addedMNs; // keys are all relating to the internalId of MNs. Keys can come from // untrusted input (evo snapshots), so the hash is salted against flooding. std::unordered_map updatedMNs; std::set removedMns; template void Serialize(Stream& s) const { s << addedMNs; WriteCompactSize(s, updatedMNs.size()); std::vector updatedMNsInternalIds; updatedMNsInternalIds.reserve(updatedMNs.size()); for (const auto& entry : updatedMNs) { updatedMNsInternalIds.emplace_back(entry.first); } std::sort(updatedMNsInternalIds.begin(), updatedMNsInternalIds.end()); for (const auto& internalId : updatedMNsInternalIds) { WriteVarInt(s, internalId); s << updatedMNs.at(internalId); } WriteCompactSize(s, removedMns.size()); for (const auto& internalId : removedMns) { WriteVarInt(s, internalId); } } template void Unserialize(Stream& s) { UnserializeImpl(s, false); // Default: new format } // Legacy-aware unserialize method template void UnserializeLegacyFormat(Stream& s) { UnserializeImpl(s, true); // Legacy format } private: template void UnserializeImpl(Stream& s, bool isLegacyFormat) { // Reset all collections before reading addedMNs.clear(); updatedMNs.clear(); removedMns.clear(); for (size_t to_read = ReadCompactSize(s); to_read > 0; --to_read) { addedMNs.push_back(std::make_shared(deserialize, s)); } for (size_t to_read = ReadCompactSize(s); to_read > 0; --to_read) { uint64_t internalId = ReadVarInt(s); // CDeterministicMNState can have newer fields but doesn't need migration logic here as // CDeterministicMNStateDiff is always serialised using a bitmask and new fields have a new bit guide value, // so we are good to continue. We do need migration logic to change field order though. if (isLegacyFormat) { // Use legacy deserializer for old format CDeterministicMNStateDiffLegacy legacyDiff(deserialize, s); // Convert to new format and store updatedMNs.emplace(internalId, legacyDiff.ToNewFormat()); } else { // Use current deserializer for new format updatedMNs.emplace(internalId, CDeterministicMNStateDiff(deserialize, s)); } } for (size_t to_read = ReadCompactSize(s); to_read > 0; --to_read) { uint64_t internalId = ReadVarInt(s); removedMns.emplace(internalId); } } public: bool HasChanges() const { return !addedMNs.empty() || !updatedMNs.empty() || !removedMns.empty(); } }; constexpr int llmq_max_blocks() { int max_blocks{0}; for (const auto& llmq : Consensus::available_llmqs) { int blocks = (llmq.useRotation ? 1 : llmq.signingActiveQuorumCount) * llmq.dkgInterval; max_blocks = std::max(max_blocks, blocks); } return max_blocks; } /** Outcome of applying a block to the deterministic masternode list: the list * before and after the block and the diff between them. A block that leaves * the list untouched yields an empty diff (see diff.HasChanges()); for an * undone block the lists are only filled when the diff has changes. */ struct MNListUpdates { CDeterministicMNList old_list; CDeterministicMNList new_list; CDeterministicMNListDiff diff; //! The masternode the block pays, as selected from old_list CDeterministicMNCPtr payee; }; /** Sentinel suffix carried by serving-failure messages that report locally * missing block data (pruned, or below an unvalidated snapshot base) rather * than peer misbehavior. Every producer must append this verbatim so that * IsBlockDataUnavailableError() keeps recognizing the condition; matching on * this constant is what keeps such requests from penalizing the peer. */ inline constexpr std::string_view BLOCK_DATA_UNAVAILABLE_SUFFIX{ "is not available (pruned or below an unvalidated snapshot base)"}; class CDeterministicMNManager { static constexpr int DISK_SNAPSHOT_PERIOD = 576; // once per day // keep cache for enough disk snapshots to have all active quourms covered static constexpr int DISK_SNAPSHOTS = llmq_max_blocks() / DISK_SNAPSHOT_PERIOD + 1; static constexpr int LIST_DIFFS_CACHE_SIZE = DISK_SNAPSHOT_PERIOD * DISK_SNAPSHOTS; //! Lists the cache may hold before a lookup runs CleanupCache(). Cleanup retains only the //! tip and the bases of live quorums, a few dozen lists; the rest is scratch that historical //! requests (a full list read from disk plus its mini-snapshots) and connected blocks added. //! The budget caps what peers can make the node hold through historical requests, while //! sequential historical work keeps its intermediate lists until it outgrows the budget. static constexpr size_t MAX_CACHED_LISTS{64}; private: Mutex cs; CEvoDB& m_evoDb; CMasternodeMetaMan& m_mn_metaman; const evo::StateOrigin& m_origin; Uint256HashMap mnListsCache GUARDED_BY(cs); Uint256HashMap mnListDiffsCache GUARDED_BY(cs); const CBlockIndex* tipIndex GUARDED_BY(cs) {nullptr}; const CBlockIndex* m_initial_snapshot_index GUARDED_BY(cs) {nullptr}; public: CDeterministicMNManager() = delete; CDeterministicMNManager(const CDeterministicMNManager&) = delete; CDeterministicMNManager& operator=(const CDeterministicMNManager&) = delete; explicit CDeterministicMNManager(CEvoDB& evoDb, CMasternodeMetaMan& mn_metaman, const evo::StateOrigin& origin = evo::GenesisOrigin()); /** Store a full list for a snapshot chainstate, inside its open EvoDB * transaction. */ bool SeedListForBlock(const CDeterministicMNList& list) EXCLUSIVE_LOCKS_REQUIRED(!cs); ~CDeterministicMNManager(); bool ProcessBlock(gsl::not_null pindex, BlockValidationState& state, const CDeterministicMNList& oldList, const CDeterministicMNList& newList, MNListUpdates& updatesRet, kernel::Notifications& notifications) EXCLUSIVE_LOCKS_REQUIRED(!cs, ::cs_main); bool UndoBlock(gsl::not_null pindex, MNListUpdates& updatesRet) EXCLUSIVE_LOCKS_REQUIRED(!cs); /** Apply local metadata updates only after successful active-chain connection. */ void ResetPlatformBans(const CBlock& block, const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** Drop candidate state whose EvoDB transaction was rolled back. */ void DiscardBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(!cs); void UpdatedBlockTip(gsl::not_null pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs); CDeterministicMNList GetListForBlock(gsl::not_null pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs) { LOCK(cs); return GetListForBlockInternal(pindex); }; CDeterministicMNList GetListAtChainTip() EXCLUSIVE_LOCKS_REQUIRED(!cs); void SetListForBlockForTesting(const CDeterministicMNList& list) EXCLUSIVE_LOCKS_REQUIRED(!cs) { LOCK(cs); mnListsCache.insert_or_assign(list.GetBlockHash(), list); } // Test if given TX is a ProRegTx which also contains the collateral at index n static bool IsProTxWithCollateral(const CTransactionRef& tx, uint32_t n); // Recalculate and optionally repair diffs between snapshots struct RecalcDiffsResult { int start_height{0}; int stop_height{0}; int diffs_recalculated{0}; int snapshots_verified{0}; std::vector verification_errors; std::vector repair_errors; }; // Callback type for building a new MN list from a block using BuildListFromBlockFunc = std::function pindexPrev, const CDeterministicMNList& prevList, const CCoinsViewCache& view, bool debugLogs, BlockValidationState& state, CDeterministicMNList& mnListRet)>; [[nodiscard]] RecalcDiffsResult RecalculateAndRepairDiffs(const node::BlockManager& blockman, const CBlockIndex* start_index, const CBlockIndex* stop_index, BuildListFromBlockFunc build_list_func, bool repair) EXCLUSIVE_LOCKS_REQUIRED(!cs); [[nodiscard]] bool IsRepaired() const; void CompleteRepair() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); // Migration support for nVersion-first CDeterministicMNStateDiff format [[nodiscard]] bool IsMigrationRequired() const EXCLUSIVE_LOCKS_REQUIRED(!cs, ::cs_main); [[nodiscard]] bool MigrateLegacyDiffs(const CBlockIndex* const tip_index) EXCLUSIVE_LOCKS_REQUIRED(!cs, ::cs_main); private: void CleanupCache(int nHeight) EXCLUSIVE_LOCKS_REQUIRED(cs); CDeterministicMNList GetListForBlockInternal(gsl::not_null pindex) EXCLUSIVE_LOCKS_REQUIRED(cs); // Helper methods for RecalculateAndRepairDiffs static std::vector CollectSnapshotBlocks(const CBlockIndex* start_index, const CBlockIndex* stop_index, const Consensus::Params& consensus_params); bool VerifySnapshotPair(const CBlockIndex* from_index, const CBlockIndex* to_index, const CDeterministicMNList& from_snapshot, const CDeterministicMNList& to_snapshot, RecalcDiffsResult& result); static std::vector> RepairSnapshotPair( const node::BlockManager& blockman, const CBlockIndex* from_index, const CBlockIndex* to_index, const CDeterministicMNList& from_snapshot, const CDeterministicMNList& to_snapshot, BuildListFromBlockFunc build_list_func, RecalcDiffsResult& result); void WriteRepairedDiffs(const std::vector>& recalculated_diffs) EXCLUSIVE_LOCKS_REQUIRED(!cs); }; #endif // BITCOIN_EVO_DETERMINISTICMNS_H