Add output script index and corresponding script history RPC

bitcoin/bitcoin: PR #36629

1 major finding · 1 minor finding · 10 suggestions

Earlier concerns neither republished nor resolved: 2 minor findings · 1 suggestion. See the Run archive for their assessments.

Findings

Link

[major] · Restart recovery can apply stale offsets to a replacement block

A restart across a branch replacement can leave stale offsets that persistently fail getscripthistory; the clean-restart case was reproduced on regtest, but no production occurrence was identified.

Location: src/index/txoscriptindex.cpp:81 (head).

Details and suggested fix

WriteEntries persists (prefix, height) -> offsets separately from the locator, whose commit can be skipped until chainstate is flushed. If block A's rows survive but its locator does not, restarting at A's parent and then connecting replacement block B never passes A to CustomRemove. Replay writes B's prefixes but leaves prefixes unique to A. Find then seeks A's offsets inside B, so incompatible replacement bytes cause transaction-read errors while the index reports itself synced. The recorded test-only regtest experiment reproduced this after invalidateblock and a clean restart; another restart preserved the failure, while rebuilding only txoscriptindex repaired it. Store the originating block hash with each row and reject mismatches before reading transaction offsets. Add a restart-and-replacement regression test for a script present only in A.


Link

[minor] · Restoring the tip can hide an incomplete history response

Concurrent operator invalidateblock/reconsiderblock calls can make getscripthistory return incomplete history after the original tip is restored; this interleaving is established statically, with no production occurrence identified.

Location: src/rpc/blockchain.cpp:4274 (head).

Details and suggested fix

After the initial readiness check, Find resolves each row through the live m_chain[key.height] and silently skips it if that height is temporarily absent. If invalidation shortens the chain when a row is visited and reconsideration restores it before the final guard, the omitted transaction is not recovered. Tip equality, or final membership of the asof block, then allows the incomplete response through. Track a disconnect generation under cs_main, capture it with the selected block, and reject the query if that generation changes even when the original tip is restored.


Optional improvements

Link

[suggestion] · Per-output spentness probes bypass the lookup budget

Dense spendable-output histories can cause many unmetered UTXO probes under one cs_main hold, or spender-index seeks with asof; the lock duration has not been measured.

Location: src/rpc/blockchain.cpp:4031 (head).

Details and suggested fix

A transaction paying the same script many times contributes one candidate-body charge, but each spendable matching output still requires separate spentness work. Without asof, cache misses in PeekCoin reach the chainstate database while one cs_main lock covers the whole loop. With asof, each unresolved output without a spender incurs a fresh FindSpender seek and is erased without a budget charge. At about 31 serialized bytes per P2WPKH output, the allowance can admit on the order of a million probes. Charge a fixed work cost per probe, including misses. Bounded lock batches could also limit uninterrupted lock time, but must preserve chain-view lifetime and detect intervening chain changes.


Link

[suggestion] · Verbose history expansion is outside the read budget

Verbose getscripthistory responses expand all inputs and outputs into uncharged JSON, potentially using several times the 50 MiB read allowance; peak memory has not been measured.

Location: src/rpc/blockchain.cpp:4206 (head).

Details and suggested fix

At verbosity 1 and 2, TxToUniv decodes complete transactions, including unrelated outputs and their scriptPubKey descriptions, and retains transaction hex by default. Small serialized outputs become nested objects containing several strings, and the handler copies the decoded vout array before annotating it. None of that storage is charged to remaining_bytes, so dense-output histories can consume substantially more response memory than their serialized read cost suggests. Charge an estimated per-input/per-output expansion cost at verbose levels. Moving rather than copying the decoded array would additionally remove the temporary per-transaction copy.


Link

[suggestion] · Post-snapshot spenders can exhaust an asof page's budget

Later confirmed spends can make a fixed asof page unanswerable even with include_spending_transactions=false; height pagination cannot separate outputs created in one block, although their snapshot spentness remains unchanged.

Location: src/rpc/blockchain.cpp:4116 (head).

Details and suggested fix

FindSpender deserializes the full spending transaction, and count_transaction charges it before the ancestry check discards spends confirmed after query_block. This also happens when include_spending_transactions=false, because asof still resolves spentness. The size-limit fixture explicitly expects an older-snapshot query to hit this budget error. For outputs created together, narrowing the height range cannot reduce the page further, despite the help saying newer blocks do not invalidate the query. Add a snapshot-aware lookup that checks each candidate's block header and ancestry before reading its body, keeps scanning excluded candidates, and charges the work actually performed. If later-chain activity is intentionally allowed to exhaust snapshot queries, document that limit in the asof help.


Link

[suggestion] · Selective pruned-block downloads lack a privacy warning

Fetching exactly pruned_blocks from one peer reveals query-correlated historical blocks and may identify the queried scripts, depending on their history; the recommended workflow has no privacy warning.

Location: src/rpc/blockchain.cpp:3753 (head).

Details and suggested fix

The help and release notes recommend fetching the listed hashes with getblockfrompeer. These are matching unavailable blocks in the selected range, with normally few false positives from the six-byte prefix, rather than a cover download. Each call sends the chosen peer a targeted block request. By comparing outputs across requested old blocks, that peer may infer scripts of interest and associate them with this node. Add a privacy warning beside the recommendation, suggesting a trusted peer or broader block downloads instead of fetching exactly the listed hashes.


Link

[suggestion] · Undo-position discovery spends budget on full block reads

For non-coinbase matches in undo-bearing blocks, verbosity 2 charges a full block read just to find undo positions, reducing the history that fits within the budget.

Location: src/rpc/blockchain.cpp:4187 (head).

Details and suggested fix

On each block-cache miss, the handler reads undo data and the complete block, then uses the block only to build undo_positions. Sparse histories spanning many blocks therefore spend much of their allowance on transaction bodies unrelated to the response. Consider storing each transaction's ordinal alongside its byte offset so matches can select vtxundo[i - 1] without rereading the block. This costs roughly one additional varint per stored offset. Extra spenders from txospenderindex still lack ordinals and would retain the current fallback; the budget improvement depends on block and undo sizes.


Link

[suggestion] · Verbosity-0 amounts lack the OpenRPC unit annotation

OpenRPC marks decoded vout.value as a Bitcoin amount at verbosity 1 and 2, but omits that unit annotation for the same numeric field at verbosity 0.

Location: src/rpc/blockchain.cpp:3801 (head).

Details and suggested fix

The summary response fills value with ValueFromAmount, but declares it as RPCResult::Type::NUM. Unlike STR_AMOUNT, that declaration does not emit x-bitcoin-unit: amount in getopenrpcinfo or rpc.discover. Change this declaration to STR_AMOUNT, matching decoded outputs, so schema consumers can recognize the amount uniformly without changing the returned JSON.


Link

[suggestion] · Ranged-descriptor mempool subsets are not checked

The multipath and range-subset assertions exercise only confirmed index lookups, leaving the corresponding selected-output behavior unchecked in the separate mempool matching path.

Location: test/functional/rpc_getscripthistory.py:296 (head).

Details and suggested fix

test_ranged_descriptor mines its transaction before querying any range. Mempool matching instead tests each output against the expanded scripts set, so the confirmed assertions do not exercise that selection path. Run the same (range, indices) assertions before mining as well, checking the txid, selected output indexes, and absence of block metadata. This adds direct multipath/range coverage without another transaction or block.


Link

[suggestion] · Cached undo fields go unchecked on the second match

The undo-size test would still pass if undo-derived fields were attached only while loading a block, leaving its second same-block match without prevout or fee.

Location: test/functional/rpc_getscripthistory.py:433 (head).

Details and suggested fix

The fixture returns two matching spends from small_block, but checks prevout data only through history["transactions"][0]["vin"]. Its later getrawtransaction comparison also selects only that first transaction. The second result reuses cached undo data, so omitting undo attachment on cache hits would escape these assertions. Before invalidating small_block, compare vin and fee for both results against getrawtransaction(txid, 2, small_block).


Link

[suggestion] · The default descriptor range boundary is not covered

The default-range assertion uses only derivation indexes 0 through 3, so it cannot distinguish the documented upper bound of 1000 from a shorter default.

Location: test/functional/rpc_getscripthistory.py:293 (head).

Details and suggested fix

range=None reaches EvalDescriptorStringOrObject's inclusive {0, 1000} default, but all eight fixture outputs are below index 4. A default ending at 100 or 999 would therefore leave the assertions passing. Derive the last output on each branch at index 1000 instead of 3. The default case would then check its upper boundary, while the [1, 2], end-2, and empty [4, 4] expectations remain unchanged.


Link

[suggestion] · The RPC fuzzer stops before getscripthistory parsing

The generic RPC fuzzer does not exercise getscripthistory's handler parsing because its setup leaves g_txoscriptindex unset.

Location: src/test/fuzz/rpc.cpp:155 (head).

Details and suggested fix

RPCFuzzTestingSetup adds no index to TestingSetup, so calls that pass the RPC framework's argument checks stop at the index-enabled guard before option parsing, descriptor expansion, or lookups. The allowlist entry is still necessary for command classification; indexed getblockfilter lookups have a similar setup limitation. Add a dedicated fuzz target with a synchronized in-memory script index and bounded descriptor ranges to reach the new handler paths.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.