1 minor finding · 5 suggestions
Findings
[minor] · New parent-hash assertion aborts the connect_block fuzz target
Source inspection shows that a structurally valid connect_block fuzz input with a mismatched hashPrevBlock now aborts at the new assertion instead of reaching UTXO validation.
Location: src/validation.cpp:2550 (head).
Details and suggested fix
ConsumeBlock() can randomize block.hashPrevBlock, but the harness still sets new_index.pprev = active_tip and calls the member wrapper with fJustCheck=true. The wrapper derives ctx.prev_block_hash from that index parent. In this mode, CheckBlock() skips PoW and merkle-root verification, and its remaining checks do not inspect the previous hash. A structurally valid block therefore reaches the new assertion with a matching view but a mismatched header. The base checked only the index parent's hash against the view, so these inputs previously reached the UTXO checks. Keep the core invariant and adjust the harness to consume the parent-hash mutation bytes without applying them, preserving the fuzz input format.
Optional improvements
[suggestion] · Redundant script_flags can disagree with the context
No current caller omitting or mismatching script_flags was found, but ConnectBlock() trusts this redundant field, whose SCRIPT_VERIFY_NONE default omits active rules and P2SH/witness sigop counting.
Location: src/validation.h:524 (head).
Details and suggested fix
BlockValidationContext stores script_flags alongside its complete derivation inputs: block_hash, deployments, and params. Omitting the field from a designated initializer produces SCRIPT_VERIFY_NONE. The core then passes that value directly to both GetTransactionSigOpCost() and CheckInputScripts(), even when check_scripts is true. Derive the flags in the core with GetBlockScriptFlags(ctx.block_hash, ctx.deployments, ctx.params) instead of requiring callers to populate the redundant field. This preserves current results, retains the factory's consensus-subset check, and removes an invalid combination from the public context API.
[suggestion] · Context comparisons miss deployment activation boundaries
context_matches_the_block_index repeats the factory's deployment formulas far beyond activation, so a one-block error in height selection can leave every deployment and script-flag assertion passing.
Location: src/test/validation_context_tests.cpp:42 (head).
Details and suggested fix
The default TestChain100Setup leaves the tip at height 100, so this context describes block 101. All five buried deployments are already active there. Replacing the factory's child-height evaluation with the parent's height would therefore leave these assertions unchanged. The deployment expectations repeat DeploymentActiveAfter(tip, ...), and the flags expectation uses ctx.deployments rather than independently checking the selected height. Add cases using -testactivationheight overrides and children at N-1 and N. Compare their contexts against DeploymentActiveAt(*child, ...), the form used before this refactor, and build the expected script flags from those independent values.
[suggestion] · ContextualCheckBlock() retains redundant index inputs
Current callers supply matching ancestry, but ContextualCheckBlock() still requires two sources for height and previous median time past and repeats an index walk.
Location: src/validation.cpp:4389 (head).
Details and suggested fix
MakeBlockValidationContext() already copies the parent's height plus one into ctx.height and its median time past into ctx.prev_median_time_past. ContextualCheckBlock() gets deployments from that context but reads those other facts again through pindexPrev. Drop its index parameter and use the copied values, replacing the CSV non-null assertion with assert(ctx.height > 0). Keep the index parameter on ContextualCheckBlockHeader(), where GetNextWorkRequired() needs it. This removes the redundant inputs without changing current results.
[suggestion] · Script execution cache locking lacks concurrent coverage
The new ValidationCache accessors permit use without cs_main, but existing tests never overlap insertion with lookup, leaving the new synchronization contract unexercised.
Location: src/validation.h:384 (head).
Details and suggested fix
The existing script-cache tests serialize access under cs_main, and validation_core_tests uses each cache serially. Add a focused test sharing one ValidationCache without cs_main: run insertion alongside lookup loops using both erase=false and erase=true, check for false hits with a disjoint set of never-inserted keys, and join all threads before destroying the cache. Do not require inserted entries to survive eviction or erased hits to disappear immediately, since deletion is lazy. This would give ThreadSanitizer a path that detects an unguarded insert racing with lookup, which the current serial tests do not provide.
[suggestion] · Header-check conversion is buried in the ConnectBlock() move
a764ec8c combines changes to header/block acceptance with the large ConnectBlock() extraction, making their equivalence harder to check independently.
Location: src/validation.cpp:4341 at a764ec8c4d64 (commit) (commit).
Details and suggested fix
Commit a764ec8c4d64e78cfb660d6e55cc34a40e8e61d2 changes the contextual checks and their acceptance callers while also extracting disconnection, consensus helpers, and the connection core. Separating the header/block acceptance conversion would let reviewers check its clock and deployment inputs without also following the large ConnectBlock() move.
Keep the cache-lock commit 0f5499a43d32977fd9b88cab604fc74d4c86fa3d first, then split the second commit in dependency order: sequence-lock and IsBIP30Repeat() value overloads; free DisconnectBlock() and its wrapper; context, flags and BIP30 extraction plus contextual checks and callers with validation_context_tests; finally free ConnectBlock(), its result and wrapper with validation_core_tests. The old member connection implementation can remain until the last step. This ends at the same tree. If preserving upstream commit identities takes precedence for traceability, document this decomposition instead.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
BIP30 prevents duplicate transactions from overwriting still-unspent outputs, including attacks against nodes replaying old history. The two historical exceptions preserve blocks whose miners reused coinbase contents, replacing the earlier outputs and making them effectively unspendable. Extending enforcement backward, except for those exact blocks, addressed an IBD denial-of-service attack on pre-enforcement forks.
The exception decision is historical consensus behavior, not merely a performance option. Moving it into a context must retain the distinction between the exact grandfathered blocks and other blocks at those heights. The pinned base explicitly ties the rule to preventing overwrite attacks during IBD.
The BIP34-based BIP30 bypass was introduced to save database accesses, but depends on the known historical chain and absence of latent duplicate-transaction chains—not height alone. Its original uniqueness argument was subsequently corrected: pre-BIP34 coinbases can accidentally begin with the encoding of a future height. Re-enforcement from height 1,983,702 is inclusive. The earlier candidates were covered by existing BIP30 enforcement or by the original coinbase having been spent in a transaction that could not itself be duplicated at the relevant height.
The extracted enforce_bip30 value represents a bounded optimization with historical premises: the BIP34 ancestor hash, the two duplicate pairs, and the re-enforcement limit. A generic statement that BIP34 makes BIP30 unnecessary would omit the very constraint that prompted the correction. Historical objections also explain why headers-first alone was not considered sufficient protection against bogus early history.
Source 1 · Source 2 · Source 3 · Source 4 · Source 5
Assumevalid deliberately separated script-verification skipping from checkpoints. A specific, externally verifiable block hash supplies an auditable assumption without forcing chain selection; an invalid assumed history can nevertheless cause acceptance of invalid scripts. Work burial was intended to resist pressure to accept a newly invalid chain and allow public response, while retaining signature-verification coverage during release testing. Its depth also trades off against synchronization speed on slow devices.
The pinned wrapper checks ancestry under both the assumed-valid block and best header, minimum chainwork, and more than two weeks of equivalent work before clearing check_scripts. The context boolean is therefore the result of node policy with security premises, not a fact derivable solely from the block. Calling it policy does not make arbitrary script omission consensus-neutral.
Source 1 · Source 2 · Source 3
The full-script cache was intentionally narrower than a transaction-validity cache. Its proposal warned that broader validity caching had caused consensus failures. It keys script success by witness transaction hash and script flags, relying on consistent prevout data and precomputation across mempool and block validation. Objections about making mempool behavior consensus-critical led to additional prevout checks and a narrower script-check input interface. The signature cache remained useful against malleability-based denial of service.
The extracted core must continue to perform UTXO, amount, sequence-lock, and other non-script checks independently of cache hits. Its context and callback do not enlarge what a script-cache hit proves. The historical concern was dependency control, not merely whether the cache has a mutex.
Source 1 · Source 2 · Source 3 · Source 4 · Source 5
CuckooCache was designed to support concurrent reads and lazy erasures, with deletion marking an atomic garbage-collection flag rather than immediately removing the entry. Its historical motivations included lower memory overhead, reduced lock contention during parallel script checking, and retaining useful entries around reorganizations. The pinned implementation explicitly requires external synchronization for its relaxed atomic operations.
This explains why an erasing lookup can belong to the read-side synchronization class: it is not ordinary container removal. It does not imply that all cache operations, insertion, reset, or destruction may run concurrently without synchronization. Replacing cs_main must preserve the cache's own synchronization contract.
The historical persistence invariant is dependency-ordered durability: block and undo files precede index records referring to file positions, and the block index precedes chainstate referring to the best-block hash. Dirty-index tracking and coordinated flushing allowed writes to be batched rather than forced for every block, improving relay latency while protecting crash recovery. The rationale distinguishes ordering from merely making each write final.
The pinned base writes undo, marks script validity, and then advances the supplied view. Historical evidence explains the durable dependencies, but does not by itself require every private in-memory marker to follow that same statement order. The important distinction is between changing a tentative view and publishing or persisting chainstate that depends on index and undo state.
Source 1 · Source 2 · Source 3
Ralph's inferences
Consume-on-connect is best understood as cache replacement policy rather than a one-use validity guarantee. Marking a successful hit discardable makes room for other work; lazy deletion can still leave the entry available. A cache miss must simply cause verification, not change validity.
The head contract describes block connection consuming signature-cache hits, while the cache design permits lazy erasure. The new lock boundary need not turn consumption into exclusive ownership of an entry, but must retain the distinction between cache policy and the checks a hit permits skipping.
The historical constraints are compatible in principle with passing evaluated deployment rules, script flags, and BIP30 decisions across a context boundary, provided they describe the same block ancestry and UTXO predecessor. Assumevalid additionally requires a policy decision made from the node's header and work state.
The head context separates copied consensus inputs from the wrapper's assumevalid decision. This is a conditional explanation of the boundary: historical rationale does not require consensus calculations to own a ChainstateManager, but it does require preservation of the premises represented by those values.
A borrowed ancestor callback needs both stable data and a surviving owner. GetMedianTimePast reads ancestor timestamps through parent links; the context's function object does not itself confer ownership of that graph. Immutability alone therefore cannot establish the callback's lifetime.
The new contract explicitly limits callback use to the block index's lifetime. The inspected index header also warns that copied entries can retain dangling parent and skip pointers. Off-lock use is consequently conditional on completed publication, unchanged fields, and exclusion of teardown or replacement for the entire call—not merely on releasing cs_main after context construction.
Earlier advancement of a tentative view's best-block marker is compatible with the historical persistence model only if wrapper failure prevents that view from being published or flushed. The inspected evidence supports this condition for the ConnectTip success gate, but does not establish equivalence on every failure path.
The core now advances the marker only after successful consensus and script checks, while undo writing can still fail afterward. ConnectTip flushes its overlay only after the wrapper returns success, and the overlay is documented as ephemeral. Thus the historical question is failed-view disposal and publication ordering, not a general requirement that an already-mutated private view always retain its predecessor marker. The old code already allowed partial coin mutations on validation failure.