Repository navigation
Add output script index and corresponding script history RPC - #36629
andrewtoth wants to merge 5 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. LLM Linter (✨ experimental)Possible places where named args for integral literals may be used (e.g.
Possible places where comparison-specific test macros should replace generic comparisons:
2026-11-28 23:41:24 |
8363edf to
614302e
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
Concept ACK |
1 similar comment
|
Concept ACK |
|
Strong Concept ACK |
kravens
left a comment
There was a problem hiding this comment.
Concept ACK.
Reviewed 614302e. I built it and ran txoscriptindex_tests, baseindex_tests, rpc_getscripthistory.py, rpc_misc.py, feature_init.py and feature_assumeutxo.py, all passing. I also did a manual regtest run: address, Electrum scripthash, ranged wpkh() descriptor, verbosity 0/1/2, and spender linking. Results matched expectations. My comments are mostly about structure:
1. The lookup budget does not count block and undo reads. At verbosity 2, tx_to_json reads the full block and its undo data for every block that holds a non-coinbase match (rpc/blockchain.cpp:4116). Step 10 also reads a full block whenever two or more extra spenders share one (rpc/blockchain.cpp:4064). Neither read is charged. I ran this on regtest with 150 matches, each in its own block padded to ~60 kB. Bytes read by bitcoind during one call (rchar):
| verbosity | matching tx bytes | bytes read by node |
|---|---|---|
| 0 | 52,039 | 0.94 MB |
| 2 | 52,039 | 21.2 MB |
On mainnet that means one full block plus its undo data per matching block. A query that fits in the 50 MiB budget can therefore read far more than 50 MiB. Either charge these reads, or say in the help text that the budget does not cover them.
2. OrderedVarInt could be BigEndianFormatter<3>. Big-endian already sorts by height, and the same key already uses it for the tx offset. Both encodings are 3 bytes for heights 16,512 through 2,113,663 (roughly until 2048). After that, BE3 stays at 3 bytes while OrderedVarInt grows to 4, and BE3 goes up to height 16,777,215. I tried it locally. It removes ordered_varint.h and its tests (+4/−210), and the PR's unit and functional tests still pass:
+ static constexpr uint32_t HEIGHT_SIZE{3};
...
- Using<OrderedVarIntFormatter>(obj.height),
+ Using<BigEndianFormatter<HEIGHT_SIZE>>(obj.height),3. Ordering spenders doesn't need a block read. txospenderindex keys already store a CDiskTxPos, and its nTxOffset grows with the transaction's position in the block. I added it to TxoSpender and sorted extra spenders by (height, tx_offset). That removes the grouping loop and the GetBlockChecked call (+6/−20). test_confirmed_transaction_order still passes. It fails if the offset is dropped from the comparison, so the test does cover this.
4. Find could take the whole set of script hashes. Today the RPC calls Find once per hash and merges results by (height, tx_offset). A transaction paying two scripts of one descriptor is read and charged twice; rpc_getscripthistory.py relies on this ("repeated reads of overlapping transactions exceed the work budget"). A multi-hash Find would read each candidate once and drop both ScriptHistoryMatch::tx_offset and the by_position merge. The budget would then trip later than it does now, never earlier, so that test case would need updating. Returning pruned blocks as their own set instead of null-tx placeholders would also remove the duplicated branch at index/txoscriptindex.cpp:163 and :174, and the matching filter in the RPC.
5. One budget, one error. Index lookups charge a uint64_t& and fail with "Script history index lookup limit exceeded…". Extra transaction bodies throw a std::runtime_error with "Script history exceeds the … byte budget" (rpc/blockchain.cpp:3933). Both enforce the same limit through two code paths with two messages. The index-layer message also names RPC options (index/txoscriptindex.cpp:138). A small budget type that both layers charge, with the user-facing wording kept in the RPC, would be simpler.
6. Could the RPC go in its own file? blockchain.cpp grows by ~530 lines to 4,238. The handler is one ~400-line lambda that opens with a 12-step index comment. src/rpc/scripthistory.cpp with one function per step would be easier to read and review.
7. TxToJSON is now declared in rawtransaction_util.h. That header belongs to bitcoin_common, which the wallet also links. TxToJSON takes a Chainstate and is still defined in rawtransaction.cpp in bitcoin_node. Declaring it in a node-side header would keep that boundary clean.
Nits:
-
The mempool scan matches against
scriptsorscript_hashesdepending on how the query was given (rpc/blockchain.cpp:3986). Hashing everything up front would leave one set and remove the branch. -
When
rangeis given, the descriptor is parsed twice: once atrpc/blockchain.cpp:3896and again insideEvalDescriptorStringOrObject. -
RawTransactionDocchanges thegetrawtransactionhelp text:blockhashmoves belowvsize_adjustedand gains "(omitted for mempool transactions)".- The
hexdescription changes. - At verbosity 2,
feemoves to the end.
Probably fine, but worth a line in the commit message.
Disclosure: AI (Claude Opus 5.5) was used to find these issues and to draft this review.
614302e to
cf9b981
Compare
ViniciusCestarii
left a comment
There was a problem hiding this comment.
Concept ACK. I skimmed the code but plan to take a deeper look. Commented 2 nits.
5735ea9 to
1fc5b61
Compare
|
Thanks @kravens, @romanz, and @ViniciusCestarii for the reviews, and @sedited, @l0rinc, and @w0xlt for the concept ACKs! I took some of the suggestions, and made some additional updates. This changes the index format so anyone who was testing with the previous version needs to rebuild it.
|
|
Concept ACK |
kravens
left a comment
There was a problem hiding this comment.
tACK 1fc5b61
Re-reviewed the changes since 614302e (same base, no rebase). Built it and ran txoscriptindex_tests, txospenderindex_tests, ordered_varint_tests, caches_tests, baseindex_tests, rpc_getscripthistory.py, rpc_misc.py, rpc_gettxspendingprevout.py, feature_init.py and feature_assumeutxo.py. All pass.
From my earlier comments, 1 (block and undo reads outside the budget), 3 (spender ordering without a block read) and 7 (TxToJSON header) are fixed: tx_to_json now charges the serialized undo and block (rpc/blockchain.cpp:4154, :4159), test_undo_size_limit covers the limit, and the step-10 block read is gone. 2, 4, 5 and 6 were suggestions; no objection to leaving them.
What I checked in the new layout:
- One row per (prefix, height); the value is a run of VARINT offset deltas read until the stream is empty.
Serializerejects empty, non-increasing and out-of-block offsets, andUnserializecaps the count atMAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT. Keys, values and transaction bodies are all charged to the budget. Findkeeps one block file open across rows and seeks withSEEK_SET, which keeps theAutoFileobfuscation position correct (streams.cpp:41). Matches still come back in (height, offset) order, so theby_positionmerge in the RPC holds.CustomRemoveerases the (prefix, height) key and a competing block at the same height overwrites it;txoscriptindex_reorg_erases_rowscovers the rewind.- 6-byte prefix: with roughly 2^31 distinct scripts on mainnet, the chance that a queried script shares its bucket with any other script drops from about 2^-9 to 2^-17. Agree with the change.
asof: I read it with the paging use case in mind and could not break it. Spentness at asof comes only from the matches and txospenderindex; spenders above asof are dropped by the ancestor check at rpc/blockchain.cpp:4097 and the output stays unspent. Reorgs above asof leave the answer unchanged, reorgs through asof fail the final check, and confirmations and times come from the asof block via TxToUniv, so a page stays identical while the tip moves. test_asof exercises all of this.
Observations, none blocking:
- asof could be served during the initial index sync.
BlockUntilSyncedToCurrentChain()returns false until the whole sync finishes (index/base.cpp:444), so a node still building either index answers nothing, even for an asof block both indexes passed long ago. The ancestor checks atrpc/blockchain.cpp:3954and:3960already guarantee that every row up to asof exists (the summary's best block lags the DB by up to 30 s during the initial sync and never leads it). Skipping the twoBlockUntilSyncedToCurrentChain()calls when asof is given would let a server start paging old history while the index catches up. Fine as a follow-up. - Explicit
include_mempool=truetogether withasofis silently ignored (rpc/blockchain.cpp:3890). The help text says so, but anRPC_INVALID_PARAMETERwould make the conflict visible to a caller who set both on purpose. - Release notes. The summary mentions release notes, but the branch only touches
doc/files.md. Did adoc/release-notes-36629.mdmiss the push? rpc: share transaction JSON helpersstill has an empty commit body. It changes thegetrawtransactionhelp layout (blockhashmoves belowvsize_adjusted,feemoves last at verbosity 2). One line in the message would help whoever bisects a help-text diff later.- The "test ancestor commits" CI job died in
p2p_segwit.pyon an assertion that looks unrelated, before it reached the later commits, so the per-commit build check needs a re-run.
Disclosure: AI (Claude Fable 5.1) was used to find these issues and to draft this review.
|
Thanks @kravens, @ViniciusCestarii, @romanz, @craigraw and ralph for the reviews and suggestions!
|
arejula27
left a comment
There was a problem hiding this comment.
Concept ACK
I really like this idea. Many users run an Electrum server just to get a script index, so having it in Core means they would not need to run extra programs, which helps on low resource devices.
I read through the index and the RPC and the code looks good to me. I only left two small nits inline.
This could also speed up processes inside Core, for example wallet rescans, the same way they already use blockfilterindex but getting exact heights instead of filter matches. I think this should be a follow-up. I did a quick prototype with the help of Opus (too be fair it did the protoype) and the results look promising. Benchmark on regtest (6,000 blocks, 20 payments to the wallet, importdescriptors with timestamp 0 and range 1000 on a fresh wallet, 2 runs):
| mode | time | blocks inspected |
|---|---|---|
| no indexes | 0.45s | all |
| blockfilterindex | 4.8s to 5.2s | 85 |
| txoscriptindex | 0.37s to 0.39s | 20 |
This was a quick test, so don't take the results too seriously.
| } | ||
| scan_object.pushKV("range", options["range"]); | ||
| } | ||
| for (const CScript& script : EvalDescriptorStringOrObject(scan_object, provider)) scripts.insert(script); |
There was a problem hiding this comment.
nit: a mistyped address or an address from another network is not a valid destination, so it falls through to the descriptor path and the error is 'bcrt1q...' is not a valid descriptor function. That is confusing for someone who passed an address. Maybe the error could say Input is not a valid address, scripthash or descriptor.
|
Concept ACK @arejula27, no-index inspected all blocks in 0.45s and blockfilterindex inspected 85 blocks in ~5s, hmm? |
| /** | ||
| * Unsigned integer encoding whose lexicographic byte order matches numeric order. | ||
| * | ||
| * Length is stored in the leading bits of the first byte (UTF-8 style), so | ||
| * every n-byte encoding sorts before every (n+1)-byte encoding. Payload bits | ||
| * are big-endian after subtracting the ranges covered by shorter encodings. | ||
| * Supports up to five bytes, sufficient for any uint32_t. Size cutovers match | ||
| * Bitcoin Core VARINT: | ||
| * | ||
| * 1 byte: 0 .. 127 | ||
| * 2 byte: 128 .. 16,511 | ||
| * 3 byte: 16,512 .. 2,113,663 | ||
| * 4 byte: 2,113,664 .. 270,549,119 | ||
| * 5 byte: 270,549,120 .. 34,630,287,487 | ||
| * | ||
| * Unlike VARINT, this can be used as a LevelDB key field for range seeks. | ||
| */ |
There was a problem hiding this comment.
This is only used to store the height. Looks an overkill to me compared to just using big endian encoded uint32_t. How much is the estimated saving in disk space vs uint32_t?
This was also mentioned in the main PR thread here:
there the suggestion is to use big-endian-3-byte which would be enough for the next ~240 years.
@kravens, it is better to post suggestions as separate comments to some line in the code because then each one can be marked as resolved independently and conversation can be grouped together, instead of being scattered around in the PR main thread.
There was a problem hiding this comment.
I removed this and replaced with big-endian-3-byte. One issue would be testnet3, which is already past 5 million blocks. At this pace it could exceed 16,777,215 blocks in ~30 years.
Perhaps it is easiest to just use the full 4 bytes and remove any doubt, while avoiding this complexity. I will consider it.
There was a problem hiding this comment.
I added another byte to the key, but shared it with both the prefix and height.
- 28-bit height is 268,435,455 max, ~5100 years on mainnet and ~800 years for testnet3.
- 52-bit prefix makes collisions with any script ~1 in 2.8M, or ~1 in 217M against any script appearing in > 10 blocks.
This adds an extra 2GB to the db though, but I think the tradeoff makes sense.
|
@vasild yep, it looks weird. That row is misleading and I should not have included it. It was a quick check on empty regtest blocks, only to see if the difference was big enough to be worth mentioning. Since the blocks only have the coinbase, reading all of them is almost free. The filter adds an overhead, for every block,
I think the blockfilterindex vs txoscriptindex comparison still holds. |
|
concept ACK |
|
I did some quick tests locally, and I think there’s a spentness bug when two coinbases have the same txid. What made me look twice was that changing only I used regtest with Here’s what
The live path checks whether the outpoint exists in the current UTXO set. Both coinbases have the same txid and output number, so the coin created at height 102 makes both occurrences look unspent. I think comparing the coin’s creation height with the height of the match would fix that part. For historical queries, the unresolved outputs are also keyed by outpoint. With both coinbases in the result, the height-101 spend gets associated with the first one. When I ask for just height 102, the same spend gets associated with the second one. The code checks that the spender is on the chain through I think the creation position needs to be carried through spender resolution. I also noticed a separate issue with mempool locking. With |
283bf82 to
7133c83
Compare
|
Thanks @arejula27, @vasild, and @jaromil for the reviews, and @Rob1Ham for the concept ACK!
@jaromil Thanks for finding this edge case. Interesting. I haven't used this option before. Do you have a use case that depends on correctly handling duplicate coinbases in regtest history? I don't think it's possible to have duplicate coinbase txs on mainnet aside from the BIP30 exceptions (which are handled) unless BIP54 or another fix like it is not activated by height 1,983,702 (~2046). I would like to avoid the complexity of fixing this edge case if it is ok with you. |
7133c83 to
fef6987
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
fef6987 to
88b7c0d
Compare
|
Updated with a few index and RPC improvements. Note the index database format has changed, so if you were testing you will have to rebuild the index.
|
Yep, I agree. I only used that regtest setup to reproduce the edge case, and I don’t have a use case that depends on it. The mainnet risk is remote, and I’m optimistic we’ll have BIP54 by then :^) |
Backport the provisional txoscriptindex and getscripthistory RPC from bitcoin/bitcoin#36629, pinned at 88b7c0d9032241c0426e0218e7bdf22bb609102d. GitHub's compare against target snapshot afedb19cca4c3b40d89514fb0c66b0c20e4f5d62 identifies merge base dd96035e031edf56fcf66a09d443f257a346af1f. Upstream commits by Andrew Toth <[email protected]>: * d87083df6a337d45135be74d0ae7594312b10cde index: add txoscriptindex * 93b6064b96e3b12efb455fdd8069b259db4321c3 index: expose spender transaction offsets * 40d354f8bf100e46ded7b521dcf6533391595ff9 rpc: share transaction JSON helpers * 9044d4714c6fd6dd71f35000abb0f0428e29c09a rpc: add getscripthistory * 88b7c0d9032241c0426e0218e7bdf22bb609102d docs: add release notes Carry the header-only util/not_null.h prerequisite at the pinned base from MarcoFalke's fafa44e020ab7783515c3176f2205d47e6bc99c3 and fa4785828e804f44726102070fb1adeacbdce6e5. Carry MarcoFalke's test-only StopIndex utility from fa339713dbc58e36b0da0f2f1cce8a231939893f to drain callbacks before fixture teardown. Use Roots' existing index lifecycle and spender-index storage. The newly exposed spender offset is derived from existing disk positions. Use Roots' existing index summary lookup for getindexinfo and preserve cache defaults and overflow-safe accounting, the index readiness test and blockchain RPC includes. Configure the upstream test's disposable node to accept its existing OP_RETURN size padding via the Roots script and datacarrier policy options. The existing spender index remains incompatible with pruning. The script index uses a separate database and supports pruning on its own. This provisional backport retains the pinned RPC's accepted limitation: spentness and spender attribution can be wrong for duplicate outpoints. The existing BIP30 regression passed. The exact historical mainnet exception blocks were not replayed for this backport. After Core merges the PR, compare the landed commit range and prerequisites with the aggregate diff from dd96035e031edf56fcf66a09d443f257a346af1f to 88b7c0d9032241c0426e0218e7bdf22bb609102d. Review differences against this isolated commit before refreshing it, and verify spender-index compatibility and the script-index format again. Co-authored-by: Andrew Toth <[email protected]>

Add a new index
txoscriptindexwhich indexes all output scripts. Introduce a newgetscripthistoryRPC that returns all transactions that create outputs corresponding to the provided scripts, and optionally the transactions that spend those outputs iftxospenderindexis also configured.This has been a long-requested feature, attempted in previous PRs (#2802, #3652, #6835, #10370, #14053).
Some concerns raised were about the ability for an index like this to scale. I think the new techniques being used to build the indexes (#35531, #36002) alleviate this concern. This index can be synced in a few hours and the current disk usage is ~56 GB. This is less than the ~66 GB
txindexdisk usage in v31 and earlier. This index can also be used with a pruned node, so a full node can be supported in < 100 GB of disk space. Missing blocks are returned by hash and can be requested from peers usinggetblockfrompeer.Some other previous concerns were more conceptual, that this type of index could encourage address reuse and chain analysis. IMO this ship has sailed, and the current status quo of not shipping an address index is turning off users who expect this functionality. Workarounds involve installing, configuring, and syncing other third-party software, making the UX of using Bitcoin Core in a self-sovereign way unnecessarily difficult.
The index hashes each output script with SHA256, then applies salted SipHash-1-3-UJ and stores a 52-bit prefix. This is to support the popular Electrum protocol, which supplies only the script hash. The RPC can also look up by address or descriptors. Ranged descriptors are also supported, so a single RPC call can return the entire history of a receive/change xpub pair.
Keys pack the 52-bit script-hash prefix and a 28-bit big-endian block height (up to ~268M blocks, ~5,100 years on mainnet) into 10 bytes (plus an optional generation suffix for reorged heights, validated against a small
(height, gen) -> block_hashtable). This lets LevelDB seek directly to the prefix + block height, so we can page by block height range, while keeping the index append-only and resilient to reorgs and unclean shutdowns. At ~1.59B distinct mainnet scripts, a 52-bit prefix makes collisions rare in practice (~1 in 2.8M per script, ~0.07% across a 2,000-script ranged descriptor, and ~1 in 217M against any script appearing in >10 blocks), and any collision is filtered out against the full SHA256 hash.To prevent DoS concerns by supplying an address with millions of outputs, the RPC tracks a byte budget of reads and throws immediately if too many reads are attempted. The error message instructs the user to narrow the block range.
Improvements to
txospenderindex(#36480) will also allow us to use that pruned. The end result would allow users to run with all optional indexes (including this one) in < 200 GB of disk space. Of course a larger pruned setting would be desired if many historical block lookups were being requested.