Provider refusals
write_verifier: Provider declined the request because of a cybersecurity restriction. Experiments remain incomplete; static verification can continue.
2 major findings · 2 minor findings · 11 suggestions
Findings
[major] · An uncollected FRESH spend can move replay past an unwritten coin
With no node caller yet, spending an uncollected FRESH coin during streaming can let the persisted replay boundary pass its unwritten creation, leaving the coin missing after crash recovery.
Location: src/coinsstore.cpp:930 (head).
Details and suggested fix
Suppose the database is settled at W, and coin x was created at h, where W < h <= bound. A run fixes new_head at N. While an earlier chunk is being written, block N+1 spends x before collection reaches its shard. SpendEntryAt() erases the still-FRESH entry outright. Only collection clears FRESH, so nothing preserves the run's obligation to write x. The remaining dirty entries can then place settled_height at S >= h, and the last write changes the marker to (N, S). A crash before a later run records the spend leaves replay starting above x's creation. Recovery accepts N without restoring x, and reconnecting its spender fails on a missing input; rebuilding with -reindex-chainstate repairs this.
Prevent commits above new_head until collection finishes and enforce that ordering, or preserve the affected entries' run-head values. Add a one-change-chunk test that spends a FRESH coin in an uncollected shard and recovers from the advanced persisted heads.
[major] · Restored-coin erases from above new_head can enter the run
With no node caller yet, a post-new_head spend of an uncollected restored coin can enter the earlier run, deleting a coin that replay cannot recreate after a crash.
Location: src/coinsstore.cpp:836 (head).
Details and suggested fix
Let the written head be W. A disconnect toward a fork F >= W restores x, a coin created at or below W that the database already holds. TagFor() files that restoration at F. Begin a bounded run with bound >= F and new_head = N, then commit a spend of x in N+1 before its shard is collected. Because the entry is dirty and uncollected, Height::Oldest keeps it filed at F. CollectChunk() therefore writes the current erase under the marker for N, even though x is unspent at N. Replay from either W or the subsequently advanced settled head never reapplies x's creating block. A crash before the next run records N+1 can consequently leave recovery accepting N without x, and reconnecting N+1 fails on a missing input.
Keep the collected value consistent with new_head, or prohibit commits above that head until collection finishes. Cover this restored-coin case with a multi-chunk cut-and-replay test.
[minor] · CoinsStore::Sync() does not override the cache interface
Although no node caller constructs a store yet, Sync() through CCoinsViewCache& skips the shards and passes the unused inherited map and null hash to the database.
Location: src/coinsstore.h:139 (head).
Details and suggested fix
CCoinsViewCache::Sync() is non-virtual, so a base-reference call executes its BatchWrite() on inherited cacheCoins and m_block_hash. The store maintains neither: its SetBestBlock() overrides update only m_tier_block_hash. With a database base, this reaches assert(!block_hash.IsNull()); it does not write the store's dirty shards. FlushStateToDisk() already calls CoinsTip().Sync() through CCoinsViewCache&, making this incompatible with the stated substitution contract. Make Sync() virtual, mark the store implementation override, and test synchronization through a base reference. That also requires replacing CoinsViewOverlay's deleted Sync() with a suitable rejecting override, since a deleted function cannot override a non-deleted virtual.
[minor] · Cursor() can pair a partial run snapshot with the wrong block
With no node write-out caller yet, argument evaluation order can let Cursor() pair a partial coin snapshot with a known best block despite the new guard.
Location: src/kernel/coinstats.cpp:124 (head).
Details and suggested fix
Cursor() supplies NewIterator() and GetBestBlock() as independent constructor arguments. If GetBestBlock() executes first, it can return block B before an off-lock WriteRun() lands its first batch. That batch erases DB_BEST_BLOCK together with coin changes, after which NewIterator() can snapshot the partially written set. The saved hash still resolves to B, so the new null-index guard permits hashing and reporting that partial set as B's UTXO set. gettxoutsetinfo leaves a gap between its forced flush and cursor creation in which a background run could start. Read DB_BEST_BLOCK through the same snapshot as the coin iterator, rather than combining a snapshot with a separate latest-value read.
Optional improvements
[suggestion] · Flush() stages an entire dirty shard outside the batch-size bound
Forced-flush scratch space grows with an entire dirty shard rather than the batch limit; peak RSS and the practical exploitability of deliberately skewing shards have not been measured.
Location: src/coinsstore.cpp:1028 (head).
Details and suggested fix
WipeShard() moves every dirty entry into worker.writes before RunWipeWorker() checks wipe.limit. SortWrites() also reserves an ordering array and a second CoinWrite array for that shard. These capacities remain allocated for the worker's lifetime, while erased nodes remain in the allocator's regions. Moving the scripts therefore does not bound the additional metadata storage. Balanced default shards make this much smaller, but ShardIndex() uses grindable leading txid bytes and enforces no balance. Measure peak RSS with a deliberately skewed shard to determine whether a fallback is needed. A lower-overhead fallback can sort node pointers under the shard lock, then materialize bounded batches in key order while retaining the lock until their writes land. Also correct the comment that grinding affects contention and nothing else.
[suggestion] · The indexed gettxoutsetinfo path treats an open marker as a bug
GetUTXOStats() still reports an internal bug for an open write-run marker on the indexed muhash/none path; no node caller runs write-outs in this revision.
Location: src/kernel/coinstats.cpp:121 (head).
Details and suggested fix
With -coinstatsindex, use_index=true, and no specific block requested, the muhash and none paths evaluate CHECK_NONFATAL(blockman.LookupBlockIndex(view.GetBestBlock())) under cs_main. A non-final run started after the RPC's forced flush can leave DB_BEST_BLOCK absent, which makes this throw NonFatalCheckError. The new ComputeUTXOStats() guard treats the same missing best block as an expected inability to obtain statistics. Return nullopt, or a specific retry error, from the indexed path when the best block is null or unknown instead of reporting an internal bug.
[suggestion] · Prefix recovery skips the advanced settled-head marker
The cut-at-any-write test never recovers after the final settled-head marker lands, so its recovery assertions cannot detect a boundary advanced past an outstanding change.
Location: src/test/coinsstore_tests.cpp:1030 (head).
Details and suggested fix
FailingAtBase throws before forwarding the selected call. Failing the last call therefore leaves the original marker, while run_cut_at(0) lets the advanced marker land but returns before replay. Every recovery case then reapplies the hard-coded range WRITTEN + 1..HEIGHTS, rather than the range recorded in db.GetHeadBlocks(). Include the prefix after all writes have landed, discard the store, and derive recovery from the persisted heads before comparing with the uninterrupted reference. Include an owed erase spanning the settled boundary so that an incorrectly advanced head can leave a detectable discrepancy.
[suggestion] · Restoration prewrites have no reorg recovery coverage
No test exercises KeepWritten() and restoration WriteCoins() together, leaving recovery under the previous marker and subsequent erase propagation untested.
Location: src/coinsstore.cpp:324 (head).
Details and suggested fix
KeepWritten() clears FRESH and queues restored coins for persistence before the next run's marker. WriteCoins() changes neither the marker nor the best block, so recovery must remain correct if a crash leaves the previous heads in place after that preparatory write. Add a reorg test in which creation and spending cancel in the lagging tier, disconnection restores the coin, and the restored payload is prepared and persisted. Cut before and after preparation and at later writes, recover from the stored heads through ReplayBlocks(), and compare with an uninterrupted reference. Finally spend the prepared coin and require its erase to reach the database rather than cancel locally.
[suggestion] · KeepWritten() does not identify who persists run->restored
StreamWriteOut() never submits run->restored; no current caller supplies restored coins, and the API does not explicitly require the owner to persist them before streaming.
Location: src/coinsstore.h:272 (head).
Details and suggested fix
BeginWriteOut() transfers the pending restorations into run->restored, but StreamWriteOut() never reads that field. Meanwhile, KeepWritten() says that the next run writes the coins before its marker, and the payload's comment describes that ordering without naming the writer. The Sync() implementation acknowledges that this write belongs to the caller, but that requirement is absent from the streaming contract. State on BeginWriteOut(), StreamWriteOut() and KeepWritten() that the owner must call CCoinsViewDB::WriteCoins() for the payload before streaming, and must abandon the run rather than continue if preparation fails.
[suggestion] · The open-marker nullopt result has no direct coverage
No test exercises ComputeUTXOStats() with an open write-run marker, so restoring the old assertion would leave its current callers' coverage unchanged.
Location: src/kernel/coinstats.cpp:124 (head).
Details and suggested fix
The utxo_snapshot and utxo_total_supply fuzz callers force-flush before computing statistics and assert the result. Add an in-memory database test with a known indexed block: require successful statistics initially, open a marker with non-final WriteRun(), and require nullopt for each hash type. Then close the run and check successful statistics with the expected head and totals. This directly distinguishes the new behavior from the old Assert(pindex).
[suggestion] · Late flush helpers run while the test store is still alive
The busy-pool test drains queued helpers before destroying CoinsStore, leaving their required early return after store destruction unexercised.
Location: src/test/coinsstore_tests.cpp:672 (head).
Details and suggested fix
The helper lambdas capture this, &wipe and &workers, but late tasks must inspect only their shared claimed state and return. The test already runs them after Flush() returns, yet release.set_value() and pool->Stop() remain inside the store's scope. Keep the pool blocked until that scope ends, then release and drain it. Also assert that helper tasks were queued before destroying the store; the existing two-core guard permits that check.
[suggestion] · The BlockApplyView reset tests never run prefetch workers
Tests verify Release() and reuse only with an unstarted pool, leaving worker calls to derived ReadBase() and the drain-before-reset ordering unexercised.
Location: src/coinsstore.cpp:1299 (head).
Details and suggested fix
ProcessInput() calls virtual ReadBase() on pool workers, where BlockApplyView reads m_keep_base_reads and m_store. Its reset drains those workers before clearing per-block state. Extend the existing Release() and reuse test with a started pool, StartFetching(), and a gated base read. Verify that release waits for the outstanding fetch and that the next block uses the reset keep-base-reads setting. Keep the returned ResetGuard within the view's lifetime so the test follows the supported ownership contract.
[suggestion] · CompactFullAsync()'s termination policy is buried in the store commit
The store commit also makes unexpected compaction exceptions terminate the process, but its message does not explain this independent behavior change.
Location: src/txdb.cpp:305 at 206d4a033b16 (commit) (commit).
Details and suggested fix
In 206d4a033b161339ffce1af44b4e56fe2fef7206, the CoinsStore commit, CompactFullAsync() gains a noexcept lambda and narrows its handler from std::exception to std::runtime_error. Exceptions such as std::bad_alloc and std::logic_error were previously logged by that handler; they now terminate the process. Extract this hunk into a separate commit before or after the store commit, with a message explaining the failure policy. No store code depends on the hunk, so the rearrangement leaves the final tree and dependency order unchanged while making this existing-node behavior easier to assess.
[suggestion] · Prefetch task-count tuning is bundled with the store addition
The existing input-prefetch path changes scheduling independently of CoinsStore, but history cannot isolate that performance change from the large store addition.
Location: src/coins.cpp:414 at 206d4a033b16 (commit) (commit).
Details and suggested fix
206d4a033b161339ffce1af44b4e56fe2fef7206, the CoinsStore commit, changes StartFetching() from one task per worker to min(workers, ceil(inputs/8)) tasks. This affects existing block connections with input fetching enabled and needs no store code. Move the hunk and its existing explanatory paragraph into a separate commit after the primitives commit, 913886ab944c23fb605690129620fb70255a50b4, and before the store commit. That preserves dependencies and the final tree while allowing prefetch performance regressions to be bisected separately.
[suggestion] · CreateLocked() exposes an unreachable conflict result
The second conflict arm represents an impossible case under the held shard lock instead of asserting the precondition already established by ApplyConfirmed().
Location: src/coinsstore.cpp:473 (head).
Details and suggested fix
ApplyConfirmed() rejects a create over an unspent coin when possible_overwrite is false, then calls CreateLocked() without releasing the shard lock. The helper's only false return checks the same condition, so its caller's second conflict-reporting arm cannot run. Make the helper return void and assert inserted || entry.coin.IsSpent() || possible_overwrite. Remove the unreachable conflict arm and update the declaration's comment, preserving an explicit failure if the invariant is violated.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
FRESH is a claim about the backing view, not simply about an entry being newly inserted locally. Historical PR #9107 deliberately made freshness assignment more conservative to prevent future consensus mistakes. Its discussion also stresses retaining the parent's flags when merging a child's coins. PR #9310 added an explicit check against a FRESH child overwriting an unspent parent entry.
The store must preserve the distinction between a creation that can disappear without a database erase and a modification whose spentness still needs propagation. The pinned base specifically explains why re-adding a DIRTY spent coin cannot make it FRESH: a subsequent spend would otherwise discard the deletion owed to the parent. Child merges must preserve that obligation.
Source 1 · Source 2 · Source 3 · Source 4
Avoiding negative database lookups motivated the BIP34-based BIP30 shortcut: the original proposal noted that BIP30 checking reached beneath the cache because negative results were not cached. That shortcut was subsequently corrected because pre-BIP34 coinbases could already encode future heights; BIP34 was not an unconditional, permanent uniqueness guarantee.
Duplicate-output assumptions must remain conditional on consensus enforcement and the recognized chain history. The pinned base checks the known BIP34 activation-chain hash and resumes explicit BIP30 checking at height 1,983,702. The store's coinbase-overwrite permission is therefore compatibility machinery beneath validation, not permission to accept arbitrary duplicate transactions.
Source 1 · Source 2 · Source 3
The historical duplicate coinbases really overwrote earlier outputs. Issue #22596 documents how treating those outputs like ordinary reversible creations produced false database-inconsistency reports during deep backward verification.
Connection and disconnection cannot assume every same-outpoint occurrence has ordinary spend-and-undo semantics. The pinned disconnect path has special handling for the earlier overwritten coinbases, distinct from the later duplicate blocks admitted during connection. Preserving this history matters even though the normal modern chain prevents such overwrites.
Non-atomic chainstate flushing was introduced to avoid the flush-time memory peak of a single atomic LevelDB batch. The blockchain serves as the existing external update journal: a head-pair record identifies an incomplete transition, and startup rolls backward and forward to reconstruct a consistent tip. The historical implementation also changed roll-forward additions to check whether an overwrite actually occurs, allowing valid FRESH cancellation during large recoveries.
WriteRun extends an established recovery mechanism rather than requiring the whole run to be atomic. The important compatibility contract is that every persisted prefix remains recoverable under its recorded heads; individual batches need not represent complete blocks or an intermediate chain tip.
The earlier stack explicitly identifies queue waits under cs_main as a separate deadlock problem from ordinary mutex-order inversion. Its wait rule forbids waiting while holding a lock that queued work may acquire. Work intentionally awaited under cs_main must not block acquiring that lock; a try-lock is different because it does not wait.
This is the existing constraint behind separating I/O from lock-requiring completions and behind making flush ranges claimable by the waiting caller. Queue priority alone cannot satisfy the rule when all pool workers are already blocked on cs_main.
The earlier durability step states that block and undo bytes must be synced before the index records them, including every file written during the run. Its stated motivation is that later concurrent file writers must not allow the index to get ahead of recoverable bytes.
Replay is possible only while the indexed blocks and required undo records are available. FIFO execution of effects and their completions is consequently part of a larger persistence-ordering contract, not by itself proof that recovery data is durable or retained.
Ralph's inferences
ReplayBlocks provides conditional reconstruction, not repair of arbitrary database corruption. For recorded heads (new, old), it disconnects old to the common ancestor using undo, tolerates DISCONNECT_UNCLEAN, then reapplies the new branch with overwrite-aware additions and idempotent spends. It finally flushes the new best block. Missing blocks, unusable undo, or unknown heads can still prevent recovery.
For every prefix of a bounded run, all database values that need correction must lie within what this rollback/roll-forward traversal rewrites, or have been secured by an independently safe preparatory write. Before the first marked batch the previous recoverable state must remain valid; after marking, recovery targets new_head, not the run's height bound. The final best-block record can replace the marker only after all required writes have landed.
A settled head is a lower boundary for future replay, not merely a progress counter. Advancing it past an outstanding change can make that change permanently invisible to recovery. In particular, an old deletion obligation must survive a later recreation or disconnect; the later coin's height cannot erase the earlier obligation.
The bounded-run contract permits writing an owed erase while postponing a recreation above the bound. This avoids leaving an old coin below the next replay boundary. Reorg inverse changes also need special treatment: replay from the settled head will not reproduce arbitrary intermediate disconnect operations. The bound therefore cannot automatically be used as the next old head.
A coin restored by disconnection may never have reached the database: creation and spending could have cancelled entirely in the lagging cache. Recovery must either replay its creating block or already possess the restored coin before moving its replay boundary beyond that creation. A preparatory restoration must also remain safe if a crash leaves the previous marker in place.
This explains the store's explicit KeepWritten/TakeRestored contract: selected restored coins are written before the next run's marker, and their FRESH status is removed because the database may now hold them. A later spend must emit an erase rather than disappear locally. This preparation is additional to ReplayBlocks; ReplayBlocks does not discover such omitted coins automatically.
Undo-backed spending substitutes the coin already used during isolated validation; it does not establish a new freshness fact. The outpoint alone is insufficient to distinguish historical incarnations of a duplicate output, since the transaction's output bytes repeat while creation height and coinbase metadata identify the validated coin.
BlockApplyView preserves spend provenance and maps undo coins to their transaction inputs only when the structures fit. A store miss supplied from undo must still leave a deletion obligation when the backing database may contain the coin. By contrast, a genuinely fresh coin created and spent within the block can cancel. The isolated-commit precondition—that nothing else changes the store between validation and application—is essential to this substitution.
The effects/completion split breaks a wait cycle: a cs_main holder can wait for I/O only if the I/O worker does not need cs_main to finish. Completions may require that lock, so they remain separately applicable by the holder; the worker's completion hook must only try the lock. End-to-end completion ordering additionally requires all completion appliers to share the same serialization lock.
WaitForIO and a drained byte backlog do not mean all state updates have been applied; Idle additionally includes pending completions. Stop drains accepted I/O but leaves completions for the owner. These distinctions preserve ordering without forcing the worker and a lock-holding waiter to wait on each other.
Front submission reduces queue delay but cannot preempt tasks already blocked on cs_main. Claimable flush ranges provide the stronger progress property: the caller takes unclaimed ranges itself and waits only for helpers that have actually claimed work and can finish without cs_main.
The pinned flush starts helpers after the first marker-bearing batch, uses front submission, and lets delayed tasks return when their ranges are already claimed. It retains emptied shards' locks until their writes land so readers cannot observe a coin in neither memory nor the database. On a write failure, later flushing must not close the recovery marker over missing changes.