Skip to content

feat: assumeutxo M2 — EvoDB multi-chainstate isolation and subsystem gating - #7456

Merged
PastaPastaPasta merged 17 commits into
dashpay:developfrom
PastaPastaPasta:assumeutxo/m2-evodb-roles
Aug 7, 2026
Merged

PastaPastaPasta merged 17 commits into
dashpay:developfrom
PastaPastaPasta:assumeutxo/m2-evodb-roles

Conversation

@PastaPastaPasta

@PastaPastaPasta PastaPastaPasta commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

M1 (#7451) added AssumeUTXO snapshot persistence, but Dash stores deterministic masternode, quorum, MNHF, and credit-pool state in a shared EvoDB. Running the snapshot and background chainstates concurrently therefore requires independent EvoDB transaction state and markers, chain-aware Dash validation, and protection against emitting or signing from the wrong chainstate.

This is milestone 2 of the AssumeUTXO series. It supplies the Dash-specific multi-chainstate foundation required by the later background-completion and loadtxoutset milestones.

What was done?

  • Added stable NORMAL and SNAPSHOT EvoDB identities, each with an independent transaction overlay, root batch, and best-block marker while retaining one physical EvoDB.
  • Added WriteDerived for immutable block-derived records. Independently derived values must serialize identically, including values pending in the other chainstate's overlay.
  • Wired block connect, disconnect, replay, verification, flushing, and snapshot activation to the calling chainstate's EvoDB identity. Snapshot activation now refuses a missing EvoDB marker instead of attaching snapshot coins to inconsistent Dash state.
  • Protected shared mined-quorum commitments from cross-chainstate erasure.
  • Passed the validating chainstate through Dash special-transaction and quorum processing. MNHF, asset-unlock, and quorum lookups now evaluate membership relative to the caller's chain instead of implicitly borrowing the active chain.
  • Suppressed active-tip, wallet, UI, and deterministic-masternode notifications from background validation. BlockChecked remains ungated because it reports validation results rather than active-tip changes.
  • Avoided penalizing peers when this snapshot-backed or pruned node cannot serve otherwise plausible masternode-list or quorum-rotation history.
  • Disabled DKG participation and quorum signing while an active snapshot remains unvalidated, including a final guard at the signature-share production boundary and clear RPC/status reporting.
  • Canonicalized serialization of block-derived masternode-list diffs and MNHF signals so logically identical values cannot produce false EvoDB mismatches.

Review follow-ups (appended commits):

  • A WriteDerived mismatch is local EvoDB corruption, never evidence about the block. It now aborts the node with M_ERROR (matching the existing EvoDbInconsistencyMessage convention) instead of marking the block BLOCK_CONSENSUS-invalid and penalizing the relaying peer. A typed EvoDbInconsistencyError preserves that classification through the catch blocks on the miner, RPC, and MNHF-recomputation paths.
  • EvoDB access outside a BeginTransaction scope previously always bound to the NORMAL identity, so transaction-less consumers (RPC, mempool, miner, P2P serving) could not see snapshot-chain records pending in the SNAPSHOT overlay. CEvoDB now tracks a default identity that snapshot activation sets to SNAPSHOT and ResetChainstates resets; the background-completion milestone must reset it to NORMAL at marker promotion (TODO noted in code).
  • GetListForBlockInternal no longer fabricates an empty "initial snapshot" masternode list when a diff for a DIP3-active block is missing; it throws instead. The message deliberately carries the IsBlockDataUnavailableError sentinel and is deliberately a plain runtime_error rather than EvoDbInconsistencyError: at that layer a missing diff can be benign (pending in the other chainstate's unflushed overlay, e.g. while serving historical mnlistdiff), so it is reported as unavailable history without penalizing the requesting peer, and only definite mismatches abort the node. Scheduler-thread consumers (CActiveMasternodeManager::UpdatedBlockTip, governance trigger creation) catch it and skip the update, since an uncaught exception there would terminate the node.

Second review round (appended commits):

  • bls::bls_legacy_scheme is process-wide, but the correct value belongs to the block being validated. ConnectBlock only saved and committed the flag; it never established it, and ProcessSpecialTxsInBlock switches legacy to basic only when crossing V19 forward. With an active post-V19 snapshot, the background chainstate therefore validated pre-V19 blocks under the basic scheme, and a background disconnect across V19 could commit legacy onto the active chain's consumers. ConnectBlock now enters under the scheme the block's parent left behind, and ConnectTip/DisconnectTip commit it only from the active chainstate.
  • The scheduler-thread guards caught every std::exception, so the plain runtime_errors that CDeterministicMNList::ApplyDiff raises for missing removals or updates, duplicate masternodes, and duplicate unique properties were logged as benign unavailable history while the active masternode stayed READY. The unavailable-history condition now has its own BlockDataUnavailableError type and is the only thing those guards (and BuildSimplifiedMNListDiff) catch; everything else propagates exactly as before the guards existed.
  • CEvoDB::GetCurrentIdentity() resolved to a process-wide active_transaction, so an open background NORMAL transaction redirected every concurrent transaction-less read away from the active snapshot's overlay. An open transaction is one validation execution context, not a process mode, so it now resolves only for the thread that began it.
  • Snapshot state could outlive the chainstate it describes in two ways, both fixed: PopulateAndValidateSnapshot commits the SNAPSHOT best-block and dual-chainstate markers as its last step, so abandoning activation afterwards (e.g. WriteSnapshotBaseBlockhash on an unwritable datadir) left a single-chainstate node carrying both; and -reindex/-reindex-chainstate wiped the shared EvoDB, erasing the SNAPSHOT marker while chainstate_snapshot stayed on disk, so startup failed on the erased marker with advice the user had already followed. Markers are now rolled back on abandoned activation, and the persisted snapshot chainstate's on-disk artifacts are discarded alongside the EvoDB wipe -- the Dash-shaped equivalent of the reindex-time cleanup in assumeutxo (2) bitcoin/bitcoin#27596/assumeutxo: Fix -reindex before snapshot was validated bitcoin/bitcoin#29726, which runs before any chainstate has coins views and so needs no mempool transfer or leveldb-lock dance.

The batch contains the original eight focused commits, a rebase fixture adaptation after the txindex removal, and eight review follow-up commits. The partial Bitcoin Core BlockInfo and ChainstateRole prerequisites were intentionally moved to the later loadtxoutset milestone where their APIs are first consumed.

How Has This Been Tested?

  • Added focused EvoDB unit coverage for overlay isolation, tombstones, cross-overlay derived-value checks, independent marker flushing, disk mismatch rejection, and preservation of the legacy NORMAL marker key.
  • Added dual-chainstate integration coverage for restart consistency, snapshot-only flushing, shared quorum erasure, chain-aware commitment/quorum lookup, cache-order isolation, and suppression of background notifications.
  • Added canonical serialization coverage for deterministic masternode-list diffs.
  • Added transaction_less_access_uses_default_identity covering default-identity resolution of transaction-less reads and writes. Known gap: the DIP3-active missing-diff throw has no end-to-end unit test because regtest activates DIP3 at height 432, above the unit-test chain heights; it is covered by the serving-path catch and review.
  • Before the stack-only relocation of the two unused Bitcoin prerequisite commits, make check passed and the following functional subset passed: feature_mnehf.py, feature_asset_locks.py, feature_dip3_deterministicmns.py (both modes), feature_llmq_signing.py (both modes), feature_llmq_rotation.py, and rpc_quorum.py.
  • After the review follow-up commits: full rebuild plus evo_db_tests, evo_deterministicmns_tests, evo_mnhf_tests, evo_assetlocks_tests, and validation_chainstatemanager_tests pass (20 cases), and lint-circular-dependencies is clean.
  • After the second review round (rebased onto develop at e829261): full rebuild clean and the complete test_dash suite passes (815 cases). Each new regression test was negative-controlled -- chainstate_connectblock_bls_scheme fails on both halves of the BLS fix independently, open_transaction_does_not_capture_other_threads fails without the thread scoping, and chainstatemanager_snapshot_discarded_on_reindex reproduces the unrecoverable reindex before the fix.
  • Every rewritten commit passes git diff-tree --check.

Breaking Changes

No released-interface changes. Internally, ActivateExistingSnapshot becomes fallible so startup can reject a snapshot chainstate whose EvoDB marker is missing. Two RPC-visible additions while a snapshot is active and unvalidated: masternode status gains a quorumParticipation field and appends a "DKG participation and quorum signing disabled" clause to status, and quorum sign fails with an explanatory error. AbstractEHFManager::Signals changed from std::unordered_map to std::map (canonical serialization); the on-disk encoding is unchanged, but iteration order of EHF signals in getblockchaininfo output is now sorted.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation (the AssumeUTXO documentation update is part of a later milestone)
  • I have assigned this pull request to a milestone

@PastaPastaPasta

Copy link
Copy Markdown
Member Author

@PastaPastaPasta
PastaPastaPasta force-pushed the assumeutxo/m2-evodb-roles branch 2 times, most recently from 06b5c6f to 1a95697 Compare July 14, 2026 17:01
@github-actions

Copy link
Copy Markdown

This pull request has conflicts, please rebase.

@github-actions

Copy link
Copy Markdown

This pull request has conflicts, please rebase.

@PastaPastaPasta
PastaPastaPasta force-pushed the assumeutxo/m2-evodb-roles branch from 26c8718 to b6edcf8 Compare August 1, 2026 18:17
@PastaPastaPasta
PastaPastaPasta force-pushed the assumeutxo/m2-evodb-roles branch from 11a31da to 5f3a876 Compare August 1, 2026 22:40
@knst

knst commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

that's not my final review feedback, I am not determined yet how exactly improve or change this PR or keep it as it is

  1. New sanitizers requires chainstate to be replaced to chainmanager; I repeat these changes independently, see fix: multiple asan's finding #7513
    These changes are unrelated to content of 7456 [make evodb multi-chainstate] and I'd like to get them merged independently.

  2. conceptually 7456 changes should work and it seems fine for me, concept ACK for me for idea as working.
    Though, I think changes here are not full.

There are several components that are logically part of chainstate, but initialized separately and behave differently.
They are:

  • credit_pool_manager (part of CChainstateHelper)
  • ehf_manager (part of CChainstateHelper)
  • mn_payments (part of CChainstateHelper)
  • dmnman. It's initialized inside chainstate, has in dependencies only evodb but many piece of validation of blocks are depends on dmnman
  • quorumsman. This class seems as a bit over-complex assuming that multiple chains could exist due to keeping caches inside, see: mapQuorumsCache, scanQuorumsCache, quorumBaseBlockIndexCache. Instead having 2 implementation for chain == nullptr and chain != nullptr maybe better to pull out these members to new object that is part of chainstate?

@PastaPastaPasta what is your thoughts on credit_pool_manager, ehf_manager, mn_payments? I think they should be part of ChainState.

And one more things: you have no plans to make evodb a part of assume-utxo, right?
Though, I think credit_pool_manager and ehf_manager probably should be.

=================

EvoDbIdentity - can I get clarification about this one? it means that one physical file with database will keep several logical copies of evo-db, right?
why not move evodb to chainstate in this case?
Alternativly, would not it be better to keep evodb as a just separate file?

-evodb = std::make_unique<CEvoDB>(db_params);
+m_evodb{std::make_unique<CEvoDB>(db_params, snapshot_base ? "evodb" + std::string{node::SNAPSHOT_CHAINSTATE_SUFFIX} : "evodb")},

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown

This pull request has conflicts, please rebase.

@PastaPastaPasta
PastaPastaPasta force-pushed the assumeutxo/m2-evodb-roles branch from 5f3a876 to d47d9b8 Compare August 2, 2026 18:42
@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown

This pull request has conflicts, please rebase.

@PastaPastaPasta
PastaPastaPasta force-pushed the assumeutxo/m2-evodb-roles branch from d47d9b8 to 7fabb1d Compare August 2, 2026 21:04
@PastaPastaPasta
PastaPastaPasta force-pushed the assumeutxo/m2-evodb-roles branch from 7fabb1d to bdd5626 Compare August 2, 2026 21:15
@PastaPastaPasta

Copy link
Copy Markdown
Member Author

@knst Fable's raw response:

The load-bearing fact his review is missing
Every piece of Dash evo state he lists is a pure function of blocks, keyed by block hash: creditPoolCache is Uint256LruHashMap<CCreditPool> looked up by pindex, mnhfCache likewise, dmnman's MN lists are block-keyed diffs, and quorum composition at base block B depends only on B's ancestry. Both chainstates share one global block index, so this state is chainstate-agnostic by construction — the MN list at height h is identical whether the background chain or the snapshot chain derived it.

The only state that is genuinely per-chainstate is tip tracking: which block each chainstate has flushed up to (best-block markers) and the in-flight transaction/undo stacks for the block currently connecting. That's exactly — and only — what EvoDbIdentity splits. Everything else stays shared, and the overlap becomes a feature: WriteDerived verifies that independently derived payloads agree byte-for-byte, aborting the node on divergence.

That's the frame for answering everything below.

Per-question answers
"EvoDbIdentity — one physical file keeping several logical copies of evo-db, right?"
No — this is the key clarification. One physical DB, one shared copy of all block-derived data (MN diffs, commitments, credit pool, EHF signals). Per-identity there are only: a transaction context (pending batches) and a best-block marker. The committed keyspace is not duplicated; cross-identity writes of the same key are disjoint by construction (background validates ≤ base, snapshot validates > base, seed is flushed at activation), and WriteDerived enforces identity when they do overlap. It's closer to "one ledger, two bookmarks" than "two ledgers."

"Why not move evodb into Chainstate / keep it as a separate suffixed file?"
His suffixed-file suggestion mirrors upstream's chainstate_snapshot dir and is a defensible alternative — but it was considered and has concrete costs:

Completion atomicity. Upstream completion renames chainstate_snapshot → chainstate. A second DB means a second rename that cannot be atomic with the first, which squares the crash-recovery matrix M3's RecoverSnapshotCleanup already has to handle for the chainstate rename alone. The single-DB design completes via PromoteSnapshotMarkers — one atomic batch write, no rename.
Lost cross-validation. With a shared keyspace, background validation incrementally re-derives and cross-checks the snapshot's seeded evo state via WriteDerived, catching a bad snapshot early and localizing the divergence. Separate files reduce this to a single holistic compare at completion.
Duplication. Two files store identical derived data for the overlapping range.
Downgrade safety was designed around the single file: released software ignores chainstate_snapshot and reads the legacy b_b4 marker, so the chainstate dir + legacy marker remain a consistent background pair and downgrade mid-snapshot degrades to background IBD (documented at the top of evodb.h).
"Should credit_pool_manager / ehf_manager / mn_payments (and dmnman) be part of Chainstate?"
I'd argue no, as members — and the series is deliberate about the alternative: managers stay singletons and the calling Chainstate& is threaded through validation ("bind block validation to the calling chainstate"). Reasons: (a) their state is block-keyed, so per-chainstate instances would duplicate identical state and forfeit the cross-check; (b) Chainstate objects are created and destroyed across snapshot activation/completion/ResetChainstates — embedding managers there recreates precisely the lifetime hazards #7513 just fixed, now for every consumer holding a manager reference (mempool, miner, RPC, net); (c) mempool/P2P/RPC need MN-list and quorum answers independent of which chainstate is active, so they'd route through ActiveChainstate()'s embedded members anyway — same shape, more indirection; (d) it forks upstream's Chainstate layout, growing the perpetual backport diff. On dmnman specifically: it's initialized in LoadChainstate/CompleteChainstateInitialization (not "inside chainstate") because reindex has to wipe and recreate it in lockstep with pblocktree — it's a per-load singleton, and [#7471](https://github.com/dashpay/dash/pull/7471) already moved its wiring into ChainstateLoadOptions.

"quorumsman is over-complex; pull the caches into a per-chainstate object?"
I think this reads the caches backwards. mapQuorumsCache/scanQuorumsCache/quorumBaseBlockIndexCache are all keyed by quorum-base block hash or pindex — that's what makes them already correct under multiple chainstates, and shared caching dedupes work where the two chains overlap (everything ≤ base). Per-chainstate cache objects would duplicate memory, recompute on the background chain, and add cache-lifecycle churn when the snapshot chainstate is deleted at completion. The chain == nullptr / != nullptr dual paths in ScanQuorums are a fair complexity complaint, but that's an independent refactor opportunity, not something the assumeutxo work requires or worsens.

"You have no plans to make evodb part of assume-utxo, right? Though credit_pool_manager and ehf_manager probably should be."
This one he'll be glad to hear: the plan is the opposite, and it's already built — he's reviewing M2 in isolation. M4 (assumeutxo/m4-evo-snapshot, fork PR PastaPastaPasta#53) defines evo snapshot format v3: the dump embeds the MN list at the base, quorum commitments and rotation cycles, the credit pool, MNHF/EHF signals, and asset-unlock ranges, with an evo_hash commitment in dumptxoutset output; loadtxoutset seeds evodb from it and background validation cross-checks the seed as it catches up. So credit pool and EHF are exactly where he thinks they should be — in the snapshot, not left behind.

This is based on the context of the full WIP assumeutxo implementation. I think it answers your questions well.

@PastaPastaPasta
PastaPastaPasta marked this pull request as ready for review August 3, 2026 00:04
@thepastaclaw

thepastaclaw commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

🔍 Review in progress — actively reviewing now (commit 066fca8)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bdd5626c20

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/evo/smldiff.cpp Resolved
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 066fca8b4f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/active/context.cpp

nodeman->UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload);

if (m_chainman.IsSnapshotActiveAndUnvalidated()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Move snapshot gate before masternode tip update

This guard runs after nodeman->UpdatedBlockTip(), so an active masternode that is not yet READY during an unvalidated snapshot can enter CActiveMasternodeManager::UpdatedBlockTip()'s Init(pindexNew) path before the gate is checked; InitInternal() calls GetListForBlock(pindexNew) without the new BlockDataUnavailableError catch, and that uncaught exception is on the scheduler validation callback path. In the same missing-history snapshot scenario this gate is meant to suppress, the node can terminate before DKG/signing is disabled, so check IsSnapshotActiveAndUnvalidated() before calling nodeman or catch the unavailable-list exception in the init path as well.

AGENTS.md reference: AGENTS.md:L168-L170

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/llmq/snapshot.cpp (1)

22-29: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add coverage for unavailability without peer penalization.

GETQUORUMROTATIONINFO already treats is not available (pruned or below an unvalidated snapshot base) as local unavailability, but p2p_quorum_data.py should include a pruned/unvalidated-snapshot request to cover this peer-sparing path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/llmq/snapshot.cpp` around lines 22 - 29, Extend the GETQUORUMROTATIONINFO
coverage in p2p_quorum_data.py with a request for block data that is unavailable
because it is pruned or below an unvalidated snapshot base. Assert that this
local-unavailability response does not penalize the peer, preserving the
existing handling for the error text produced by CheckBlockDataAvailable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/evo/evodb.cpp`:
- Around line 67-74: Update CEvoDB::BeginTransaction so GetContext(identity) and
CEvoDBScopedCommitter construction complete before assigning active_transaction
and active_transaction_thread; only publish transaction state after both
fallible operations succeed, while preserving the existing lock and returned
committer behavior.

In `@src/validation.cpp`:
- Around line 3594-3597: Require this == &m_chainman.ActiveChainstate() in the
UI tip notification conditions for both invalidation handling at
src/validation.cpp lines 3594-3597 and conflicting-chain handling at lines
3699-3702, alongside the existing pindex_was_in_chain checks; leave the
main-signal notifications unchanged.
- Line 2011: Initialize the required pre-disconnect BLS scheme before
UndoSpecialTxsInBlock in src/validation.cpp:2011, while preserving the scheme
transition committed by DisconnectTip; also initialize the pre-connect scheme
before ProcessSpecialTxsInBlock during replay in src/validation.cpp:4655 and
restore the active-chainstate scheme afterward. Add coverage for interrupted
post-V19 snapshot replay and CVerifyDB validation.

---

Nitpick comments:
In `@src/llmq/snapshot.cpp`:
- Around line 22-29: Extend the GETQUORUMROTATIONINFO coverage in
p2p_quorum_data.py with a request for block data that is unavailable because it
is pruned or below an unvalidated snapshot base. Assert that this
local-unavailability response does not penalize the peer, preserving the
existing handling for the error text produced by CheckBlockDataAvailable.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 37a9ab73-7488-4e6f-9838-ceae31e6e69a

📥 Commits

Reviewing files that changed from the base of the PR and between e829261 and 066fca8.

📒 Files selected for processing (45)
  • src/Makefile.test.include
  • src/active/context.cpp
  • src/active/context.h
  • src/active/dkgsessionhandler.cpp
  • src/active/masternode.cpp
  • src/dbwrapper.h
  • src/evo/assetlocktx.cpp
  • src/evo/assetlocktx.h
  • src/evo/chainhelper.cpp
  • src/evo/chainhelper.h
  • src/evo/creditpool.cpp
  • src/evo/deterministicmns.cpp
  • src/evo/deterministicmns.h
  • src/evo/evodb.cpp
  • src/evo/evodb.h
  • src/evo/mnhftx.cpp
  • src/evo/mnhftx.h
  • src/evo/smldiff.cpp
  • src/evo/smldiff.h
  • src/evo/specialtxman.cpp
  • src/evo/specialtxman.h
  • src/governance/signing.cpp
  • src/llmq/blockprocessor.cpp
  • src/llmq/blockprocessor.h
  • src/llmq/quorumsman.cpp
  • src/llmq/quorumsman.h
  • src/llmq/signing_shares.cpp
  • src/llmq/signing_shares.h
  • src/llmq/snapshot.cpp
  • src/net_processing.cpp
  • src/node/chainstate.cpp
  • src/node/miner.cpp
  • src/rpc/blockchain.cpp
  • src/rpc/masternode.cpp
  • src/rpc/quorums.cpp
  • src/test/evo_cbtx_tests.cpp
  • src/test/evo_db_tests.cpp
  • src/test/evo_deterministicmns_tests.cpp
  • src/test/util/setup_common.cpp
  • src/test/util/setup_common.h
  • src/test/validation_chainstate_tests.cpp
  • src/test/validation_chainstatemanager_tests.cpp
  • src/validation.cpp
  • src/validation.h
  • src/versionbits.h
🚧 Files skipped from review as they are similar to previous changes (36)
  • src/versionbits.h
  • src/Makefile.test.include
  • src/llmq/signing_shares.h
  • src/test/evo_deterministicmns_tests.cpp
  • src/net_processing.cpp
  • src/rpc/masternode.cpp
  • src/rpc/quorums.cpp
  • src/active/context.cpp
  • src/node/miner.cpp
  • src/llmq/quorumsman.h
  • src/dbwrapper.h
  • src/governance/signing.cpp
  • src/llmq/signing_shares.cpp
  • src/rpc/blockchain.cpp
  • src/evo/smldiff.cpp
  • src/evo/chainhelper.cpp
  • src/test/evo_cbtx_tests.cpp
  • src/evo/chainhelper.h
  • src/evo/creditpool.cpp
  • src/evo/assetlocktx.h
  • src/evo/mnhftx.cpp
  • src/evo/specialtxman.h
  • src/active/dkgsessionhandler.cpp
  • src/llmq/blockprocessor.h
  • src/active/masternode.cpp
  • src/evo/deterministicmns.cpp
  • src/evo/smldiff.h
  • src/test/util/setup_common.cpp
  • src/evo/specialtxman.cpp
  • src/active/context.h
  • src/llmq/quorumsman.cpp
  • src/evo/assetlocktx.cpp
  • src/test/validation_chainstatemanager_tests.cpp
  • src/llmq/blockprocessor.cpp
  • src/evo/evodb.h
  • src/evo/mnhftx.h

Comment thread src/evo/evodb.cpp
Comment on lines +67 to +74
std::unique_ptr<CEvoDBScopedCommitter> CEvoDB::BeginTransaction(EvoDbIdentity identity)
{
LOCK(cs);
assert(!active_transaction.has_value());
active_transaction = identity;
active_transaction_thread = std::this_thread::get_id();
GetContext(identity);
return std::make_unique<CEvoDBScopedCommitter>(*this, identity);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate evodb files =="
fd -a 'evodb\.(cpp|h)$|EvoDb' . || true

echo "== evodb outline =="
ast-grep outline src/evo/evodb.cpp --view expanded || true

echo "== relevant evodb.cpp sections =="
wc -l src/evo/evodb.cpp src/evo/evodb.h
sed -n '1,180p' src/evo/evodb.cpp
echo "== evodb.h =="
sed -n '1,240p' src/evo/evodb.h

echo "== calls to BeginTransaction and active_transaction =="
rg -n "BeginTransaction|active_transaction|active_transaction_thread|CEvoDBScopedCommitter|GetContext|Start|Commit|Rollback" src test contrib -S || true

Repository: dashpay/dash

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== evodb.cpp relevant lines =="
wc -l src/evo/evodb.cpp src/evo/evodb.h
sed -n '1,130p' src/evo/evodb.cpp
echo
sed -n '1,220p' src/evo/evodb.h

echo
echo "== focused BeginTransaction/assert usages =="
rg -n "active_transaction|active_transaction_thread|BeginTransaction|GetContext\\(|Commit|Rollback|scoped" src/evo/evodb.* src/test/evo_db_tests.cpp src -g '*.cpp' -g '*.h' -S

echo
echo "== evodb tests relevant sections =="
sed -n '1,120p' src/test/evo_db_tests.cpp
sed -n '120,280p' src/test/evo_db_tests.cpp

Repository: dashpay/dash

Length of output: 50369


Set transaction state after fallible construction.

GetContext(identity) and std::make_unique<CEvoDBScopedCommitter> can throw after active_transaction is set. The failed call leaves state without a committer to clear it, so the next BeginTransaction asserts and an in-party transaction may resolve with the stale identity if the caller reuses its thread. Build the context and committer before assigning active_transaction and active_transaction_thread.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/evo/evodb.cpp` around lines 67 - 74, Update CEvoDB::BeginTransaction so
GetContext(identity) and CEvoDBScopedCommitter construction complete before
assigning active_transaction and active_transaction_thread; only publish
transaction state after both fallible operations succeed, while preserving the
existing lock and returned committer behavior.

Comment thread src/validation.cpp

std::optional<MNListUpdates> mnlist_updates_opt{std::nullopt};
if (!m_chain_helper->special_tx->UndoSpecialTxsInBlock(block, pindex, mnlist_updates_opt)) {
if (!m_chain_helper->special_tx->UndoSpecialTxsInBlock(*this, block, pindex, mnlist_updates_opt)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Initialize the BLS scheme in direct replay and verification paths.

ReplayBlocks() and CVerifyDB call DisconnectBlock() directly. ReplayBlocks() also calls RollforwardBlock() directly. These paths bypass the guards in DisconnectTip() and ConnectBlock(). A post-V19 operation can then process BLS data with the scheme left by another chainstate.

  • src/validation.cpp#L2011-L2011: establish the required pre-disconnect scheme for direct DisconnectBlock() callers while preserving the transition that DisconnectTip() commits.
  • src/validation.cpp#L4655-L4655: establish the required pre-connect scheme before ProcessSpecialTxsInBlock() during replay, then restore the active-chainstate scheme after replay.

Add coverage for interrupted post-V19 snapshot replay and CVerifyDB validation.

📍 Affects 1 file
  • src/validation.cpp#L2011-L2011 (this comment)
  • src/validation.cpp#L4655-L4655
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/validation.cpp` at line 2011, Initialize the required pre-disconnect BLS
scheme before UndoSpecialTxsInBlock in src/validation.cpp:2011, while preserving
the scheme transition committed by DisconnectTip; also initialize the
pre-connect scheme before ProcessSpecialTxsInBlock during replay in
src/validation.cpp:4655 and restore the active-chainstate scheme afterward. Add
coverage for interrupted post-V19 snapshot replay and CVerifyDB validation.

Comment thread src/validation.cpp
Comment on lines +3594 to +3597
if (this == &m_chainman.ActiveChainstate()) {
GetMainSignals().SynchronousUpdatedBlockTip(m_chain.Tip(), nullptr, IsInitialBlockDownload());
GetMainSignals().UpdatedBlockTip(m_chain.Tip(), nullptr, IsInitialBlockDownload());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Suppress UI tip notifications for background chainstate changes.

GetMainSignals() now checks the active chainstate. The nearby uiInterface.NotifyBlockTip() calls only check pindex_was_in_chain. A background invalidation or chainlock conflict can therefore report its tip as a UI tip update.

  • src/validation.cpp#L3594-L3597: require the active-chainstate check in the invalidation UI notification condition.
  • src/validation.cpp#L3699-L3702: require the active-chainstate check in the conflicting-chain UI notification condition.
📍 Affects 1 file
  • src/validation.cpp#L3594-L3597 (this comment)
  • src/validation.cpp#L3699-L3702
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/validation.cpp` around lines 3594 - 3597, Require this ==
&m_chainman.ActiveChainstate() in the UI tip notification conditions for both
invalidation handling at src/validation.cpp lines 3594-3597 and
conflicting-chain handling at lines 3699-3702, alongside the existing
pindex_was_in_chain checks; leave the main-signal notifications unchanged.

@knst knst left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 066fca8

I'd probably have some comments for code in this PR when I will see assumeutxo M3....assumeutxo M7 but for now I am happy with Fable's responses here: #7456 (comment)

Comment thread src/rpc/masternode.cpp
CDeterministicMNState::GetJsonHelp(/*key=*/"dmnState", /*optional=*/true),
{RPCResult::Type::STR, "state", "Masternode state (human-readable string)"},
{RPCResult::Type::STR, "status", "Masternode status (human-readable string, based on current state)"},
{RPCResult::Type::BOOL, "quorumParticipation", "Whether DKG participation and quorum signing are enabled"},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the name of quorumPparticipation is a bit missleading ; can't figure out better naming.

@thepastaclaw any ideas?

@PastaPastaPasta
PastaPastaPasta merged commit ab65592 into dashpay:develop Aug 7, 2026
59 of 67 checks passed
@PastaPastaPasta PastaPastaPasta changed the title backport: assumeutxo M2 — EvoDB multi-chainstate isolation and subsystem gating feat: assumeutxo M2 — EvoDB multi-chainstate isolation and subsystem gating Aug 7, 2026
@PastaPastaPasta PastaPastaPasta added this to the 24 milestone Aug 7, 2026
PastaPastaPasta added a commit to PastaPastaPasta/dash that referenced this pull request Aug 12, 2026
…ompletion and snapshot promotion

c28ddc8 test: cover background MN-hash erase and the promote/discard recovery overlap (pasta)
a8b6790 docs: fix stale check_block_index reference and explain deferred candidate admission (pasta)
d16440b refactor: centralize durable rename/remove for the snapshot lifecycle (pasta)
413afb1 fix: report a missing snapshot base block as a startup error, not an abort (pasta)
4b1294c test: assert cold snapshot activation captures no base MN-list marker (pasta)
cedba66 docs: note the cross-chainstate duplicate-commitment corner (pasta)
ab3b671 validation: move the mempool to the snapshot chainstate on activation (pasta)
44bd797 refactor: share the block-data-unavailable sentinel as a named constant (pasta)
2ef1222 backport: adapt bitcoin#27746 for Dash (Pasta)
43efc47 Merge bitcoin#27746: Rework validation logic for assumeutxo (Ryan Ofsky)
d1ffdd6 Merge bitcoin#28050: test: make assumeUTXO test capture the expected fatal error (Pasta)
3da9105 Merge bitcoin#27862: validation: Stricter assumeutxo error handling when renaming chainstates (Pasta)
9cfc65a backport: adapt Dash EvoDB completion path for bitcoin#25740 (Pasta)
483b3d7 Merge bitcoin#25740: assumeutxo: background validation completion (Pasta)

Pull request description:

  ## Issue being fixed or feature implemented

  [M1 (dashpay#7451)](dashpay#7451) added AssumeUTXO snapshot persistence and [M2 (dashpay#7456)](dashpay#7456) gave the snapshot and background chainstates independent EvoDB identities, markers, and chain-aware Dash validation. What was still missing is the end of the lifecycle: nothing ever *completed* background validation, so a snapshot-backed node stayed in the dual-chainstate state (with DKG participation and quorum signing disabled) forever.

  This is milestone 3 of the AssumeUTXO series: background validation completion. When the background chainstate reaches the snapshot base block, the node now verifies the background-derived state against the snapshot, disables the background chainstate, and on the next restart promotes the snapshot chainstate (coins directory and EvoDB markers) to the normal single-chainstate layout.

  ## What was done?

  Upstream backports (kept 1:1 where practical, Dash adaptations in separate commits):

  - **bitcoin#25740** — assumeutxo: background validation completion. Adds `ChainstateManager::MaybeCompleteSnapshotValidation()` (UTXO-set hash comparison against `m_assumeutxo_data` when the background tip reaches the base block) and `ValidatedSnapshotCleanup()` (restart-time promotion of `chainstate_snapshot` over `chainstate`), with `SnapshotCompletionResult` reporting and the `chainstate_snapshot_INVALID` quarantine path.
  - **bitcoin#27862** — stricter error handling when renaming chainstates (abort instead of continuing after a failed rename).
  - **bitcoin#28050** — test: capture the expected fatal error during assumeutxo completion failure.
  - **bitcoin#27746** — rework validation logic for assumeutxo: `Chainstate::m_disabled` replaces ad-hoc usability checks, `CompleteChainstateInitialization()` split out of `LoadChainstate()` so chainstates can be reinitialized after cleanup, `LoadExternalBlockFile` moved to `ChainstateManager`, per-blockfile undo tracking without the active-chain reference, and `BLOCK_ASSUMED_VALID` documentation/semantics updates.

  Dash-specific completion path:

  - **EvoDB marker promotion.** `CEvoDB::PromoteSnapshotMarkers()` atomically (single synced batch) moves the SNAPSHOT best-block marker to the legacy NORMAL key and removes all dual-chainstate metadata; `DiscardSnapshotMarkers()` does the same for a rejected snapshot while preserving NORMAL state. Both reset the transaction-less default identity to NORMAL, closing the `TODO(assumeutxo)` markers left in M2.
  - **Base-state comparison.** Snapshot activation records a canonical hash of the deterministic masternode list at the base block (`EVODB_SNAPSHOT_MNLIST_HASH`); the background chainstate independently records the list hash it derives when it connects the base block (`EVODB_BACKGROUND_MNLIST_HASH`). Completion compares them (in addition to the upstream UTXO-set hash) and fails with `SnapshotCompletionResult::EVO_STATE_MISMATCH` on divergence. This is the first installment of the holistic base-state comparison M2 deferred; extending it to the CbTx `merkleRootMNList`/`merkleRootQuorums` and credit-pool commitments is called out as a TODO for the `loadtxoutset` milestone, where the snapshot payload gains Dash state. Until then this comparison is a **corruption tripwire, not an independent check**: in the only case both markers exist (activation with the background tip already at the base) they are written from a single derivation, and a cold-start activation captures neither and skips the comparison. Divergence therefore only signals on-disk damage to the marker pair; the independent comparison arrives when the snapshot payload carries the base MN list.
  - **Crash recovery.** `ValidatedSnapshotCleanup()` performs two directory renames plus a marker promotion, each individually durable. `RecoverSnapshotCleanup()` (run at startup before chainstate detection) classifies every interruption point — first rename done, both renames done with markers pending, promotion durable but deletion pending, invalid-snapshot rename done with marker discard pending — and either rolls back, finishes the promotion, or fails with a precise error instead of the generic reindex advice.
  - **Lifecycle correctness fixes discovered while wiring the above:** `EraseSnapshotMarkers()` (the abandoned-activation rollback from M2) now also erases the new MN-list-hash markers; snapshot activation moves the mempool to the snapshot chainstate and restart activation clears it from the background chainstate (the bitcoin#27596 shape), so background block connects can no longer call `removeForBlock`/`removeExpiredAssetUnlock` against mempool state built on the snapshot tip; the invalid-snapshot revert hands the mempool back.

  Review follow-ups from the M2 merge applied here:

  - The peer-penalty exemption for unavailable history no longer depends on three files repeating one literal string: the sentinel is a named constant (`BLOCK_DATA_UNAVAILABLE_SUFFIX`) shared by every producer and the matcher.
  - The background MN-list hash is computed only for the snapshot base block (activation captures it directly when the background tip is already at the base). The initial implementation hashed the full deterministic MN list on every block connect, which would have been a measurable IBD regression on every node.
  - A comment documents the cross-chainstate duplicate-commitment corner in `CQuorumBlockProcessor::ProcessCommitment`.

  Review follow-ups from the dashpay#7553 review round:

  - A snapshot base block missing from the on-disk block index is now reported by `ChainstateManager::LoadBlockIndex()` as a normal startup failure (recoverable via the standard reindex advice), instead of aborting in candidate admission; `GetSnapshotBaseBlock()` regains upstream's cached `SnapshotBase()` delegation (bitcoin d4a11ab) that the initial adaptation had dropped. Note the related deliberate deviation: `MaybeCompleteSnapshotValidation()` converts one upstream hard assert into a `SKIPPED` return for synthetic in-memory unit fixtures, discriminated by `CoinsDB().StoragePath()` being empty.
  - Every snapshot-lifecycle directory rename/removal now goes through new `RenameDurably()`/`RemoveAllDurably()` helpers (`fs::rename`/`fs::remove_all` + `DirectoryCommit`), so the crash-recovery invariant is enforced by the helper rather than by remembering a follow-up call at six sites.
  - New tests: a missing-base startup failure, the promote/discard overlap state in `RecoverSnapshotCleanup` (must land in the same end state as a completed discard), and background-MN-hash coverage in the marker rollback test.

  With completion wired, the M2 duty gate resolves end-to-end: `IsSnapshotActiveAndUnvalidated()` becomes false at completion, so DKG participation and quorum signing re-enable without a restart, and the `masternode status` clause clears.

  ## How Has This Been Tested?

  - Rebased onto develop immediately after the M2 merge (`ab65592f85d`); every conflict was resolved against M2's final review round (thread-scoped EvoDB transactions, `EraseSnapshotMarkers`, reindex-time snapshot discard, fallible `DetectSnapshotChainstate`, BLS scheme establishment). The merged M2 test `chainstate_connectblock_bls_scheme` is adapted in the bitcoin#27746 commit for `AcceptBlock` moving to `ChainstateManager`.
  - Full clean build (autotools, `--enable-debug`), then the complete `test_dash` suite passes ("No errors detected"), including targeted reruns of `evo_db_tests`, `validation_chainstatemanager_tests`, `validation_chainstate_tests`, `evo_deterministicmns_tests`, `evo_mnhf_tests`, `evo_assetlocks_tests`, `evo_cbtx_tests`, `blockmanager_tests`, `coinstatsindex_tests`, and `validation_block_tests`.
  - New coverage: `snapshot_marker_promotion_and_discard` (promotion/discard idempotency across restarts), the extended abandoned-activation marker rollback test, `chainstatemanager_snapshot_completion` and `_hash_mismatch` (upstream-shaped), an `EVO_STATE_MISMATCH` completion case, four crash-recovery tests that each reproduce a distinct `ValidatedSnapshotCleanup` interruption point on disk and drive it through `LoadVerifyActivateChainstate()`, and mempool-ownership assertions at both activation paths.
  - An independent review pass traced the highest-risk interactions end to end: the `ConnectTip` → `MaybeCompleteSnapshotValidation` EvoDB transaction lifecycle (the scoped committer closes before completion runs, so the single-open-transaction invariant holds), BLS-scheme guard nesting across connect/disconnect, all four mempool handoff transitions, and the recovery state machine. Its two "correct but implicit" findings are addressed in the final commit (at-rest raw reads for the lifecycle markers; a comment documenting the deliberate promote/discard overlap in `RecoverSnapshotCleanup`).
  - `lint-circular-dependencies`, `lint-python`, and `git diff --check` are clean.

  ## Breaking Changes

  None released. The dual-chainstate on-disk state introduced in M2 (unreleased) gains two lifecycle marker keys (`b_dcs_mn`, `b_dcs_bg_mn`); nodes that never load a snapshot never write any of them. `ChainstateLoadStatus::FAILURE_FATAL` is a new internal failure class treated like `FAILURE_INCOMPATIBLE_DB` at init.

  ## Checklist:

  - [x] I have performed a self-review of my own code
  - [x] I have commented my code, particularly in hard-to-understand areas
  - [x] I have added or updated relevant unit/integration/functional/e2e tests
  - [ ] I have made corresponding changes to the documentation (`doc/design/assumeutxo.md` updated for the implemented lifecycle; the user-facing AssumeUTXO documentation lands with `loadtxoutset`)
  - [ ] I have assigned this pull request to a milestone

Top commit has no ACKs.

Tree-SHA512: 0a5b28e1d1301a9c7a3bd0d825e2890408baf6d93ef697c8569913f680540122af277f3860386416bdbb5df5d6ee087af8f1f9af8780bd3d7a5967a420fa4896
knst added a commit to knst/dash that referenced this pull request Nov 30, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
knst added a commit to knst/dash that referenced this pull request Nov 30, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
knst added a commit to knst/dash that referenced this pull request Nov 30, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
knst added a commit to knst/dash that referenced this pull request Dec 1, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
knst added a commit to knst/dash that referenced this pull request Dec 1, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
knst added a commit to knst/dash that referenced this pull request Dec 1, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
knst added a commit to knst/dash that referenced this pull request Dec 1, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
PastaPastaPasta added a commit that referenced this pull request Dec 1, 2026
c026c31 validation: resolve EHF signals from the chainstate holding the block (Konstantin Akimov)
2939c22 evo: MNHF signals of a snapshot chainstate (Konstantin Akimov)
280d321 evo: give each chainstate's Evo state its origin (Konstantin Akimov)
4567b4c llmq: erase a disconnected block's mined commitments unconditionally (Konstantin Akimov)
483a73b evo: give each chainstate its own Evo state (Konstantin Akimov)
b726669 txmempool: let the chainstate holding the mempool rebind its MN manager (Konstantin Akimov)
b7bf6e5 feat(dbwrapper): report LevelDB iterator read errors (pasta)
1a2a603 refactor(llmq): stop writing the unused q_bbu2 best-block key (pasta)
9354b28 Revert "Merge #8237: feat: keep snapshot-chainstate Evo state in its own EvoDB generation" (Konstantin Akimov)

Pull request description:

  ## Issue being fixed or feature implemented

  With an AssumeUTXO snapshot loaded, a node runs two chainstates, and each derives its own Evo state from its own chain. #8237 keeps both in one EvoDB, split into generations, with one instance of every manager: the view a call reads is resolved from the calling thread's open EvoDB transaction or from a default identity. Every cache in those managers is then shared between the two views, and every one of the roughly 110 call sites has to read the right one. The rest of the stack exists to make that safe: #8238 partitions every Evo-derived cache by view, #7887 binds non-active paths and dispatcher boundaries to a view, and #8270 rejects unbound reads and stops reads of a rejected generation.

  This PR takes the other route: the Evo state derived from a chain belongs to the chainstate that derived it. Each `Chainstate` owns its own EvoDB and its own managers, so there are no views, identities or cache partitions, and a rejected snapshot drops its Evo state with its chainstate. It reverts #8237 and replaces #8238, #7887 and #8270: there are no views to partition, bind or reject reads from. What remains needed of #7887, the containment of local Evo errors on worker threads, comes later in the stack with the code that can raise them. It is the base of the reworked AssumeUTXO stack; #7593 and #8271 follow on top of it.

  ## What was done?

  - **Revert of #8237**, with two of its commits that do not depend on generations re-applied: "refactor(llmq): stop writing the unused q_bbu2 best-block key" and "feat(dbwrapper): report LevelDB iterator read errors" (both by pasta).
  - **`EvoChainState`**: one bundle per `Chainstate` holding its `CEvoDB`, `CDeterministicMNManager`, `CQuorumSnapshotManager`, `CQuorumBlockProcessor`, `CQuorumManager` and `CSpecialTxProcessor` (with the credit pool and MNHF managers). A `ChainstateManager` factory (`m_make_evo_chainstate`), set by init, the test fixtures and `bitcoin-chainstate`, builds it for every chainstate. The background chainstate keeps `evodb/`; a snapshot chainstate's state lives in `evo_snapshot/`.
  - **Node-wide access**: `NodeContext::evodb`, `dmnman` and `special_tx` and `LLMQContext::qsnapman`, `quorum_block_processor` and `qman` are gone. `PeerManager`, the signing manager, RPC, the node interfaces and the provider-transaction service read the active chainstate's Evo state per call through `ChainstateManager::ActiveEvo()`; the miner uses the Evo state of the chainstate it builds on; the mempool's masternode manager is rebound when a chainstate takes the mempool. `EnsureActiveEvo()` throws an RPC error when no Evo state is loaded, and the node interface methods resolve the Evo state once per call and return their "not available" result without it.
  - **BLS check queue**: the quorum block processor owned the queue of `-parbls` threads, and with one processor per chainstate a node with a snapshot would run two. `LLMQContext`, which sized it on develop and owns the BLS worker, owns the one queue, and every chainstate's block processor uses it.
  - **Shutdown**: `ChainstateManager::CloseEvoState()` destroys every chainstate's Evo state, joining its threads and closing its databases. `PrepareShutdown()` calls it where develop reset the node-wide managers, so a restarting Dash-Qt releases the databases before the replacement opens them, and the destructor calls it before the block index is freed. The LLMQ context, which owns the BLS worker, is reset after it.
  - **`CEvoDB` is a single database again**: `EvoDbIdentity`, the per-identity transaction contexts, the default identity and the dual-chainstate markers from #7456 are removed. `EvoViewBindingError`, which only that code raised, goes with it. The same-database check of `WriteDerived()`, the thread scoping of `HasActiveTransaction()`, and the missing-state errors stay.
  - **Snapshot lifecycle**: a rejected snapshot leaves `evo_snapshot/` behind and the next start removes it when no snapshot chainstate is active, as does a reindex. Completion compares the masternode list each chainstate holds at the base. After a validated snapshot, the cleanup merges the snapshot chainstate's EvoDB into the background chainstate's (`CEvoDB::MergeSnapshot()`), marks the promotion pending, swaps the coins directories, and the next `LoadChainstate()` finishes it (`FinishPromotion()`) once the coins database is open and only if its tip is the one the Evo state was merged for; otherwise startup asks for `-reindex-chainstate`. A cleanup interrupted between the merge and the renames resumes on the next start instead of validating the snapshot again. Startup leaves a pending promotion and `evo_snapshot/` alone while a snapshot chainstate directory exists that could not be activated. The base block hash is written only for a snapshot that loaded. Startup refuses a persisted snapshot chainstate whose Evo state is not at its coins tip. This replaces the Dash promotion path of #7553 (completion markers, `RecordBackgroundMNListHash`).
  - **Mined commitments**: a chainstate disconnecting a block erased its mined commitments only if no other chainstate contained the block, because both shared one keyspace. `EraseMinedCommitmentIfUnreferenced` is removed.
  - **`evo::StateOrigin`**: the snapshot base (hash, and height once the block index is loaded) of a chainstate's Evo state, owned by its `EvoChainState` and handed to its managers. The masternode manager is the first to use it: at or below the base only the lists a snapshot carried exist, so a missing one is reported as unavailable instead of being rebuilt from diffs the chainstate never had. Startup also skips the masternode list diff repair for Evo state that comes from a snapshot: it has no lists below its base, which the repair would report as corruption. The repair runs on the chainstate that was active at startup. `evodb verify` and `evodb repair` refuse such state for the same reason.
  - **Masternode list cache**: only the active chainstate's masternode manager is told its tip, and the list cache was pruned against that tip only. A manager whose chainstate connects blocks without being the active one now prunes against the block it processes.
  - **EHF signals**: versionbits read EHF signals through one global instance, which was the active chainstate's MNHF manager, so a background chainstate's deployment checks read the snapshot chainstate's signals. `ChainstateManager` now registers a router: a block above the snapshot base is answered by the snapshot chainstate, the base and its ancestors by the background chainstate where it connected them and otherwise from the signal record a snapshot chainstate carries. The deployment states of blocks the background chainstate has connected are cached apart, so background validation never reuses a state derived from the carried record. A snapshot that fails to load or is rejected at completion resets the routing and clears the versionbits cache. `getdeploymentinfo` reads the signals of the queried block through the router.
  - `lint-circular-dependencies.py` lists the two include cycles that come from validation owning each chainstate's Evo state.

  Not in this PR, and safe to leave for later in the stack because nothing here activates a snapshot at runtime outside unit tests: the masternode, quorum-watching, governance, CoinJoin and net-handler services still take the Evo managers of the chainstate active at startup. The duty gates from #7456 and #8049 are kept.

  ## How Has This Been Tested?

  Unit tests
  - Added to `validation_chainstatemanager_tests`:
    - `chainstatemanager_evo_state_is_per_chainstate`: each chainstate gets its own Evo state, and the active one is what `ActiveEvo()` returns.
    - `chainstatemanager_snapshot_init_missing_evo_state`: a snapshot chainstate without `evo_snapshot/` fails startup and asks for a reindex.
    - `chainstatemanager_snapshot_cleanup_resumes_merged_promotion`: a crash after the Evo state was merged, before the coins directories were swapped, resumes the promotion without validating the snapshot again.
    - `chainstatemanager_snapshot_cleanup_refuses_promotion_without_its_coins`: with the snapshot coins gone, startup does not finish the promotion on the background chainstate's coins and asks for `-reindex-chainstate`.
  - Added to `evo_db_tests`:
    - `merge_snapshot_and_finish_promotion`: an interrupted merge runs again, and the best block stays at the base until the promotion finishes.
    - `open_transaction_belongs_to_its_thread`.
  - Removed, because they test code this PR removes:
    - `evo_db_tests`: the generation, identity, marker and journaled-promotion cases.
    - `validation_chainstatemanager_tests`: `chainstatemanager_evodb_reorg_erase_guard`, `chainstatemanager_mined_commitment_is_chain_aware`, `chainstatemanager_snapshot_init_missing_evodb_marker`, `chainstatemanager_snapshot_completion_without_base_list_marker`, `chainstatemanager_snapshot_cleanup_{keeps_earlier_invalid_dir,keeps_live_snapshot_dir,overlap_promote_equals_discard,recovers_prepared_promotion,recovers_promoted_swap,recovers_rejection_before_rename}`, `chainstatemanager_snapshot_promotion_crash_{after_collect,after_merge,mid_merge}`.
  - Updated for the fixtures (`ActiveEvo()` instead of node-wide managers): the evo, llmq, coinjoin, governance, wallet and qt unit tests and `test/util/setup_common`.

  No functional test changes: the behaviour of a node with one chainstate is unchanged.

  ## Breaking Changes

  None for released versions. A regtest datadir that holds a snapshot chainstate created by a develop build (Evo state as a generation inside `evodb/`) reports a missing snapshot Evo state at startup and needs `-reindex`.

  ## Checklist:
  - [x] I have performed a self-review of my own code
  - [ ] I have made corresponding changes to the documentation
  - [x] I have assigned this pull request to a milestone _(if you have permission to set one)_

Top commit has no ACKs.

Tree-SHA512: d65538bfb7f3d8672a615b3404780cc84935891ec71607cbd4b2c06c9f9683d55dbad1c5e45c0ddf35df8d570c7211dfd5a3f2600dec2ded4d5fa24299a0402d
knst added a commit to knst/dash that referenced this pull request Dec 1, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
PastaPastaPasta pushed a commit to PastaPastaPasta/dash that referenced this pull request Dec 4, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
PastaPastaPasta pushed a commit to PastaPastaPasta/dash that referenced this pull request Dec 4, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
PastaPastaPasta pushed a commit to PastaPastaPasta/dash that referenced this pull request Dec 4, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
PastaPastaPasta pushed a commit to PastaPastaPasta/dash that referenced this pull request Dec 4, 2026
…ion is incomplete"

This reverts commit 7230da6 (dashpay#8049), together with the phase abort dashpay#7456 put in WaitForNextPhase for the same case. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so the DKG phase threads never run beside an unvalidated snapshot and both gates are dead code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants