Skip to content

fix: refuse unsafe AssumeUTXO snapshot loads and harden rejection, with a Dash end-to-end test - #8273

Open
PastaPastaPasta wants to merge 43 commits into
dashpay:developfrom
PastaPastaPasta:feat/assumeutxo-dash-hardening
Open

PastaPastaPasta wants to merge 43 commits into
dashpay:developfrom
PastaPastaPasta:feat/assumeutxo-dash-hardening

Conversation

@PastaPastaPasta

@PastaPastaPasta PastaPastaPasta commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

The Dash-specific fixes and refusals the loader needs, the stall bookkeeping for a snapshot chainstate's missing Evo state, and an end-to-end test on a masternode network.

AssumeUTXO stack (merge in this order; each PR holds the commits of the ones below it; #8272 has merged): #8078 → #8273 → #8079 → #8276. Review only the commits listed as new.

Restack (2026-12-04). This PR now sits on the restacked #8078, on the per-chainstate Evo design that #8286 put on develop. Its commits are the versions knst ported onto that design in #8284.

What was done?

New on top of #8078:

  1. 03f240d855 fix(governance): wait for the collateral index to follow the active chainstate.
  2. f1e26ac67e fix(validation): serialize snapshot activations. A second concurrent loadtxoutset is refused before it touches the first activation's state.
  3. 966c0d3fe5 fix(validation): replace a leftover chainstate_todelete at promotion.
  4. 039524aeb6 fix(validation): detach the mempool when a snapshot is rejected.
  5. cc528716ef fix(validation): stop loading a mempool file once its chainstate no longer holds the mempool.
  6. bcb2c6501b test: add an end-to-end AssumeUTXO test on a Dash masternode network. feature_assumeutxo_dash.py extends the dump test from feat: emit the v4 evo snapshot section and require a matching evo pin #7601: it loads the dumps on cold nodes, refuses mutated files and pins, and rejects at completion. It then sends InstantSend, withdrawal and EHF traffic above the base, raises an InstantSend conflict before validation completes, and covers a basic-scheme ChainLock before v19, an EHF stall across a restart, and promotion.
  7. 5c2abac903 fix(validation): refuse packages through a chainstate that does not hold the mempool.
  8. 6cde1e7b0c fix(validation): refuse a snapshot that omits a known ChainLock, allow a reindex past one.
  9. fbee5ddcc9 test: dump on a node that numbers masternodes differently.
  10. cd1c2d9be2 feat(rpc,net): refuse Evo history requests until snapshot background validation completes.
    • Historical Evo RPCs (getquorumproofchain, quorum rotationinfo, protx diff/listdiff, …) are refused, and so are the historical forms of the list and info RPCs at or below the base. Their tip forms keep working.
    • GETMNLISTDIFF and GETQUORUMROTATIONINFO are not served, with no misbehavior score.
  11. 95aeeee27b feat(validation): remember Evo state stalls and keep the chain usable around them.
    • The chainstate remembers the blocks whose Evo state it could not derive, refuses them at once until a restart, and logs the first stall.
    • Candidate selection passes over branches through a stalled block. InvalidateBlock, ChainLock enforcement and block import stop at a stall instead of aborting.
  12. a201ead5a2 test: the promoted lists carry the validated masternode numbering (knst).
  13. 14f8fb15c5 test: cover the evo snapshot section, completion and stalls of a snapshot chainstate (knst). The unit cases for the stall bookkeeping and completion.
  14. 3196da7942 test: compare a snapshot node's masternodes and quorums with a synced node (knst).

What to focus on: commits 8 and 11, and the end-to-end test.

How Has This Been Tested?

On Linux x86_64 (Debug, GCC, depends, -DWERROR=ON), this head builds. validation_chainstatemanager_tests, validation_chainstate_tests, evo_snapshot_tests, evo_db_tests and evo_islock_tests pass at this head.

At the top of the stack (#8276), the full test_dash passes, and so do feature_assumeutxo, feature_assumeutxo_dash, feature_assumeutxo_refusals, wallet_assumeutxo and rpc_dumptxoutset.

To test: test/functional/test_runner.py feature_assumeutxo_dash.py feature_assumeutxo_refusals.py.

Breaking Changes

None with a single chainstate. Snapshots can only be loaded on regtest until the network pins (#8276) land.

Checklist:

  • I have performed a self-review of my own code
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

@PastaPastaPasta PastaPastaPasta added this to the 24.1 milestone Nov 27, 2026
@github-actions

Copy link
Copy Markdown

This pull request has conflicts, please rebase.

@thepastaclaw

thepastaclaw commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 3196da7) · triage: normal · Phase 2 only (queue backlog)

@thepastaclaw thepastaclaw 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.

Final validation — Phase 1 + Phase 2

Changes requested: 2 blockers

  • A higher-work snapshot can replace the active chain with a fork that contradicts a known ChainLock — src/validation.cpp:6898-6910 (new; not shown inline, see below)
    Impact: A regtest operator loading a pinned snapshot from a competing fork can make the node report that fork as active even though it omits a block the node already knows is ChainLocked.
  • An existing snapshot blocks a reindex that would discard it — src/init.cpp:2173-2189 (new; not shown inline, see below)
    Impact: A regtest operator who requests a full reindex to abandon a snapshot and rebuild with pruning or a legacy index gets a startup error instead of the requested rebuild.

This layer adds AssumeUTXO load and startup refusals, hardens snapshot rejection and mempool handoff, and adds end-to-end coverage on a Dash masternode network. The Linux and ASan builds, lint, and Cppcheck passed; the Linux and ASan test jobs were still pending when checked. The head is 45 commits behind develop and has six merge conflicts.

🔴 2 blocking | 🟡 4 suggestion(s)

6 finding(s) not shown inline (GitHub refused the PR diff as too large)

🔴 Blocking: A higher-work snapshot can replace the active chain with a fork that contradicts a known ChainLock
Impact: A regtest operator loading a pinned snapshot from a competing fork can make the node report that fork as active even though it omits a block the node already knows is ChainLocked.
src/validation.cpp:6898-6910

The load and the final switch both accept this fork. If the competing headers arrived before the ChainLock and the locked block is already on the active chain, EnforceBlock() stops at that block without marking the competing branch. The flag scan in SnapshotActivationRefusal() therefore finds no conflict, and HasConflictingChainLock(base.nHeight, ...) returns false when the base is higher than the lock. Compare the base and the best known locked block at the lower of their two heights when ChainLocks are enabled. Extend the refusal test to exercise a known lock on the active chain with competing headers already indexed; setting BLOCK_CONFLICT_CHAINLOCK by hand only tests the flag scan.

source: gpt-6.2-sol (phase2-reviewer: general, dash-core-commit-history)

🔴 Blocking: An existing snapshot blocks a reindex that would discard it
Impact: A regtest operator who requests a full reindex to abandon a snapshot and rebuild with pruning or a legacy index gets a startup error instead of the requested rebuild.
src/init.cpp:2173-2189

The error tells operators to wait for validation and promotion even when they explicitly asked to discard the snapshot. AppInitMain() refuses based on directory existence before reading the reset flags, but LoadChainstate() deletes the snapshot on either reset path before DetectSnapshotChainstate() can open it. Apply the refusal only to startup paths that retain the snapshot. Add a restart case using a supported combination, such as -reindex -prune=1 -txindex=0, and check that it rebuilds without using the snapshot.

source: gpt-6.2-sol (phase2-reviewer: general, dash-core-commit-history)

🟡 Suggestion: A mempool file import can still change the pool after its chainstate loses ownership
Impact: If snapshot activation overtakes a mempool import, the old import can apply fee priorities to the new chainstate’s pool and report success without checking ownership again.
src/node/mempool_persist.cpp:88-99

The ownership check protects transaction admission but not the rest of the import. Per-transaction fee deltas are applied before the check, expired entries skip it, and the trailing fee deltas and unbroadcast flags are applied without it. A metadata-only dump can therefore mutate the pool and return success without ever checking ownership. Check ownership under cs_main together with each batch of mutations and return a distinct ownership-loss result. That would let importmempool explain why the import stopped and let startup distinguish a load that stopped from one that completed just before the switch; the current post-load ownership sample can leave loaded false after a completed load and suppress the shutdown dump. Moving the RPC’s initial chainstate selection under a wider lock alone would not protect the later mutations.

source: muse-spark-1.3-contributor (phase1-reviewer: general); gpt-6.2-sol (phase2-reviewer: general, dash-core-commit-history)

🟡 Suggestion: Single-session CoinJoin can keep waiting for a block after a snapshot has advanced the tip
Impact: A regtest wallet whose CoinJoin client was waiting one more block can stay stuck until another block connects, even after snapshot activation advances the chain and masternode sync finishes.
src/validation.cpp:6851-6863

WaitForAnotherBlock() subtracts the last successful height from the client’s cached height. CJWalletManagerImpl updates that cache only through UpdatedBlockTip() and handles neither InitializeSnapshotTip() nor its default InitializeCurrentBlockTip() callback. A snapshot at the best header can therefore satisfy the height requirement without clearing the wait. Update the CoinJoin height cache through the snapshot-tip callback without emitting a normal block event or triggering a wallet rescan.

source: gpt-6.2-sol (phase2-reviewer: general, dash-core-commit-history)

🟡 Suggestion: The completion test can pass even if a background block resets InstantSend’s cached height
Impact: CI can pass the Dash end-to-end test even if snapshot completion incorrectly delivers its last background block to InstantSend as an active block.
test/functional/feature_assumeutxo_dash.py:679-689

The old-cycle lock checks signature verification, not the notification behavior claimed by the test. NetInstantSend::BlockConnected() would cache the historical height if given the wrong role, but BuildVerificationBatch() selects the signing start using the active chain’s actual height, so the expected processing islock log can still appear. Keep the old-cycle verification check and add a focused completion test that drains the validation queue and checks that GetTipHeight() still reports the snapshot tip.

source: gpt-6.2-sol (phase2-reviewer: general, dash-core-commit-history)

🟡 Suggestion: The mempool detachment commit leaves file and package admission unguarded until later commits
Impact: A maintainer bisecting snapshot rejection can land on a revision where a mempool file load can assert and package admission can still operate on a pool that no chainstate owns.
<commit:32933baa29d>:1

32933baa29d introduces the no-owner state. At that revision, LoadMempool() can still call AcceptToMemoryPool(), which asserts that the chainstate has a mempool, and ProcessNewPackage() takes the node’s pool without checking ownership. The guards added by 0330f63d0fe and e5235ca35ac are also useful when activation transfers ownership, so they can land before detachment. Put the guards first and keep the rejection-specific coverage with the commit that introduces detachment.

source: gpt-6.2-sol (phase2-reviewer: general, dash-core-commit-history)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: dash-core-commit-history); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: dash-core-commit-history); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The new commits intricately coordinate snapshot activation, rejection, mempool ownership, and index startup, but the only storage migration change is a narrow stale-directory cleanup in ChainstateManager::ValidatedSnapshotCleanup before the existing promotion rename.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — dash-core-commit-history (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — dash-core-commit-history (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `src/validation.cpp`:
- [BLOCKING] src/validation.cpp:6898-6910: A higher-work snapshot can replace the active chain with a fork that contradicts a known ChainLock
  Impact: A regtest operator loading a pinned snapshot from a competing fork can make the node report that fork as active even though it omits a block the node already knows is ChainLocked.
  The load and the final switch both accept this fork. If the competing headers arrived before the ChainLock and the locked block is already on the active chain, `EnforceBlock()` stops at that block without marking the competing branch. The flag scan in `SnapshotActivationRefusal()` therefore finds no conflict, and `HasConflictingChainLock(base.nHeight, ...)` returns false when the base is higher than the lock. Compare the base and the best known locked block at the lower of their two heights when ChainLocks are enabled. Extend the refusal test to exercise a known lock on the active chain with competing headers already indexed; setting `BLOCK_CONFLICT_CHAINLOCK` by hand only tests the flag scan.
- [SUGGESTION] src/validation.cpp:6851-6863: Single-session CoinJoin can keep waiting for a block after a snapshot has advanced the tip
  Impact: A regtest wallet whose CoinJoin client was waiting one more block can stay stuck until another block connects, even after snapshot activation advances the chain and masternode sync finishes.
  `WaitForAnotherBlock()` subtracts the last successful height from the client’s cached height. `CJWalletManagerImpl` updates that cache only through `UpdatedBlockTip()` and handles neither `InitializeSnapshotTip()` nor its default `InitializeCurrentBlockTip()` callback. A snapshot at the best header can therefore satisfy the height requirement without clearing the wait. Update the CoinJoin height cache through the snapshot-tip callback without emitting a normal block event or triggering a wallet rescan.

In `src/init.cpp`:
- [BLOCKING] src/init.cpp:2173-2189: An existing snapshot blocks a reindex that would discard it
  Impact: A regtest operator who requests a full reindex to abandon a snapshot and rebuild with pruning or a legacy index gets a startup error instead of the requested rebuild.
  The error tells operators to wait for validation and promotion even when they explicitly asked to discard the snapshot. `AppInitMain()` refuses based on directory existence before reading the reset flags, but `LoadChainstate()` deletes the snapshot on either reset path before `DetectSnapshotChainstate()` can open it. Apply the refusal only to startup paths that retain the snapshot. Add a restart case using a supported combination, such as `-reindex -prune=1 -txindex=0`, and check that it rebuilds without using the snapshot.

In `src/node/mempool_persist.cpp`:
- [SUGGESTION] src/node/mempool_persist.cpp:88-99: A mempool file import can still change the pool after its chainstate loses ownership
  Impact: If snapshot activation overtakes a mempool import, the old import can apply fee priorities to the new chainstate’s pool and report success without checking ownership again.
  The ownership check protects transaction admission but not the rest of the import. Per-transaction fee deltas are applied before the check, expired entries skip it, and the trailing fee deltas and unbroadcast flags are applied without it. A metadata-only dump can therefore mutate the pool and return success without ever checking ownership. Check ownership under `cs_main` together with each batch of mutations and return a distinct ownership-loss result. That would let `importmempool` explain why the import stopped and let startup distinguish a load that stopped from one that completed just before the switch; the current post-load ownership sample can leave `loaded` false after a completed load and suppress the shutdown dump. Moving the RPC’s initial chainstate selection under a wider lock alone would not protect the later mutations.

In `test/functional/feature_assumeutxo_dash.py`:
- [SUGGESTION] test/functional/feature_assumeutxo_dash.py:679-689: The completion test can pass even if a background block resets InstantSend’s cached height
  Impact: CI can pass the Dash end-to-end test even if snapshot completion incorrectly delivers its last background block to InstantSend as an active block.
  The old-cycle lock checks signature verification, not the notification behavior claimed by the test. `NetInstantSend::BlockConnected()` would cache the historical height if given the wrong role, but `BuildVerificationBatch()` selects the signing start using the active chain’s actual height, so the expected `processing islock` log can still appear. Keep the old-cycle verification check and add a focused completion test that drains the validation queue and checks that `GetTipHeight()` still reports the snapshot tip.

In `<commit:32933baa29d>`:
- [SUGGESTION] <commit:32933baa29d>:1: The mempool detachment commit leaves file and package admission unguarded until later commits
  Impact: A maintainer bisecting snapshot rejection can land on a revision where a mempool file load can assert and package admission can still operate on a pool that no chainstate owns.
  `32933baa29d` introduces the no-owner state. At that revision, `LoadMempool()` can still call `AcceptToMemoryPool()`, which asserts that the chainstate has a mempool, and `ProcessNewPackage()` takes the node’s pool without checking ownership. The guards added by `0330f63d0fe` and `e5235ca35ac` are also useful when activation transfers ownership, so they can land before detachment. Put the guards first and keep the rejection-specific coverage with the commit that introduces detachment.

@PastaPastaPasta

Copy link
Copy Markdown
Member Author

On the two blocking findings in #8273 (review), both fixed in 64aadc5 (fix(validation): refuse a snapshot that omits a known ChainLock, allow a reindex past one):

  • A higher-work snapshot can replace the active chain with a fork that contradicts a known ChainLock. Whenever ChainLocks are enabled, SnapshotActivationRefusal() now compares the base's ancestor at the best known ChainLocked height with the locked block. A base above the lock that doesn't descend from it is refused at load and at the switch ("the snapshot base's chain omits a ChainLocked block"). Before, a lock that arrived after the competing headers marked nothing on that branch, and HasConflictingChainLock() says nothing for a height above the lock, so both checks passed. There is no test for this yet. It needs a network with ChainLocks enabled (feature_assumeutxo_dash.py) where the competing headers are indexed before the lock.
  • An existing snapshot blocks a reindex that would discard it. The startup refusal of -prune, the legacy indexes and -masternodeblsprivkey now applies only when neither -reindex nor -reindex-chainstate is set, because LoadChainstate() deletes the snapshot chainstate on both paths before it is opened. feature_assumeutxo_refusals.py restarts a third node, which holds an unvalidated snapshot, with -reindex -prune=1 -fastprune -txindex=0, and checks that the node rebuilds without the snapshot.

The four suggestions in the review are still open: the mempool import ownership check, CoinJoin's cached height at the snapshot tip, the completion test's InstantSend height check, and moving the guards ahead of the detachment commit.

Other changes in this push:


🤖 Posted autonomously by Claude (claude-opus-5-5) on behalf of pasta.

@github-actions

Copy link
Copy Markdown

This pull request has conflicts, please rebase.

1 similar comment
@github-actions

Copy link
Copy Markdown

This pull request has conflicts, please rebase.

@PastaPastaPasta
PastaPastaPasta force-pushed the feat/assumeutxo-dash-hardening branch from 608caae to 5109a5d Compare November 28, 2026 07:22
thepastaclaw
thepastaclaw previously approved these changes Nov 28, 2026

@thepastaclaw thepastaclaw 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.

Re-review — Final validation — Phase 2 only (queue backlog)

New on this head: This head adds the ChainLock ancestry refusal and reindex snapshot-discard behavior, plus regression coverage for differing masternode registration numbering. ClangFormat and the main check pass; the review check remains in progress and the skip-condition check is queued.

🟡 5 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

5 finding(s) not shown inline (GitHub refused the PR diff as too large)

🟡 Suggestion: The mempool detachment commit leaves file and package admission unguarded until later commits
Impact: An intermediate stack head can detach mempool ownership while file and package admission still use that pool through the original chainstate.
<commit:32933baa29d>:1

A consumer applying the stack through the detachment commit can reach an unsafe intermediate state: e08880d4e92 changes mempool ownership, while the file-import ownership check arrives in 6657c092b6 and the package-admission check in d3310a6684. Move those guards into the detachment commit, or otherwise make every intermediate stack head safe after ownership is removed.

source: gpt-6.2-astra (phase2-reviewer: general, backport-reviewer, dash-core-commit-history)

🟡 Suggestion: The completion test can pass even if a background block resets InstantSend’s cached height
Impact: The end-to-end test can report successful snapshot completion without detecting that InstantSend retained or later received the wrong tip height.
test/functional/feature_assumeutxo_dash.py:741-751

The completion assertions wait for one chainstate and the txindex, then process a later InstantSend lock, but never directly verify the InstantSend cached tip after the queued snapshot-tip notification and background events settle. The activation path explicitly reseeds that cache because queued notifications can overwrite it, so add an observable cached-height assertion or another height-dependent check that proves the promoted tip remains installed.

source: gpt-6.2-astra (phase2-reviewer: general, backport-reviewer, dash-core-commit-history)

🟡 Suggestion: Single-session CoinJoin can keep waiting for a block after a snapshot has advanced the tip
Impact: A single-session CoinJoin client can wait for additional blocks based on its pre-snapshot height even though snapshot activation has already advanced the active chain.
src/validation.cpp:6851-6863

Snapshot activation does not update the CoinJoin client's cached height. CCoinJoinClientManager only overrides UpdatedBlockTip, while the snapshot callback reaches the validation-interface subscribers without invoking the wallet manager's UpdatedBlockTip; consequently nCachedBlockHeight remains stale until a later block event. Include CoinJoin in the snapshot-tip initialization path or update its wait state when the snapshot tip becomes active.

source: gpt-6.2-astra (phase2-reviewer: general, dash-core-commit-history)

🟡 Suggestion: A mempool file import can still change the pool after its chainstate loses ownership
Impact: A concurrent snapshot activation or rejection can leave fee-priority or unbroadcast state modified in a mempool that the importing chainstate no longer owns.
src/node/mempool_persist.cpp:88-99

The importer mutates pool with PrioritiseTransaction before checking ownership at line 95, and expired entries skip that ownership check entirely. After the transaction loop, the mapDeltas and unbroadcast sections also mutate the pool without confirming that active_chainstate still owns it. Check ownership before every pool mutation, or stop processing the file as soon as ownership changes and avoid applying the remaining metadata.

source: gpt-6.2-astra (phase2-reviewer: general, backport-reviewer, dash-core-commit-history)

🟡 Suggestion: The ChainLock-omission refusal has no regression test for headers learned before the lock
Impact: A future change can reintroduce acceptance of a higher-work snapshot fork that omits a known ChainLocked block without a test detecting the consensus-safety regression.
src/validation.cpp:6930-6934

The new branch handles the ordering where competing headers are indexed first and the ChainLock arrives afterward, but the current AssumeUTXO tests do not construct that state. Add a ChainLocks-enabled test that indexes the competing branch before delivering the lock, then verifies refusal both while loading the snapshot and when attempting the activation switch.

source: gpt-6.2-astra (phase2-reviewer: general)

Review provenance

Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: backport-reviewer); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: dash-core-commit-history); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — This is a large, intricate change that modifies consensus validation and chainstate/snapshot storage behavior in files such as src/validation.cpp, src/node/chainstate.cpp, and src/evo/snapshot_chain.cpp, as well as peer-facing ChainLock and InstantSend processing.
  • Phase 1 reviewers: not run (skipped for throughput: 14 PRs queued, above the 10 limit)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — backport-reviewer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — dash-core-commit-history (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `<commit:32933baa29d>`:
- [SUGGESTION] <commit:32933baa29d>:1: The mempool detachment commit leaves file and package admission unguarded until later commits
  Impact: An intermediate stack head can detach mempool ownership while file and package admission still use that pool through the original chainstate.
  A consumer applying the stack through the detachment commit can reach an unsafe intermediate state: `e08880d4e92` changes mempool ownership, while the file-import ownership check arrives in `6657c092b6` and the package-admission check in `d3310a6684`. Move those guards into the detachment commit, or otherwise make every intermediate stack head safe after ownership is removed.

In `test/functional/feature_assumeutxo_dash.py`:
- [SUGGESTION] test/functional/feature_assumeutxo_dash.py:741-751: The completion test can pass even if a background block resets InstantSend’s cached height
  Impact: The end-to-end test can report successful snapshot completion without detecting that InstantSend retained or later received the wrong tip height.
  The completion assertions wait for one chainstate and the txindex, then process a later InstantSend lock, but never directly verify the InstantSend cached tip after the queued snapshot-tip notification and background events settle. The activation path explicitly reseeds that cache because queued notifications can overwrite it, so add an observable cached-height assertion or another height-dependent check that proves the promoted tip remains installed.

In `src/validation.cpp`:
- [SUGGESTION] src/validation.cpp:6851-6863: Single-session CoinJoin can keep waiting for a block after a snapshot has advanced the tip
  Impact: A single-session CoinJoin client can wait for additional blocks based on its pre-snapshot height even though snapshot activation has already advanced the active chain.
  Snapshot activation does not update the CoinJoin client's cached height. `CCoinJoinClientManager` only overrides `UpdatedBlockTip`, while the snapshot callback reaches the validation-interface subscribers without invoking the wallet manager's `UpdatedBlockTip`; consequently `nCachedBlockHeight` remains stale until a later block event. Include CoinJoin in the snapshot-tip initialization path or update its wait state when the snapshot tip becomes active.
- [SUGGESTION] src/validation.cpp:6930-6934: The ChainLock-omission refusal has no regression test for headers learned before the lock
  Impact: A future change can reintroduce acceptance of a higher-work snapshot fork that omits a known ChainLocked block without a test detecting the consensus-safety regression.
  The new branch handles the ordering where competing headers are indexed first and the ChainLock arrives afterward, but the current AssumeUTXO tests do not construct that state. Add a ChainLocks-enabled test that indexes the competing branch before delivering the lock, then verifies refusal both while loading the snapshot and when attempting the activation switch.

In `src/node/mempool_persist.cpp`:
- [SUGGESTION] src/node/mempool_persist.cpp:88-99: A mempool file import can still change the pool after its chainstate loses ownership
  Impact: A concurrent snapshot activation or rejection can leave fee-priority or unbroadcast state modified in a mempool that the importing chainstate no longer owns.
  The importer mutates `pool` with `PrioritiseTransaction` before checking ownership at line 95, and expired entries skip that ownership check entirely. After the transaction loop, the `mapDeltas` and unbroadcast sections also mutate the pool without confirming that `active_chainstate` still owns it. Check ownership before every pool mutation, or stop processing the file as soon as ownership changes and avoid applying the remaining metadata.

@thepastaclaw thepastaclaw added the pastaclaw:approved thepastaclaw's latest review approved this PR label Nov 28, 2026
PastaPastaPasta and others added 29 commits December 4, 2026 07:35
…pshot completion

bc43eca test: add functional test for balance after snapshot completion
226d03d validation: Send correct notification during snapshot completion

Pull request description:

  When background validation completes during an ActivateBestChain() call,
  GetRole() returns NORMAL instead of BACKGROUND for the background chainstate
  when its BlockConnected notifications are sent. The wallet, which ignores
  background notifications, then sets its last processed block to the old
  snapshot height. The role is now captured before ActivateBestChainStep().

Dash adaptations:
- The role is captured right before each ActivateBestChainStep() call inside
  Dash's inner loop, which can run more than one step after a stall.
- The Dash subscribers that ignore background notifications (the ChainLock
  handler and signer, InstantSend, CoinJoin, net_processing) no longer handle
  the blocks of the background chainstate's final step either.
- wallet_assumeutxo.py checks the third node's wallet by its last processed
  block instead of its balance: the test does not fund the wallet, which
  needs bitcoin#29354, and ensure_for() needs bitcoin#30893. The third node
  authorizes the snapshot with -assumeutxodata like node 1. Its snapshot chain
  reaches the tip by submitblock before it connects to node 0: without the
  snapshot-first block download of bitcoin#29519, active blocks arriving after
  completion would set the wallet's last processed block again and hide the
  bug.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
5555d8d test: Use blocks_path where possible
fa91089 rpc: Fix race in loadtxoutset

Pull request description:

  The tip may have advanced, also if it did not, there is no reason to
  have two variables point to the same block.

  Fixes bitcoin#27596 (comment)

The test framework part of 5555d8d (has_blockfile using blocks_path)
is already on develop via dashpay#8280 (partial bitcoin#29262); this
commit carries the remaining loadtxoutset fix from fa91089, which
needs the loadtxoutset RPC from bitcoin#27596.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…check in ActivateSnapshot

33c48c1 validation: Check if mempool exists before asserting in ActivateSnapshot (TheCharlatan)

Pull request description:

  The mempool is an optional component of the chainstate manager, so don't assume its presence and instead check if it is there first.

Dash: pulled forward from the later assumeutxo backports. After a
snapshot rejection the active chainstate has no mempool (next commit),
so a second activation in the same run must reach the "a snapshot
chainstate already exists" refusal instead of this assert.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A snapshot chainstate's Evo state is its own directory here, not a marker in the shared EvoDB, so startup reports a bogus chainstate_snapshot directory as a missing Evo state. Startup now also logs the base block it lacks the Evo state for, which the test matches.
…ock before validation

A snapshot chainstate that has not been validated in the background
cannot fully check the blocks it would reconnect after invalidating one,
and undoing a block can need Evo state it does not have yet. An
InstantSend lock that conflicts with a block on it therefore no longer
invalidates the block: the chain wins, as it does against a ChainLocked
conflict, and the lock is discarded. That is the only difference from
the ChainLock rule of dashpay#8199, which removes a lock only for a
ChainLocked conflict: here the conflicting block is not ChainLocked, and
the lock goes because the chainstate cannot act on it yet. The rule
applies only while the active chainstate is a snapshot chainstate that
background validation has not completed
(IsSnapshotActiveAndUnvalidated); afterwards such a lock invalidates the
conflicting blocks as before. The check comes before the ChainLock rule,
so a lock whose conflict is ChainLocked is discarded the same way rather
than announced, relayed and served after its removal.

A discarded lock is removed from the database, archived so it is not
requested again, and, when it still waits for its transaction, removed
from the pending entries, so GetInstantSendLockByHash no longer serves
it. ResolveBlockConflicts returns false then, and ProcessInstantSendLock
stops before removing mempool conflicts, notifying the lock and relaying
it.

Without a snapshot, a pruned node that cannot undo a conflicting block
because block data it needs was pruned stalls instead of asserting:
InstantSend logs it, keeps the lock and gives up on that lock's
conflicts. It clears the failure flags of an invalidation that was only
temporary (a lock without its transaction) on every exit, also when the
invalidation stopped partway, so no block it disconnected keeps a
failure flag. A node that cannot read a block is shutting down, and
ResolveBlockConflicts returns false.

discarded_lock_is_not_served covers a stored lock and one that waits
for its transaction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ith legacy indexes

A pruned node keeps neither the blocks the background chainstate needs nor
those Evo state below the snapshot base is read from, a masternode cannot run
its duties from an unvalidated snapshot chainstate, and the -addressindex,
-spentindex and -timestampindex indexes are not supported together with a
snapshot chainstate.

Snapshot activation now refuses all of these, in any prune mode, together with
the conditions the switch already re-checked: a non-empty mempool, a base
without more work than the active tip, and an invalid or ChainLock-conflicting
block in the base's chain. They are checked when the snapshot is loaded, before
any state is set up, and again at the switch. The load check also refuses a second snapshot after one was rejected
in this run, which used to reach the switch and abort on
assert(!m_snapshot_chainstate), and a snapshot while the chainstate of one
rejected earlier is still in chainstate_snapshot_INVALID. A rejection moves
the snapshot chainstate there and tells the user it is kept, but a second
rejection could not move its own there, and startup recovery then deleted it.

At startup, a node with a snapshot chainstate directory, validated or not,
refuses to start with -prune, one of those indexes or -masternodeblsprivkey
until a restart has promoted the snapshot. -assumeutxodata is refused off
regtest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Adapted to per-chainstate Evo state: the switch check runs in ActivateSnapshot() before the snapshot chainstate takes over. The unit scenario chainstatemanager_evo_snapshot_refused_when_loaded relies on test hooks this tree does not have and is not taken; feature_assumeutxo_refusals.py covers the refusals.
This reverts commit 8010353. A masternode refuses to start with a snapshot chainstate until a restart has promoted it, and snapshot activation refuses a masternode, so DKG participation and quorum signing never run beside an unvalidated snapshot: the production gate, its RPC error and the masternode status field are dead code.
…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.
…s first

Startup starts the index threads after the block import. The import
activates the best chain of every chainstate, so it completes background
validation of a snapshot whose remaining blocks it reads, from -loadblock or
from blocks stored before a restart. The completion then rebinds the
indexes to the snapshot chainstate and starts their threads, and startup
starts them again: assigning to a still joinable m_thread_sync calls
std::terminate. Bitcoin Core has the same order, but only with an index
opted in. Dash enables txindex by default and always keeps the governance
collateral index in node.indexes.

Startup and the completion now start the threads under index_start_mutex.
Until startup has started them, the completion only rebinds the indexes,
and startup starts them on the chainstate they are bound to. The mutex also
orders a completion in the message handler against startup starting the
threads.

feature_assumeutxo.py has node 3 load the snapshot with only the headers and
restart with the blocks below the base in a -loadblock file. Without the fix
the node aborts during startup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Snapshot activation moves the active tip without a block connection, and
told only the deterministic masternode list about it. The other Dash
consumers of the tip learned of it from the next block the snapshot
chainstate connected. A snapshot loaded at the best header may have none to
connect for a while: CMasternodeSync never saw the node reach the best
header and kept masternode sync in its blockchain stage, and InstantSend
kept the tip height it cached before the load, by which it picks the
signing cycle of rotating quorums.

The snapshot base may have only its header, so activation must not raise
UpdatedBlockTip: ZMQ's raw block notifier would fail to read the block and
drop itself for the rest of the run, and block relay would announce a block
it cannot serve. Bitcoin's activation raises no tip event either.

Activation now seeds the InstantSend tip height and the MN list tip
directly under cs_main, and queues InitializeSnapshotTip, a variant of the
startup fan-out InitializeCurrentBlockTip that reaches the masternode sync,
governance, DSTX and quorum observer state but not ZMQ, block relay or
wallets. It is ordered before the events of any later block, and is skipped once such a block has moved the tip, since
that block's own events reach the same consumers. A block can still connect
between that check and the fan-out and set the MN list tip synchronously, so
the fan-out must not set it again: CDSNotificationInterface answers
InitializeSnapshotTip with its queued tip consumers only, where
InitializeCurrentBlockTip would also put the base back as the MN list tip.
The other subscribers hold only state that block connection sets from the
queue, after this fan-out, and answer it as InitializeCurrentBlockTip.

The previous chainstate keeps connecting blocks while the snapshot is
prepared, and a BlockConnected of one of them may still be queued at the
switch. NetInstantSend would then put its tip height back below the base, and
it does not answer the fan-out, so the fan-out sets that height again under
cs_main, right after its check of the active tip.

feature_assumeutxo.py checks that masternode sync leaves the blockchain
stage once node 2, with a peer and no block to connect, has loaded the
snapshot at its best header, and that node 2's raw block notifier survives
the load at a headers-only base and publishes the next tip. Without the
fan-out masternode sync stays in its blockchain stage; with an
UpdatedBlockTip at activation the notifier is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…services

The DS notification interface, the InstantSend and quorum net handlers, governance, the CoinJoin client, the connection threads and the masternode maintenance task took the Evo managers of the chainstate that was active when they were constructed. Loading a snapshot at runtime makes another chainstate active, with its own managers: these services kept reading the background chainstate's, which stops at the snapshot base. The masternode list tip in particular was moved on the background chainstate's manager, so the list at the tip of the snapshot chain stayed at the block the snapshot was activated on, and InstantSend locks were verified against quorums the background chainstate has not derived.

They now hold the ChainstateManager and read ActiveEvo() per call, as PeerManager does; CConnman, which does not know validation, takes a callback returning the list at the tip. The masternode and quorum-watching contexts keep their references, as such a node never has a second chainstate: a masternode already refused a snapshot at startup and in loadtxoutset, and a node with -watchquorums now does too.

feature_assumeutxo_refusals.py checks the -watchquorums refusals. The end-to-end test added later, feature_assumeutxo_dash.py, checks the list at the tip after blocks connected on a snapshot loaded without a restart.
…he switch under one cs_main hold

ActivateSnapshot() released cs_main between the final refusal checks and
publishing the snapshot chainstate. In that gap the active chainstate could
connect the base or pass it, and a transaction could enter the mempool
against the old tip, spending a coin the snapshot already has spent. The
switch then made an older tip active, or carried an invalid entry into the
snapshot chainstate's mempool.

Hold cs_main from the final SnapshotActivationRefusal() check through
writing the base marker and publishing the chainstate, as upstream does
since 62ac519, and write the marker only after the checks pass, so a
refused snapshot never leaves one behind. A marker write that throws is
cleaned up as a refused load.

The snapshot chainstate's MN list tip and the InstantSend tip height are
now seeded before SetActiveChainstate() publishes the new Evo state, so a
reader of the active Evo state never sees a tip MN list that is still
empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s to

The startup thread reads the active tip and then notifies it, without
holding cs_main between the two. RPC warmup can end before that thread
does, so a loadtxoutset in the gap activates a snapshot and seeds the
snapshot Evo state's masternode list tip at its base. The notification
then resolved the Evo state per call and moved the snapshot's list tip
back to the old tip, whose list the snapshot need not carry. Startup's
GetListAtChainTip() could then throw BlockDataUnavailableError out of
the thread and terminate the node.

Under one cs_main hold, update the list tip only if the notified tip is
still the active one. A snapshot activated in between keeps the tip that
its activation seeded. The rest of the startup fan-out runs without the
lock, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…briefly

The lock is stored, or parked waiting for its transaction, before the
conflict check removes it, so a peer that asks for it in that interval can
still be sent it. Say so in the comment and the release note instead of
promising that it is never served.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… when a later one stalls

When an InstantSend lock conflicts with several blocks, ResolveBlockConflicts
invalidates them one by one and then calls ActivateBestChain. If a later
invalidation stopped on a local Evo state error (a pruned node that lacks
the data to undo a block), it returned before that call. The blocks
invalidated before it had already moved the tip back, and the tip stayed
there until the next block arrived.

Stop the loop at the stall, run ActivateBestChain for the conflicts
already invalidated, and then give up as before. A failure that is not a
local Evo state error still gives up at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hainstate

While a snapshot is validated in the background, the governance collateral
index, like every index, follows the background chainstate, and reports
itself synced once it reaches that chainstate's tip. Governance read that as
"every block up to the active tip has been read": it stopped holding
governance announcements back and processed proposals whose collateral lies
above the background tip, which the index cannot have yet. The lookup failed
as "Can't find collateral tx", and the honest peer that relayed each such
proposal got Misbehaving(20). This happened both after loading a snapshot and
after a restart while it was not yet validated.

GovCollateralIndex now records the chainstate it was initialized on, in
CustomInit(), within the same cs_main hold in which BaseIndex::Init() sets
m_synced, and IsCollateralSynced() also requires that chainstate to be the
active one. Governance therefore waits until background validation has
completed and the index, restarted on the active chainstate, has caught up.
With a single chainstate, and after a rejection, nothing changes. A cached
flag would not do, as the active chainstate changes at runtime activation,
which the index does not observe. CanSync() still decides at startup on the
indexing chainstate.

IsCollateralSynced() takes cs_main itself. Each caller either holds cs_main
already, so the acquisition is recursive and records no lock-order pair (the
collateral check, AlreadyHave(), the INV loop, CheckPostponedObjects(),
governance message processing), or holds no lock that is taken after cs_main
elsewhere (the sync manager's tick, the release of held announcements in
SendMessages(), the RPCs).

While the index is behind, CheckPostponedObjects() leaves postponed proposals
alone, since a failed lookup would drop them. The new functional test cannot
reach this, as mnsync stays at its governance step while the index is behind;
it was verified from the source. gobject prepare and gobject submit refuse
with RPC_MISC_ERROR instead of failing on the lookup. So do the GUI's
proposal creation, before the wallet commits the collateral fee, and its
submission.

Snapshot activation can leave the index behind after ProcessMessage() checked
it. The object handler checks again in the cs_main hold in which it consumes
the request authorization and processes the object, and when the index is
behind it drops the object without consuming the authorization or penalizing
the sender. Votes need no such check: processing one never looks up proposal
collateral.

feature_assumeutxo_refusals.py has a peer that serves no blocks announce a
valid proposal whose collateral is above the background tip: the node holds
the announcement without penalty, and gobject submit refuses. Once background
validation completes and the index catches up, the node requests the proposal
from that peer and accepts it. The test framework's
CGovernanceObject.serialize() is fixed, and msg_govobj added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two activations could run at once: the snapshot chainstate is only installed
at the end, so the check for an existing one let a second loadtxoutset through.
The second one failed, at the latest on the first one's database lock, and its
cleanup then rebalanced the caches, deleted the snapshot directory and
abandoned the generation of the activation still running.

ActivateSnapshot now refuses, before it changes anything, while another
activation is running.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

The unit scenario relies on test hooks this tree does not have and is not taken.
Promotion renames the background chainstate directory to chainstate_todelete
and deletes it at the end. When that deletion failed, or the node stopped
before it, the directory stays; the next startup removes it, unless it
reindexes. A snapshot loaded after such a reindex then failed its promotion
on the rename, and startup aborted until the user removed the directory.

The leftover is of no use, so promotion removes it durably before the rename.
A failure to remove it aborts the node with its own message, as a failed
rename does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A rejected snapshot handed its mempool to the validated chainstate. The
mempool's transactions were accepted against the snapshot tip, so with
-checkmempool (the regtest default) the check that follows completion
aborted on a child of a transaction mined above the base, instead of
the node stopping with its error. After a rejection raised while the
snapshot chainstate connects a block, the validated chainstate can be
far below the base, and it met that mempool with historical blocks.

Leaving the mempool with the rejected chainstate is not enough: a
rejection raised mid-step returns through that chainstate's mempool
update after its coins views were reset.

Detach the mempool from both chainstates for the rest of the run.
Transactions are refused with no-mempool. Nothing is removed, so no
InstantSend lock is dropped through the removal notification, and
DumpMempool still saves the mempool for the next startup to
re-validate.

This drops the handback of the mempool on rejection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…onger holds the mempool

A snapshot rejection detaches the mempool from both chainstates, and a
snapshot activation moves it from the background chainstate to the
snapshot one. A mempool load (importmempool, or the load at startup)
that started on the other chainstate, or after the rejection, then
reached AcceptToMemoryPool's assertion that the chainstate has a
mempool. Stop the load instead. bitcoin/master has the same gap after a
rejection.

If the mempool moved to another chainstate while the startup load ran,
the load is not marked as tried. The shutdown dump then keeps mempool.dat
instead of overwriting it with a partial pool, and savemempool refuses
until the next start, which loads the file again. The startup load reads the
active chainstate and its mempool in one cs_main hold, as activation and
rejection change them under it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
feature_assumeutxo_dash.py checked only the evo section dumptxoutset writes.
Extend it so that three cold nodes, which know only the headers, load node 0's
dumps at bases 3, 23 and 18 blocks into a rotation cycle (the last inside the
mining window), with the regtest default -checkblockindex:

- node X refuses a mutated coin, a mutated evo section, and a pin with either
  hash of another dump. -reindex and then -reindex-chainstate drop snapshots
  whose chains connected blocks above the base, and plain IBD follows.
- node R loads a section that adds an EHF signal, under a pin taken from that
  section. Background validation over P2P rejects it at completion: the node
  stops, keeps chainstate_snapshot_INVALID, misbehaves no peer and marks no
  block invalid. After the restart it refuses another snapshot while the
  rejected one is kept, then syncs from blocks. R's mempool holds a child of
  a transaction mined at base+1, valid only on the snapshot chain: node 0
  takes the parent's InstantSend lock before mine_quorum mines it and keeps
  its output locked (lockunspent) for R. Completion must still stop the node
  cleanly with that child in the mempool.
- node A takes a transaction spending snapshot coins into its mempool with an
  InstantSend lock from a carried quorum, and connects InstantSend,
  withdrawal and EHF traffic above the base. A carried platform quorum
  verifies the withdrawal's signature. Before background validation
  completes, an InstantSend lock keeps a block A mined with a conflicting
  spend; A follows the locked spend once its chain has more work. With
  the background chainstate just past blocks before v19, a basic-scheme ChainLock is accepted with no
  misbehaviour. An EHF signal of a quorum the snapshot does not carry stalls
  the snapshot chain, also across a restart; background validation still
  completes in the same run, and an InstantSend lock two cycles old verifies
  after completion (bitcoin#31556). A masternode key is refused while the
  snapshot is unpromoted, and the restart that promotes it connects the
  stalled block.

The network adds two EvoNodes for platform quorums and activates v19 at
height 60, so a background chainstate can be before v19 while the snapshot
chain is after it.

The test now takes about 100 s, so test_runner.py lists it first among the
base tests under five minutes.

At this commit the dual-chainstate scenario of feature_assumeutxo_dash.py
does not pass yet: it relies on the Evo history refusals and the stall
bookkeeping that later commits of this PR add, and the test passes at the
top of the PR.
…old the mempool

testmempoolaccept and submitpackage picked the active chainstate before
taking cs_main, and ProcessNewPackage() paired that chainstate's coins with
the node's mempool without checking that the chainstate holds it. A snapshot
activation in between had a package checked against the background
chainstate's coins and admitted to the mempool the snapshot chainstate now
holds. After a snapshot rejection, which detaches the mempool from both
chainstates, packages were still admitted, while ProcessTransaction()
refuses single transactions with no-mempool.

ProcessNewPackage() now refuses with PCKG_MEMPOOL_ERROR "no-mempool" when
the chainstate does not hold the pool, and both RPCs pick the active
chainstate in the cs_main hold of the admission.

The unit tests check the refusal through the background chainstate after an
activation, and through either chainstate after a rejection. Without the
fix the first is judged on the background coins, the second on the
validated chainstate's coins, and the third reads the rejected chainstate's
reset coins views.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…w a reindex past one

A snapshot base above the best ChainLocked block this node knows has to
descend from it. When the competing headers arrived before the lock, the
lock stops enforcement at the locked block without marking the competing
branch, and HasConflictingChainLock() says nothing about a height above
the lock, so a higher-work fork that omits the locked block passed both
checks at load and at the switch. Compare the base's ancestor at the
locked height with the locked block.

The startup refusal of -prune, the legacy indexes and
-masternodeblsprivkey while a snapshot chainstate exists also refused a
-reindex or -reindex-chainstate that would discard the snapshot before
it is opened. Skip the refusal on those paths; a test restarts a node
with an unvalidated snapshot with -reindex -prune=1 and checks it
rebuilds without the snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Before the first dump, mine a block that registers a masternode and spends
its collateral, then restart node 0. No list diff records that masternode,
so node 0 rebuilds its tip list with a registration counter one lower than
the other nodes keep, and would number later registrations differently.
Its dumps must still match node 1's, node A must still complete background
validation, and after the promotion node A's masternode lists on both
sides of the base must match node 0's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…validation completes

While an assumeutxo snapshot chainstate is active and not yet validated,
Evo and LLMQ state at or below the snapshot base is either carried by the
snapshot or missing, and block bodies below the base are not on disk.
RPCs reading that history failed deep inside with BlockDataUnavailableError,
surfacing as RPC_INTERNAL_ERROR, and getdeploymentinfo answered for the base
and its ancestors from the unvalidated carried MNHF signals.

Add EnsureEvoHistoryAvailable(), which refuses with RPC_MISC_ERROR "... is
unavailable until assumeutxo background validation completes", and use it:

- whole RPCs: getquorumproofchain, quorum rotationinfo, quorum getdata,
  quorum verify, verifychainlock, protx diff, protx listdiff, masternode
  payments, getchainlockbyheight, getcreditpoolinfo and dumptxoutset
  (verifyquorumproofchain reads no node state and is kept);
- historical arguments only, so the tip forms keep working: protx list
  with a height and protx info with a block hash at or below the base;
  quorum list and memberof with a count beyond the active quorums, quorum
  listextended at or below the base and quorum info for a quorum outside
  the active set; verifyislock with a height at or below the base; getassetunlockstatuses with a height at or
  below the base; getdeploymentinfo for a block at or below the base,
  dropping the branch that answered from the carried signals; masternode
  winners whose range reaches the base.

GETMNLISTDIFF and GETQUORUMROTATIONINFO are not served in that state: they
are dropped after deserialization, before a request token is taken or a
reply is built, without a misbehavior score.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… around them

Once a snapshot can be loaded, its chainstate meets blocks whose Evo
state needs data it does not have yet (a pre-base masternode-list diff
on its cold EvoDB, a seeded record it lost), and keeps meeting them
until background validation completes and a restart promotes the
snapshot. A local Evo state error then fails the block without marking
it invalid, but nothing remembers it: every ActivateBestChain retries
the same block, a more-work branch through it keeps a usable branch
from advancing, and a disconnect that fails this way aborts the node or,
for ChainLock and InstantSend conflict enforcement, asserts.

The chainstate now remembers the blocks it stalled on (every one: they
are all in the block index) and refuses them at once on later attempts
instead of revalidating them, until the node restarts: a chainstate's Evo
state only changes at a restart. The first stall is logged as an error.
Without a snapshot, on a node that pruned, Evo state is missing only
because the block data it is derived from was pruned, and the log says
so and suggests -reindex. Completing snapshot validation does not make
the background chainstate's state readable to the snapshot chainstate
before the next startup promotes it, so a stall outlives completion
until that restart.

Candidate selection passes over the branches that need a stalled block
connected (or disconnected), so a usable branch with less work still
advances the chain; ActivateBestChain reports the stall when only it
keeps a chain with more work out of reach. A stalled block found
invalid or conflicting with a ChainLock since obstructs nothing: it is
forgotten, and a branch through it is removed like any unusable one.

Callers that treated any failure as fatal no longer abort on a stall:
ActivateBestChain announces the blocks it connected before stopping,
ActivateBestChainStep returns the disconnected transactions to the
mempool without FatalError, block import continues with the other
chainstates and the rest of startup, LoadExternalBlockFile keeps
importing for the other chainstates, and ChainLock enforcement retries
on its next run. InvalidateBlock refuses, before it disconnects a block
or sets a failure flag, an invalidation that has to disconnect a block
the chainstate already stalled on. A stall partway through a rewind
keeps the blocks already disconnected and announces the tip reached:
InvalidateBlock and ChainLock conflict marking finish and announce what
they disconnected, and ActivateBestChain never releases cs_main with the
chain rewound below the candidates it passed: it lists them again, as
InvalidateBlock does, and selects again with the stall remembered, so it
normally reconnects the chain it started from before it reports the
stall. A block whose disconnect stalls stays in the chain, so the best
header (and best invalid block) adjusted for it are restored. A pruned
block set aside while a stalled branch is listed again is linked once
when its body arrives.

The unit cases come with the snapshot chainstate tests later in this
PR; feature_assumeutxo_dash.py covers a stall across a restart and its
recovery after promotion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal masternode ids are local to a node's history, and a snapshot numbers masternodes by the rank of their proTxHash. AdoptNumbering(), which landed with dashpay#7593, gives the promoted snapshot's lists and diffs the numbering of the list the background chainstate derived at the base.

chainstatemanager_evo_snapshot_cold_load checks that the snapshot chainstate numbers the masternodes differently from the chain the snapshot was dumped from, and that the promoted lists at and above the base carry that chain's ids.

Co-authored-by: pasta <[email protected]>
…shot chainstate

The unit tests of the evo section stopped at its encoding. These cover what a section must carry and what is refused (planned quarters, modifiers and bootstrap sets, the credit window, the base coinbase and its ChainLock, the MNHF record, scan coverage), what a snapshot chainstate answers below its base (unavailable, never absent or guessed), every field only the completion rebuild can catch, local failures at completion, and stalls on state the snapshot does not carry.

The scenarios are pasta's, from the stack this one replaces, moved onto fixtures that seed a chainstate's own Evo state.

Co-authored-by: pasta <[email protected]>
… node

feature_assumeutxo_dash.py compared the importer's masternode lists and quorums with its own other answers only. Compare them with a fully synced node at four points of the snapshot's life (above the base, with the background part-way, validated but unpromoted, and promoted), and let the promoted node rejoin the network: it verifies a lock signed after the load and mines a block the network ChainLocks.

@thepastaclaw thepastaclaw 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.

Re-review — Final validation — Phase 2 only (queue backlog)

New on this head: This head restacks the Dash AssumeUTXO loader, refusal, and recovery changes on #8078. Since the last review, the inherited layer has added a startup guard for the deterministic masternode tip, clarified when discarded InstantSend locks can still be served, and restored best-chain selection after a partial InstantSend conflict rewind. All reported build, test, and lint checks passed, including multiprocess, TSan, no-wallet, and ASan; only the review check is pending.

🟡 5 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

2 finding(s) not shown inline (the lines are not part of this PR's diff)

🟡 Suggestion: Withdrawal status reports a ChainLocked withdrawal as only mined at the snapshot base
Impact: A caller querying a withdrawal covered by the coinbase ChainLock can get mined on a headers-only snapshot node that has not separately received that lock.
src/rpc/rawtransaction.cpp:851-875

The no-height query can understate finality immediately after a snapshot load. With no standalone best ChainLock and no base block body, GetNonNullCoinbaseChainlock() returns nothing: it reads the body from disk and never consults the base coinbase carried in EvoDB. The RPC then finds the withdrawal in the carried tip pool and returns mined. Use the active chainstate's snapshot-aware GetCoinbaseChainlock() fallback, and return the standard history-unavailable error if the resulting lock height needs pool history the snapshot does not carry.

source: gpt-6.2-sol (phase2-reviewer: general)

🟡 Suggestion: A mempool file import can still change the pool after its chainstate loses ownership
Impact: If snapshot activation or rejection changes mempool ownership during a file load, the importer can still apply fee priorities or rebroadcast metadata after the transition.
src/node/mempool_persist.cpp:88-136

An import can change the pool even when it returns an ownership error, or report success if only the metadata tail remains. The ownership check under cs_main protects AcceptToMemoryPool(), but the per-transaction fee adjustment happens before that check, and the trailing fee-delta and unbroadcast loops never check ownership. The startup loader enables both metadata imports by default. Deserialize outside cs_main, then check ownership and apply each batch of mutations under the same lock hold.

source: gpt-6.2-sol (phase2-reviewer: general)

Still open from earlier rounds (3)

  • 🟡 Suggestion: The mempool detachment commit leaves file and package admission unguarded until later commits — src/validation.cpp:7223-7229 (thread)
  • 🟡 Suggestion: The ChainLock-omission refusal has no regression test for headers learned before the lock — src/validation.cpp:6791-6798 (thread)
  • 🟡 Suggestion: The completion test can pass even if a background block resets InstantSend’s cached height — test/functional/feature_assumeutxo_dash.py:841-861 (thread)
Review provenance

Source: reviewer 1: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: dash-core-commit-history); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The new changes in src/validation.cpp are intricate, but they alter local chain selection when Evo state is unavailable and harden snapshot activation, rejection, and promotion without changing consensus rules or migrating the storage format.
  • Phase 1 reviewers: not run (skipped for throughput: 16 PRs queued, above the 10 limit)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — dash-core-commit-history (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `src/rpc/rawtransaction.cpp`:
- [SUGGESTION] src/rpc/rawtransaction.cpp:851-875: Withdrawal status reports a ChainLocked withdrawal as only mined at the snapshot base
  Impact: A caller querying a withdrawal covered by the coinbase ChainLock can get `mined` on a headers-only snapshot node that has not separately received that lock.
  The no-height query can understate finality immediately after a snapshot load. With no standalone best ChainLock and no base block body, `GetNonNullCoinbaseChainlock()` returns nothing: it reads the body from disk and never consults the base coinbase carried in EvoDB. The RPC then finds the withdrawal in the carried tip pool and returns `mined`. Use the active chainstate's snapshot-aware `GetCoinbaseChainlock()` fallback, and return the standard history-unavailable error if the resulting lock height needs pool history the snapshot does not carry.

In `src/node/mempool_persist.cpp`:
- [SUGGESTION] src/node/mempool_persist.cpp:88-136: A mempool file import can still change the pool after its chainstate loses ownership
  Impact: If snapshot activation or rejection changes mempool ownership during a file load, the importer can still apply fee priorities or rebroadcast metadata after the transition.
  An import can change the pool even when it returns an ownership error, or report success if only the metadata tail remains. The ownership check under `cs_main` protects `AcceptToMemoryPool()`, but the per-transaction fee adjustment happens before that check, and the trailing fee-delta and unbroadcast loops never check ownership. The startup loader enables both metadata imports by default. Deserialize outside `cs_main`, then check ownership and apply each batch of mutations under the same lock hold.

In `src/validation.cpp`:
- [SUGGESTION] src/validation.cpp:7223-7229: The mempool detachment commit leaves file and package admission unguarded until later commits
  (carried; thread: https://github.com/dashpay/dash/pull/8273#discussion_r4733280824)
- [SUGGESTION] src/validation.cpp:6791-6798: The ChainLock-omission refusal has no regression test for headers learned before the lock
  (carried; thread: https://github.com/dashpay/dash/pull/8273#discussion_r4729952016)

In `test/functional/feature_assumeutxo_dash.py`:
- [SUGGESTION] test/functional/feature_assumeutxo_dash.py:841-861: The completion test can pass even if a background block resets InstantSend’s cached height
  (carried; thread: https://github.com/dashpay/dash/pull/8273#discussion_r4729378611)
Out-of-scope follow-up suggestions (2)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Startup can still notify Dash tip consumers with the pre-snapshot tip — In #8078's startup path, initload captures the tip before the synchronous fan-out. If activation and its queued notification run first, the new check skips the deterministic masternode update but CDSNotificationInterface can still pass the old tip to masternode sync and governance. This is a direct call to those consumers, not a broadcast to CoinJoin or all validation subscribers.
    • Follow-up: Handle stale startup notifications in #8078, which owns both the startup guard and the snapshot-tip notification path.
  • Single-session CoinJoin does not receive the snapshot-tip advance — The CoinJoin wallet manager still updates its cached height only through UpdatedBlockTip, which snapshot activation deliberately does not emit. A wallet already waiting for its next block can therefore keep waiting when the snapshot advances the active tip but no subsequent block connects.
    • Follow-up: Address this in the snapshot-tip fan-out in #8078 or a follow-up to that PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pastaclaw:approved thepastaclaw's latest review approved this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants