Add output script index and corresponding script history RPC #36629

Open
andrewtoth wants to merge 5 commits from txoscriptindex into master AGit
andrewtoth commented 2026-10-23 17:19:11 +00:00 (Migrated from github.com)

Add a new index txoscriptindex which indexes all output scripts. Introduce a new getscripthistory RPC that returns all transactions that create outputs corresponding to the provided scripts, and optionally the transactions that spend those outputs if txospenderindex is 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 (https://github.com/bitcoin/bitcoin/pull/35531, https://github.com/bitcoin/bitcoin/pull/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 txindex disk 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 using getblockfrompeer.

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_hash table). 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 (https://github.com/bitcoin/bitcoin/pull/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.

Add a new index `txoscriptindex` which indexes all output scripts. Introduce a new `getscripthistory` RPC that returns all transactions that create outputs corresponding to the provided scripts, and optionally the transactions that spend those outputs if `txospenderindex` is 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 (https://github.com/bitcoin/bitcoin/pull/35531, https://github.com/bitcoin/bitcoin/pull/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 `txindex` disk 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 using `getblockfrompeer`. 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_hash` table). 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` (https://github.com/bitcoin/bitcoin/pull/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.
DrahtBot commented 2026-10-23 17:19:22 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK sedited, l0rinc, w0xlt, romanz, nullfail, arejula27, vasild, Rob1Ham
Stale ACK kravens, ViniciusCestarii

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36778 (AssumeUTXO: replace loadtxoutset RPC with a startup arg by l0rinc)
  • #36603 (Improve loadtxoutset performance by ajtowns)
  • #35713 (Remove boost as a unit test runner by rustaceanrob)
  • #31252 (rpc: print P2WSH and P2SH redem Script in getrawtransaction and getblock by polespinasa)

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. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • src/test/txoscriptindex_tests.cpp: index.Find(script_hash, -1, 95, remaining_bytes)
  • src/test/txoscriptindex_tests.cpp: index.Find(script_hash, 95, 90, remaining_bytes)
  • src/test/txoscriptindex_tests.cpp: index.Find(script_hash, 0, 102, remaining_bytes)
  • src/test/txoscriptindex_tests.cpp: index.Find(script_hash, 1, 2, remaining_bytes) (two locations)
  • src/test/txoscriptindex_tests.cpp: index.Find(script_hash, 1, 1, remaining_bytes) (three locations)
  • src/test/txoscriptindex_tests.cpp: index.Find(script_hash, 0, 100, remaining_bytes)
  • src/test/txoscriptindex_tests.cpp: index.Find(script_hash, 101, 101, remaining_bytes) (two locations)

Possible places where comparison-specific test macros should replace generic comparisons:

  • src/test/txoscriptindex_tests.cpp: BOOST_CHECK_THROW(invalid >> key_decoded, std::ios_base::failure) → Prefer BOOST_CHECK_EXCEPTION with a predicate checking the expected failure message.
  • src/test/txoscriptindex_tests.cpp: BOOST_CHECK_THROW((DataStream{} << txoscriptindex::DBKey{...}), std::ios_base::failure) for the oversized hash prefix → Prefer BOOST_CHECK_EXCEPTION with a message-checking predicate.
  • src/test/txoscriptindex_tests.cpp: BOOST_CHECK_THROW((DataStream{} << txoscriptindex::DBKey{...}), std::ios_base::failure) for the oversized height → Prefer BOOST_CHECK_EXCEPTION with a message-checking predicate.
  • src/test/txoscriptindex_tests.cpp: BOOST_CHECK_THROW(invalid >> decoded, std::ios_base::failure) → Prefer BOOST_CHECK_EXCEPTION with a predicate checking the expected failure message.
  • src/test/txoscriptindex_tests.cpp: BOOST_CHECK_THROW(DataStream{} << txoscriptindex::DBValue{}, std::ios_base::failure) → Prefer BOOST_CHECK_EXCEPTION with a message-checking predicate.
  • src/test/txoscriptindex_tests.cpp: BOOST_CHECK_THROW(DataStream{} << decoded, std::ios_base::failure) → Prefer BOOST_CHECK_EXCEPTION with a message-checking predicate.
  • src/test/txoscriptindex_tests.cpp: BOOST_CHECK_THROW(oversized >> decoded, std::ios_base::failure) → Prefer BOOST_CHECK_EXCEPTION with a message-checking predicate.
  • test/functional/rpc_getscripthistory.py: assert output["spent"] is spent → Prefer assert_equal(output["spent"], spent).

2026-11-28 23:41:24

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36629 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36629.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36629#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/36629#issuecomment-6372429119), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36629#issuecomment-6372628097), [w0xlt](https://github.com/bitcoin/bitcoin/pull/36629#issuecomment-6373603191), [romanz](https://github.com/bitcoin/bitcoin/pull/36629#pullrequestreview-5649167214), [nullfail](https://github.com/bitcoin/bitcoin/pull/36629#issuecomment-6502969751), [arejula27](https://github.com/bitcoin/bitcoin/pull/36629#pullrequestreview-5995881687), [vasild](https://github.com/bitcoin/bitcoin/pull/36629#issuecomment-7122833738), [Rob1Ham](https://github.com/bitcoin/bitcoin/pull/36629#issuecomment-7145588932) | | Stale ACK | [kravens](https://github.com/bitcoin/bitcoin/pull/36629#pullrequestreview-5702703273), [ViniciusCestarii](https://github.com/bitcoin/bitcoin/pull/36629#pullrequestreview-5789366235) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36778](https://github.com/bitcoin/bitcoin/pull/36778) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36778.svg"></sub> (AssumeUTXO: replace `loadtxoutset` RPC with a startup arg by l0rinc) * [#36603](https://github.com/bitcoin/bitcoin/pull/36603) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36603.svg"></sub> (Improve loadtxoutset performance by ajtowns) * [#35713](https://github.com/bitcoin/bitcoin/pull/35713) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35713.svg"></sub> (Remove boost as a unit test runner by rustaceanrob) * [#31252](https://github.com/bitcoin/bitcoin/pull/31252) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/31252.svg"></sub> (rpc: print P2WSH and P2SH redem Script in getrawtransaction and getblock by polespinasa) 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. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### LLM Linter (✨ experimental) Possible places where named args for integral literals may be used (e.g. `func(x, /*named_arg=*/0)` in C++, and `func(x, named_arg=0)` in Python): - `src/test/txoscriptindex_tests.cpp`: `index.Find(script_hash, -1, 95, remaining_bytes)` - `src/test/txoscriptindex_tests.cpp`: `index.Find(script_hash, 95, 90, remaining_bytes)` - `src/test/txoscriptindex_tests.cpp`: `index.Find(script_hash, 0, 102, remaining_bytes)` - `src/test/txoscriptindex_tests.cpp`: `index.Find(script_hash, 1, 2, remaining_bytes)` (two locations) - `src/test/txoscriptindex_tests.cpp`: `index.Find(script_hash, 1, 1, remaining_bytes)` (three locations) - `src/test/txoscriptindex_tests.cpp`: `index.Find(script_hash, 0, 100, remaining_bytes)` - `src/test/txoscriptindex_tests.cpp`: `index.Find(script_hash, 101, 101, remaining_bytes)` (two locations) Possible places where comparison-specific test macros should replace generic comparisons: - `src/test/txoscriptindex_tests.cpp`: `BOOST_CHECK_THROW(invalid >> key_decoded, std::ios_base::failure)` → Prefer `BOOST_CHECK_EXCEPTION` with a predicate checking the expected failure message. - `src/test/txoscriptindex_tests.cpp`: `BOOST_CHECK_THROW((DataStream{} << txoscriptindex::DBKey{...}), std::ios_base::failure)` for the oversized hash prefix → Prefer `BOOST_CHECK_EXCEPTION` with a message-checking predicate. - `src/test/txoscriptindex_tests.cpp`: `BOOST_CHECK_THROW((DataStream{} << txoscriptindex::DBKey{...}), std::ios_base::failure)` for the oversized height → Prefer `BOOST_CHECK_EXCEPTION` with a message-checking predicate. - `src/test/txoscriptindex_tests.cpp`: `BOOST_CHECK_THROW(invalid >> decoded, std::ios_base::failure)` → Prefer `BOOST_CHECK_EXCEPTION` with a predicate checking the expected failure message. - `src/test/txoscriptindex_tests.cpp`: `BOOST_CHECK_THROW(DataStream{} << txoscriptindex::DBValue{}, std::ios_base::failure)` → Prefer `BOOST_CHECK_EXCEPTION` with a message-checking predicate. - `src/test/txoscriptindex_tests.cpp`: `BOOST_CHECK_THROW(DataStream{} << decoded, std::ios_base::failure)` → Prefer `BOOST_CHECK_EXCEPTION` with a message-checking predicate. - `src/test/txoscriptindex_tests.cpp`: `BOOST_CHECK_THROW(oversized >> decoded, std::ios_base::failure)` → Prefer `BOOST_CHECK_EXCEPTION` with a message-checking predicate. - `test/functional/rpc_getscripthistory.py`: `assert output["spent"] is spent` → Prefer `assert_equal(output["spent"], spent)`. <sup>2026-11-28 23:41:24</sup>
DrahtBot commented 2026-10-23 17:41:07 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task ASan + LSan + UBSan + integer: https://github.com/bitcoin/bitcoin/actions/runs/39994088566/job/120552982572
LLM reason (✨ experimental): CI failed because ordered_varint_tests triggered UBSan for an implicit uint64_t-to-uint8_t truncation in index/ordered_varint.h:55.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `ASan + LSan + UBSan + integer`: https://github.com/bitcoin/bitcoin/actions/runs/39994088566/job/120552982572</sub> <sub>LLM reason (✨ experimental): CI failed because `ordered_varint_tests` triggered UBSan for an implicit `uint64_t`-to-`uint8_t` truncation in `index/ordered_varint.h:55`.</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
First-time contributor

8 additional verified findings in the Review report.

Earlier concerns neither republished nor resolved: 3 suggestions. See the Run archive linked from the Review report for their assessments.

🟠 Minor · Stale txospenderindex rows can corrupt history after restart

After a crash and a reorg before index resynchronization, a stale spender returned first can make the new RPC report spent=false at asof or repeatedly fail in live mode.

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

🟠 Minor · A disconnect and reconnect can leave a successful history response incomplete

If the selected chain is disconnected and restored during one request, getscripthistory can successfully return missing or mixed confirmed results under the original asof hash.

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

🟠 Minor · The asof help understates the spender-index synchronization requirement

An otherwise available historical query is rejected while txospenderindex completes initial synchronization, even after it covers asof, although the help requires synchronization only through that block.

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

🟠 Minor · Duplicate txids lose their creation identity during spentness resolution

On chains permitting duplicate txids, such as regtest with delayed BIP34, the RPC can conflate separate output occurrences; no current production chain producing this input was identified.

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

🟠 Minor · Live spentness holds cs_main across all matching UTXO lookups

A trusted live query can hold cs_main across hundreds of thousands of UTXO lookups, delaying validation; the actual delay depends on cache and storage and was not measured.

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

🟠 Minor · Descriptor expansion and empty-history seeks escape meaningful work limits

A large multipath descriptor can allocate its entire expansion and drive millions of index seeks despite the 50 MiB read budget; latency and memory usage were not measured.

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

Review coverage was incomplete.


Reviewed: 88b7c0d90322 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:afedb19cca4c3b40d89514fb0c66b0c20e4f5d62 --> <!-- ralph-head:88b7c0d9032241c0426e0218e7bdf22bb609102d --> <!-- ralph-case:e5e0cf6d5dd4a29c6b089310e02e31569170ba1c8eb8d0610d66bd120506fc46 --> [8 additional verified findings in the Review report](<https://review.fish.foo/report/36629-88b7c0d9032241c0426e0218e7bdf22bb609102d-3293-15.html>). Earlier concerns neither republished nor resolved: 3 suggestions. See the Run archive linked from the Review report for their assessments. **🟠 Minor · Stale `txospenderindex` rows can corrupt history after restart** After a crash and a reorg before index resynchronization, a stale spender returned first can make the new RPC report `spent=false` at `asof` or repeatedly fail in live mode. Location: [`src/rpc/blockchain.cpp:4133`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/88b7c0d9032241c0426e0218e7bdf22bb609102d/src/rpc/blockchain.cpp#L4133>) (head). **🟠 Minor · A disconnect and reconnect can leave a successful history response incomplete** If the selected chain is disconnected and restored during one request, `getscripthistory` can successfully return missing or mixed confirmed results under the original `asof` hash. Location: [`src/rpc/blockchain.cpp:4280`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/88b7c0d9032241c0426e0218e7bdf22bb609102d/src/rpc/blockchain.cpp#L4280>) (head). **🟠 Minor · The `asof` help understates the spender-index synchronization requirement** An otherwise available historical query is rejected while `txospenderindex` completes initial synchronization, even after it covers `asof`, although the help requires synchronization only through that block. Location: [`src/rpc/blockchain.cpp:3895`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/88b7c0d9032241c0426e0218e7bdf22bb609102d/src/rpc/blockchain.cpp#L3895>) (head). **🟠 Minor · Duplicate txids lose their creation identity during spentness resolution** On chains permitting duplicate txids, such as regtest with delayed `BIP34`, the RPC can conflate separate output occurrences; no current production chain producing this input was identified. Location: [`src/rpc/blockchain.cpp:4133`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/88b7c0d9032241c0426e0218e7bdf22bb609102d/src/rpc/blockchain.cpp#L4133>) (head). **🟠 Minor · Live spentness holds `cs_main` across all matching UTXO lookups** A trusted live query can hold `cs_main` across hundreds of thousands of UTXO lookups, delaying validation; the actual delay depends on cache and storage and was not measured. Location: [`src/rpc/blockchain.cpp:4014`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/88b7c0d9032241c0426e0218e7bdf22bb609102d/src/rpc/blockchain.cpp#L4014>) (head). **🟠 Minor · Descriptor expansion and empty-history seeks escape meaningful work limits** A large multipath descriptor can allocate its entire expansion and drive millions of index seeks despite the 50 MiB read budget; latency and memory usage were not measured. Location: [`src/rpc/blockchain.cpp:3928`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/88b7c0d9032241c0426e0218e7bdf22bb609102d/src/rpc/blockchain.cpp#L3928>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`88b7c0d90322`](<https://git.fish.foo/bitcoin/bitcoin/commit/88b7c0d9032241c0426e0218e7bdf22bb609102d>) · [Review report](<https://review.fish.foo/report/36629-88b7c0d9032241c0426e0218e7bdf22bb609102d-3293-15.html>) · [Previous reports](<https://review.fish.foo/traces/36629/>) [permalink](<https://review.fish.foo/report/36629-88b7c0d9032241c0426e0218e7bdf22bb609102d-3293-15.html>)
sedited commented 2026-10-23 18:54:49 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
l0rinc commented 2026-10-23 19:05:41 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
w0xlt commented 2026-10-23 20:00:31 +00:00 (Migrated from github.com)

Strong Concept ACK

Strong Concept ACK
kravens (Migrated from github.com) reviewed 2026-10-23 22:56:57 +00:00
kravens (Migrated from github.com) left a comment

Concept ACK.

Reviewed 614302e7d1. 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 scripts or script_hashes depending on how the query was given (rpc/blockchain.cpp:3986). Hashing everything up front would leave one set and remove the branch.

  • When range is given, the descriptor is parsed twice: once at rpc/blockchain.cpp:3896 and again inside EvalDescriptorStringOrObject.

  • RawTransactionDoc changes the getrawtransaction help text:

    • blockhash moves below vsize_adjusted and gains "(omitted for mempool transactions)".
    • The hex description changes.
    • At verbosity 2, fee moves 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.

Concept ACK. Reviewed 614302e7d14a16fe28a2e8945fa99165693fcf94. 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: ```diff + 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 `scripts` or `script_hashes` depending on how the query was given (`rpc/blockchain.cpp:3986`). Hashing everything up front would leave one set and remove the branch. - When `range` is given, the descriptor is parsed twice: once at `rpc/blockchain.cpp:3896` and again inside `EvalDescriptorStringOrObject`. - `RawTransactionDoc` changes the `getrawtransaction` help text: - `blockhash` moves below `vsize_adjusted` and gains "(omitted for mempool transactions)". - The `hex` description changes. - At verbosity 2, `fee` moves 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.
romanz (Migrated from github.com) reviewed 2026-10-26 18:42:43 +00:00
romanz (Migrated from github.com) left a comment

Concept ACK, thanks!

Concept ACK, thanks!
romanz (Migrated from github.com) commented 2026-10-26 08:24:50 +00:00

SHA256(scriptPubKey)

Electrum 1.7.x protocol is now using scriptPubKey-based subscription and queries, so maybe it would simpler to avoid SHA256 here?

> SHA256(scriptPubKey) Electrum 1.7.x protocol is now using [scriptPubKey-based subscription and queries](https://electrum-protocol.readthedocs.io/en/latest/protocol-changes.html#version-1-7), so maybe it would simpler to avoid SHA256 here?
ViniciusCestarii (Migrated from github.com) reviewed 2026-10-26 22:06:43 +00:00
ViniciusCestarii (Migrated from github.com) left a comment

Concept ACK. I skimmed the code but plan to take a deeper look. Commented 2 nits.

Concept ACK. I skimmed the code but plan to take a deeper look. Commented 2 nits.
ViniciusCestarii (Migrated from github.com) commented 2026-10-26 19:23:24 +00:00

In "rpc: add getscripthistory" cf9b981fcc

nit: getscripthistory help writes "Bitcoin byte order" which doesn't seem to be used elsewhere in the repo. I believe "reversed byte order" is a better fit

In "rpc: add getscripthistory" cf9b981fcc7ae52c7864beae35df5d60b5c322b4 nit: `getscripthistory` help writes "Bitcoin byte order" which doesn't seem to be used elsewhere in the repo. I believe "reversed byte order" is a better fit
Lines 3752-3766
ViniciusCestarii (Migrated from github.com) commented 2026-10-26 19:27:08 +00:00

In "rpc: add getscripthistory" cf9b981fcc

nit: getscripthistory help could say pruned_blocks blocks can be fetched with getblockfrompeer and then retry. It also could also state that pruned_blocks can contain false positives (blocks where no tx match the output script).

In "rpc: add getscripthistory" cf9b981fcc7ae52c7864beae35df5d60b5c322b4 nit: `getscripthistory` help could say `pruned_blocks` blocks can be fetched with `getblockfrompeer` and then retry. It also could also state that `pruned_blocks` can contain false positives (blocks where no tx match the output script).
andrewtoth commented 2026-10-29 14:31:35 +00:00 (Migrated from github.com)

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.

  • More compact index layout for duplicate scripts in the same block. Instead of one row per output, we group all identical outputs in the same block and serialize the offsets between each of them as the value corresponding to a single key for that script and block height.
  • Increase the prefix size from 5 bytes to 6 bytes. While 5 bytes is sufficient for the txindex, a collision in this index has a much worse case. If a script with none or a few outputs being looked up collides with an output that has millions of outputs, it will require scanning through all the block ranges and reading all the false positive outputs.
  • Added an asof optional parameter to fix a blockheight when paging through requests. This let's a caller make repeated queries that set the spentness of outputs based on the asof block.
  • Bound the undo and block reads to the lookup byte budget and throw if exceeded.
  • Expose tx_offset from txospenderindex and sort spenders with it.
  • Moved TxToJSON to rpc/rawtransaction.h
  • Various documentation changes, including release notes.
  • Added more test coverage to kill some mutants.
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. - More compact index layout for duplicate scripts in the same block. Instead of one row per output, we group all identical outputs in the same block and serialize the offsets between each of them as the value corresponding to a single key for that script and block height. - Increase the prefix size from 5 bytes to 6 bytes. While 5 bytes is sufficient for the txindex, a collision in this index has a much worse case. If a script with none or a few outputs being looked up collides with an output that has millions of outputs, it will require scanning through all the block ranges and reading all the false positive outputs. - Added an `asof` optional parameter to fix a blockheight when paging through requests. This let's a caller make repeated queries that set the spentness of outputs based on the `asof` block. - Bound the undo and block reads to the lookup byte budget and throw if exceeded. - Expose `tx_offset` from `txospenderindex` and sort spenders with it. - Moved `TxToJSON` to `rpc/rawtransaction.h` - Various documentation changes, including release notes. - Added more test coverage to kill some mutants.
andrewtoth (Migrated from github.com) reviewed 2026-10-29 14:32:38 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-29 14:32:38 +00:00

I'm not sure it will make it much simpler. I think it's worth it to keep this for backwards compatibility.

I'm not sure it will make it much simpler. I think it's worth it to keep this for backwards compatibility.
xyzconstant commented 2026-10-29 16:53:41 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
kravens (Migrated from github.com) reviewed 2026-10-29 18:10:27 +00:00
kravens (Migrated from github.com) left a comment

tACK 1fc5b618e3

Re-reviewed the changes since 614302e7 (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. Serialize rejects empty, non-increasing and out-of-block offsets, and Unserialize caps the count at MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT. Keys, values and transaction bodies are all charged to the budget.
  • Find keeps one block file open across rows and seeks with SEEK_SET, which keeps the AutoFile obfuscation position correct (streams.cpp:41). Matches still come back in (height, offset) order, so the by_position merge in the RPC holds.
  • CustomRemove erases the (prefix, height) key and a competing block at the same height overwrites it; txoscriptindex_reorg_erases_rows covers 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:

  1. 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 at rpc/blockchain.cpp:3954 and :3960 already 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 two BlockUntilSyncedToCurrentChain() calls when asof is given would let a server start paging old history while the index catches up. Fine as a follow-up.
  2. Explicit include_mempool=true together with asof is silently ignored (rpc/blockchain.cpp:3890). The help text says so, but an RPC_INVALID_PARAMETER would make the conflict visible to a caller who set both on purpose.
  3. Release notes. The summary mentions release notes, but the branch only touches doc/files.md. Did a doc/release-notes-36629.md miss the push?
  4. rpc: share transaction JSON helpers still has an empty commit body. It changes the getrawtransaction help layout (blockhash moves below vsize_adjusted, fee moves last at verbosity 2). One line in the message would help whoever bisects a help-text diff later.
  5. The "test ancestor commits" CI job died in p2p_segwit.py on 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.

tACK 1fc5b618e3693c824124dd4ee4c3c95e100e645d Re-reviewed the changes since 614302e7 (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. `Serialize` rejects empty, non-increasing and out-of-block offsets, and `Unserialize` caps the count at `MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT`. Keys, values and transaction bodies are all charged to the budget. - `Find` keeps one block file open across rows and seeks with `SEEK_SET`, which keeps the `AutoFile` obfuscation position correct (`streams.cpp:41`). Matches still come back in (height, offset) order, so the `by_position` merge in the RPC holds. - `CustomRemove` erases the (prefix, height) key and a competing block at the same height overwrites it; `txoscriptindex_reorg_erases_rows` covers 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: 1. **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 at `rpc/blockchain.cpp:3954` and `:3960` already 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 two `BlockUntilSyncedToCurrentChain()` calls when asof is given would let a server start paging old history while the index catches up. Fine as a follow-up. 2. **Explicit `include_mempool=true` together with `asof` is silently ignored** (`rpc/blockchain.cpp:3890`). The help text says so, but an `RPC_INVALID_PARAMETER` would make the conflict visible to a caller who set both on purpose. 3. **Release notes.** The summary mentions release notes, but the branch only touches `doc/files.md`. Did a `doc/release-notes-36629.md` miss the push? 4. **`rpc: share transaction JSON helpers` still has an empty commit body.** It changes the `getrawtransaction` help layout (`blockhash` moves below `vsize_adjusted`, `fee` moves last at verbosity 2). One line in the message would help whoever bisects a help-text diff later. 5. The "test ancestor commits" CI job died in `p2p_segwit.py` on 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.
DrahtBot commented 2026-11-02 16:19:24 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
ViniciusCestarii (Migrated from github.com) reviewed 2026-11-06 12:45:33 +00:00
ViniciusCestarii (Migrated from github.com) left a comment

tACK 1fc5b618e3

Looks good and well tested! Left some minor comments.

It took 121461 random generated addresses to find an address which collided a 6-byte prefix and created a false positive in a pruned mainnet node. The index also took some hours to finish indexing and 54GB of space as expected.

I also tried not indexing unspendable outputs since they serve a nicher purpose and it saved 1.4 GB (2.5% smaller). Not sure if this trade off is worth it.

tACK 1fc5b618e3693c824124dd4ee4c3c95e100e645d Looks good and well tested! Left some minor comments. It took 121461 random generated addresses to find an address which collided a 6-byte prefix and created a false positive in a pruned mainnet node. The index also took some hours to finish indexing and 54GB of space as expected. I also tried not indexing unspendable outputs since they serve a nicher purpose and it saved 1.4 GB (2.5% smaller). Not sure if this trade off is worth it.
ViniciusCestarii (Migrated from github.com) commented 2026-11-05 17:47:10 +00:00

In "index: add txoscriptindex" f9d4d0af81

Out of curiosity. Why Unserialize have the check offsets.size() >= MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT but Serialize doens't?

In "index: add txoscriptindex" f9d4d0af818b004a7fa6958878e5341cf0384818 Out of curiosity. Why `Unserialize` have the check `offsets.size() >= MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT` but `Serialize` doens't?
Lines 3890-3891
ViniciusCestarii (Migrated from github.com) commented 2026-11-05 17:53:51 +00:00

In "rpc: add getscripthistory" 1fc5b618e3

nit: since they are conflicting params, it could error if asof is set and include_mempool is also explict set as true instead of silently ignoring include_mempool=true.

In "rpc: add getscripthistory" 1fc5b618e3693c824124dd4ee4c3c95e100e645d nit: since they are conflicting params, it could error if asof is set and include_mempool is also explict set as true instead of silently ignoring include_mempool=true.
ViniciusCestarii (Migrated from github.com) commented 2026-11-05 17:43:18 +00:00

In "rpc: add getscripthistory" 1fc5b618e3

nit: renaming ScriptHistoryMatch::outputs to output_indexes would make this clearer.

In "rpc: add getscripthistory" 1fc5b618e3693c824124dd4ee4c3c95e100e645d nit: renaming ScriptHistoryMatch::outputs to output_indexes would make this clearer.
ViniciusCestarii (Migrated from github.com) commented 2026-11-05 17:49:08 +00:00

In "index: add txoscriptindex" f9d4d0af81

nit:

    // Two candidate transactions in one pruned block must produce one match with a null tx.
In "index: add txoscriptindex" f9d4d0af818b004a7fa6958878e5341cf0384818 nit: ```suggestion // Two candidate transactions in one pruned block must produce one match with a null tx. ```
craigraw commented 2026-11-10 12:50:36 +00:00 (Migrated from github.com)

The OP mentions supporting the Electrum protocol, so here are three requests that would make this more usable as an Electrum server's history backend. In the Electrum protocol the status hash is computed over txid:height in blockchain order, including position within a block, but verbosity 0 returns only txid, hex and blockhash. That means a separate height lookup, and an extra block read to order a funding and spending tx in the same block. Since ScriptHistoryMatch already has tx_offset, could each entry in both transactions and spending_transactions lists include height and tx_offset? Second, get_history and status only need txids and heights. An option to omit hex (e.g. include_hex: false, alongside include_spending_transactions) would keep responses small for long histories, and callers needing bodies could still fetch them. Third, adding value to each matching vout entry would let listunspent and get_balance be answered from the same response, so all the Electrum scripthash methods could be served without fetching transaction bodies.

The OP mentions supporting the Electrum protocol, so here are three requests that would make this more usable as an Electrum server's history backend. In the Electrum protocol the status hash is computed over `txid:height` in blockchain order, including position within a block, but verbosity 0 returns only txid, hex and blockhash. That means a separate height lookup, and an extra block read to order a funding and spending tx in the same block. Since `ScriptHistoryMatch` already has `tx_offset`, could each entry in both `transactions` and `spending_transactions` lists include `height` and `tx_offset`? Second, `get_history` and status only need txids and heights. An option to omit `hex` (e.g. `include_hex: false`, alongside `include_spending_transactions`) would keep responses small for long histories, and callers needing bodies could still fetch them. Third, adding `value` to each matching `vout` entry would let `listunspent` and `get_balance` be answered from the same response, so all the Electrum scripthash methods could be served without fetching transaction bodies.
DrahtBot commented 2026-11-11 04:11:34 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task lint: https://github.com/bitcoin/bitcoin/actions/runs/42956321459/job/130312194844
LLM reason (✨ experimental): CI failed because the lint check detected a new circular dependency between rpc/blockchain and rpc/rawtransaction.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `lint`: https://github.com/bitcoin/bitcoin/actions/runs/42956321459/job/130312194844</sub> <sub>LLM reason (✨ experimental): CI failed because the lint check detected a new circular dependency between `rpc/blockchain` and `rpc/rawtransaction`.</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
andrewtoth commented 2026-11-11 15:23:10 +00:00 (Migrated from github.com)

Thanks @kravens, @ViniciusCestarii, @romanz, @craigraw and ralph for the reviews and suggestions!

  • Increased the siphash prefix from 5 to 6 bytes. This added about 2 GB to total size. A collision with a script with many entries would make small lookups very expensive, as opposed to txindex where a collision is just a single extra tx read.
  • For Electrum: added height and tx_offset to confirmed entries, value to matching outputs, and include_hex option.
  • Marked the RPC and index experimental, and added release notes explaining that the interface and database format may change.
  • Added more test coverage, and other various changes.
Thanks @kravens, @ViniciusCestarii, @romanz, @craigraw and ralph for the reviews and suggestions! - Increased the siphash prefix from 5 to 6 bytes. This added about 2 GB to total size. A collision with a script with many entries would make small lookups very expensive, as opposed to txindex where a collision is just a single extra tx read. - For Electrum: added `height` and `tx_offset` to confirmed entries, `value` to matching outputs, and `include_hex` option. - Marked the RPC and index experimental, and added release notes explaining that the interface and database format may change. - Added more test coverage, and other various changes.
andrewtoth (Migrated from github.com) reviewed 2026-11-11 15:23:19 +00:00
Lines 3890-3891
andrewtoth (Migrated from github.com) commented 2026-11-11 15:23:19 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-11 15:23:24 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-11 15:23:24 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-11 15:23:37 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-11 15:23:37 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-11 15:29:18 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-11 15:29:18 +00:00

Serialize only receives offsets generated from validated blocks, so consensus limits already guaranteed that.

But, I've updated it to also check on Serialize, to guard against future regressions 👍.

`Serialize` only receives offsets generated from validated blocks, so consensus limits already guaranteed that. But, I've updated it to also check on `Serialize`, to guard against future regressions :+1:.
arejula27 (Migrated from github.com) reviewed 2026-11-20 16:50:42 +00:00
arejula27 (Migrated from github.com) left a 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.

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.
arejula27 (Migrated from github.com) commented 2026-11-20 16:22:55 +00:00

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.

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`.
Lines 418-433
arejula27 (Migrated from github.com) commented 2026-11-20 16:22:01 +00:00

getindexinfo now has one branch per index. GetSummary() is defined in BaseIndex, so this could loop over node.indexes instead. I don't expect many more indexes soon, so this is mostly about readability. Fine to leave it as is.

`getindexinfo` now has one branch per index. `GetSummary()` is defined in `BaseIndex`, so this could loop over `node.indexes` instead. I don't expect many more indexes soon, so this is mostly about readability. Fine to leave it as is.
arejula27 (Migrated from github.com) reviewed 2026-11-21 15:47:05 +00:00
Lines 418-433
arejula27 (Migrated from github.com) commented 2026-11-21 15:47:05 +00:00

I have just realized this is already done in #35474, which turns getindexinfo into a loop over node.indexes. Whichever of the two is merged last will pick it up when resolving the conflict, so nothing to do here, sorry

I have just realized this is already done in #35474, which turns `getindexinfo `into a loop over `node.indexes`. Whichever of the two is merged last will pick it up when resolving the conflict, so nothing to do here, sorry
DrahtBot commented 2026-11-23 10:31:22 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
vasild commented 2026-11-24 05:19:04 +00:00 (Migrated from github.com)

Concept ACK

@arejula27, no-index inspected all blocks in 0.45s and blockfilterindex inspected 85 blocks in ~5s, hmm?

Concept ACK @arejula27, no-index inspected all blocks in 0.45s and blockfilterindex inspected 85 blocks in ~5s, hmm?
vasild (Migrated from github.com) reviewed 2026-11-24 14:21:34 +00:00
vasild (Migrated from github.com) commented 2026-11-24 14:11:21 +00:00

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:

https://github.com/bitcoin/bitcoin/pull/36629#pullrequestreview-5635280324

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.

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: https://github.com/bitcoin/bitcoin/pull/36629#pullrequestreview-5635280324 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.
arejula27 commented 2026-11-24 16:05:31 +00:00 (Migrated from github.com)

@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, MatchAny hashes and sorts all ~8,000 wallet scripts (the fresh wallet has 8 descriptors, each with range 1000), so it costs about the same whether the block is empty or full and then reads less blocks. On mainnet, where reading a block is expensive, it should win against no index. That many scripts also gives ~1% false positives, which are the 65 extra blocks below.

index blocks read false positives
blockfilterindex 85 65
txoscriptindex 20 0

I think the blockfilterindex vs txoscriptindex comparison still holds. txoscriptindex only reads the blocks that really pay to the wallet, while on mainnet each false positive of the filter would be a full block read, so I expect the gap to grow, not shrink. I will do a proper bench in the future, this was just a preliminary run to present a follow-up idea :p

@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, `MatchAny` hashes and sorts all ~8,000 wallet scripts (the fresh wallet has 8 descriptors, each with range 1000), so it costs about the same whether the block is empty or full and then reads less blocks. On mainnet, where reading a block is expensive, it should win against no index. That many scripts also gives ~1% false positives, which are the 65 extra blocks below. | index | blocks read | false positives | | --- | --- | --- | | blockfilterindex | 85 | 65 | | txoscriptindex | 20 | 0 | I think the blockfilterindex vs txoscriptindex comparison still holds. `txoscriptindex` only reads the blocks that really pay to the wallet, while on mainnet each false positive of the filter would be a full block read, so I expect the gap to grow, not shrink. I will do a proper bench in the future, this was just a preliminary run to present a follow-up idea :p
Rob1Ham commented 2026-11-24 21:56:22 +00:00 (Migrated from github.com)

concept ACK

concept ACK
jaromil commented 2026-11-25 12:02:20 +00:00 (Migrated from github.com)

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 start_height changed the reported spender for the same output.

I used regtest with -testactivationheight=bip34@2. That let me use the height-102 encoding in the coinbase at height 1, before BIP34 activated. I spent its output at height 101, then mined the identical coinbase at height 102. BIP30 permits reusing the txid once all outputs of the earlier transaction have been spent. At tip 102, gettxout showed the new output with one confirmation, as expected.

Here’s what getscripthistory returned for output 0, with the mempool excluded throughout.

Query at tip 102 Expected Observed
Live, both occurrences Height 1 spent, height 102 unspent Both unspent
asof set to the tip hash, both occurrences Height 1 spent, height 102 unspent Height 1 spent, height 102 unspent
Same asof, with start_height=102 Height 102 unspent Spent by the transaction at height 101

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 asof, but it never checks whether the output had been created by the time of the spend.

I think the creation position needs to be carried through spender resolution. FindSpender currently returns the first spend it finds for an outpoint. If the later coinbase is eventually spent too, the lookup needs to keep looking past the earlier spend. I’d keep the full-history and single-page queries together in a regression test, since the full historical query on its own gives the expected answer.

I also noticed a separate issue with mempool locking. With include_mempool=true and no end_height, the RPC holds pool->cs while it sorts the entire mempool and scans every output, even for an address with no matches. I haven’t measured how long that holds the lock on a busy node, but transaction admission can wait behind it. Could we scan transaction references outside the lock and sort just the matches?

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 `start_height` changed the reported spender for the same output. I used regtest with `-testactivationheight=bip34@2`. That let me use the height-102 encoding in the coinbase at height 1, before BIP34 activated. I spent its output at height 101, then mined the identical coinbase at height 102. BIP30 permits reusing the txid once all outputs of the earlier transaction have been spent. At tip 102, `gettxout` showed the new output with one confirmation, as expected. Here’s what `getscripthistory` returned for output 0, with the mempool excluded throughout. | Query at tip 102 | Expected | Observed | | --- | --- | --- | | Live, both occurrences | Height 1 spent, height 102 unspent | Both unspent | | `asof` set to the tip hash, both occurrences | Height 1 spent, height 102 unspent | Height 1 spent, height 102 unspent | | Same `asof`, with `start_height=102` | Height 102 unspent | Spent by the transaction at height 101 | 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 `asof`, but it never checks whether the output had been created by the time of the spend. I think the creation position needs to be carried through spender resolution. `FindSpender` currently returns the first spend it finds for an outpoint. If the later coinbase is eventually spent too, the lookup needs to keep looking past the earlier spend. I’d keep the full-history and single-page queries together in a regression test, since the full historical query on its own gives the expected answer. I also noticed a separate issue with mempool locking. With `include_mempool=true` and no `end_height`, the RPC holds `pool->cs` while it sorts the entire mempool and scans every output, even for an address with no matches. I haven’t measured how long that holds the lock on a busy node, but transaction admission can wait behind it. Could we scan transaction references outside the lock and sort just the matches?
andrewtoth (Migrated from github.com) reviewed 2026-11-27 16:53:07 +00:00
Lines 418-433
andrewtoth (Migrated from github.com) commented 2026-11-27 16:53:07 +00:00

Done with the latest rebase.

Done with the latest rebase.
andrewtoth (Migrated from github.com) reviewed 2026-11-27 16:53:28 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-27 16:53:28 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-27 17:15:13 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-27 17:15:13 +00:00

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.

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.
andrewtoth commented 2026-11-27 17:51:08 +00:00 (Migrated from github.com)

Thanks @arejula27, @vasild, and @jaromil for the reviews, and @Rob1Ham for the concept ACK!

  • Replaced OrderedVarInt with big-endian-3-bytes. This holds for block heights up to 16,777,215 (~300 more years).
  • Store the best block hash atomically with index updates for restart recovery. This fixes an issue found by ralph where a crash followed by a reorg before restart could leave stale database entries.
  • Sort only matching mempool transactions, after releasing the lock.
  • Improved invalid address/hash/descriptor errors.
  • Rebased for #35474 and other changes, added more test coverage, various other changes.

git range-diff 6f1365e34f..d1f48f1e33 dd96035e03..7133c83615

I used regtest with -testactivationheight=bip34@2

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

Thanks @arejula27, @vasild, and @jaromil for the reviews, and @Rob1Ham for the concept ACK! - Replaced OrderedVarInt with big-endian-3-bytes. This holds for block heights up to 16,777,215 (~300 more years). - Store the best block hash atomically with index updates for restart recovery. This fixes an issue found by ralph where a crash followed by a reorg before restart could leave stale database entries. - Sort only matching mempool transactions, after releasing the lock. - Improved invalid address/hash/descriptor errors. - Rebased for #35474 and other changes, added more test coverage, various other changes. `git range-diff 6f1365e34f..d1f48f1e33 dd96035e03..7133c83615` > I used regtest with -testactivationheight=bip34@2 @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.
DrahtBot commented 2026-11-28 22:19:01 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/46191461959/job/141122956489
LLM reason (✨ experimental): lint_fail: IWYU modified include declarations, leaving a diff that caused the check to fail.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.

  • A functional or integration test failure may be intermittent or unrelated to this pull request.
    If no dedicated issue thread exists, create a new one to track it.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/46191461959/job/141122956489</sub> <sub>LLM reason (✨ experimental): lint_fail: IWYU modified include declarations, leaving a diff that caused the check to fail.</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening. * A functional or integration test failure may be intermittent or unrelated to this pull request. If no dedicated issue thread exists, create a new one to track it. Leave a comment here, if you need help tracking down a confusing failure. </details>
andrewtoth (Migrated from github.com) reviewed 2026-11-29 17:34:30 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-29 17:34:30 +00:00

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.

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.
andrewtoth commented 2026-11-29 17:47:45 +00:00 (Migrated from github.com)

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.

  • The previous reorg-on-unclean-shutdown fix was defective, and this updates it. Make txoscriptindex append-only like txindex, using a (height, gen) -> block_hash table and an optional VARINT(gen) suffix on DBKey. When a different block is indexed at the same height, it increments the gen suffix. Disconnected blocks are not removed. On lookup it also checks that the block hash at that (height, gen) is in the active chain, otherwise it skips it. This handles both reorgs and crash-then-reorg situations cleanly.
  • Added an extra byte to the key, that is split between the prefix and height. This supports heights up to ~268M, which is ~5100 years on mainnet. This reduces prefix collisions to ~1 in 2.8M, and ~1 in 217M against scripts appearing in >10 blocks.
  • Fully implemented @jaromil's suggestion to snapshot the mempool under the lock and scan and sort after releasing it.

git range-diff dd96035e03..7133c83615 dd96035e03..88b7c0d903

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. - The previous reorg-on-unclean-shutdown fix was defective, and this updates it. Make `txoscriptindex` append-only like `txindex`, using a `(height, gen) -> block_hash` table and an optional `VARINT(gen)` suffix on `DBKey`. When a different block is indexed at the same height, it increments the `gen` suffix. Disconnected blocks are not removed. On lookup it also checks that the block hash at that `(height, gen)` is in the active chain, otherwise it skips it. This handles both reorgs and crash-then-reorg situations cleanly. - Added an extra byte to the key, that is split between the prefix and height. This supports heights up to ~268M, which is ~5100 years on mainnet. This reduces prefix collisions to ~1 in 2.8M, and ~1 in 217M against scripts appearing in >10 blocks. - Fully implemented @jaromil's suggestion to snapshot the mempool under the lock and scan and sort after releasing it. `git range-diff dd96035e03..7133c83615 dd96035e03..88b7c0d903`
jaromil commented 2026-12-02 00:13:38 +00:00 (Migrated from github.com)

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

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 :^)

> [@jaromil](https://github.com/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. 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 :^)
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36629
No description provided.