mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 09:38:38 +00:00
Add output script index and corresponding script history RPC #36629
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36629
Loading…
Reference in a new issue
No description provided.
Delete branch "txoscriptindex"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 (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
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(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.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.
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:
loadtxoutsetRPC with a startup arg by l0rinc)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++, andfunc(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)→ PreferBOOST_CHECK_EXCEPTIONwith 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 → PreferBOOST_CHECK_EXCEPTIONwith a message-checking predicate.src/test/txoscriptindex_tests.cpp:BOOST_CHECK_THROW((DataStream{} << txoscriptindex::DBKey{...}), std::ios_base::failure)for the oversized height → PreferBOOST_CHECK_EXCEPTIONwith a message-checking predicate.src/test/txoscriptindex_tests.cpp:BOOST_CHECK_THROW(invalid >> decoded, std::ios_base::failure)→ PreferBOOST_CHECK_EXCEPTIONwith a predicate checking the expected failure message.src/test/txoscriptindex_tests.cpp:BOOST_CHECK_THROW(DataStream{} << txoscriptindex::DBValue{}, std::ios_base::failure)→ PreferBOOST_CHECK_EXCEPTIONwith a message-checking predicate.src/test/txoscriptindex_tests.cpp:BOOST_CHECK_THROW(DataStream{} << decoded, std::ios_base::failure)→ PreferBOOST_CHECK_EXCEPTIONwith a message-checking predicate.src/test/txoscriptindex_tests.cpp:BOOST_CHECK_THROW(oversized >> decoded, std::ios_base::failure)→ PreferBOOST_CHECK_EXCEPTIONwith a message-checking predicate.test/functional/rpc_getscripthistory.py:assert output["spent"] is spent→ Preferassert_equal(output["spent"], spent).2026-11-28 23:41:24
🚧 At least one of the CI tasks failed.
Task
ASan + LSan + UBSan + integer: https://github.com/bitcoin/bitcoin/actions/runs/39994088566/job/120552982572LLM reason (✨ experimental): CI failed because
ordered_varint_teststriggered UBSan for an implicituint64_t-to-uint8_ttruncation inindex/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.
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
txospenderindexrows can corrupt history after restartAfter a crash and a reorg before index resynchronization, a stale spender returned first can make the new RPC report
spent=falseatasofor 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,
getscripthistorycan successfully return missing or mixed confirmed results under the originalasofhash.Location:
src/rpc/blockchain.cpp:4280(head).🟠 Minor · The
asofhelp understates the spender-index synchronization requirementAn otherwise available historical query is rejected while
txospenderindexcompletes initial synchronization, even after it coversasof, 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_mainacross all matching UTXO lookupsA trusted live query can hold
cs_mainacross 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 reportspermalink
Concept ACK
Concept ACK
Strong Concept ACK
Concept ACK.
Reviewed
614302e7d1. I built it and rantxoscriptindex_tests,baseindex_tests,rpc_getscripthistory.py,rpc_misc.py,feature_init.pyandfeature_assumeutxo.py, all passing. I also did a manual regtest run: address, Electrum scripthash, rangedwpkh()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_jsonreads 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):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.
OrderedVarIntcould beBigEndianFormatter<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 whileOrderedVarIntgrows to 4, and BE3 goes up to height 16,777,215. I tried it locally. It removesordered_varint.hand its tests (+4/−210), and the PR's unit and functional tests still pass:3. Ordering spenders doesn't need a block read.
txospenderindexkeys already store aCDiskTxPos, and itsnTxOffsetgrows with the transaction's position in the block. I added it toTxoSpenderand sorted extra spenders by(height, tx_offset). That removes the grouping loop and theGetBlockCheckedcall (+6/−20).test_confirmed_transaction_orderstill passes. It fails if the offset is dropped from the comparison, so the test does cover this.4.
Findcould take the whole set of script hashes. Today the RPC callsFindonce per hash and merges results by(height, tx_offset). A transaction paying two scripts of one descriptor is read and charged twice;rpc_getscripthistory.pyrelies on this ("repeated reads of overlapping transactions exceed the work budget"). A multi-hashFindwould read each candidate once and drop bothScriptHistoryMatch::tx_offsetand theby_positionmerge. 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-txplaceholders would also remove the duplicated branch atindex/txoscriptindex.cpp:163and: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 astd::runtime_errorwith "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.cppgrows by ~530 lines to 4,238. The handler is one ~400-line lambda that opens with a 12-step index comment.src/rpc/scripthistory.cppwith one function per step would be easier to read and review.7.
TxToJSONis now declared inrawtransaction_util.h. That header belongs tobitcoin_common, which the wallet also links.TxToJSONtakes aChainstateand is still defined inrawtransaction.cppinbitcoin_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)".hexdescription changes.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.
Concept ACK, thanks!
Electrum 1.7.x protocol is now using scriptPubKey-based subscription and queries, so maybe it would simpler to avoid SHA256 here?
Concept ACK. I skimmed the code but plan to take a deeper look. Commented 2 nits.
In "rpc: add getscripthistory"
cf9b981fccnit:
getscripthistoryhelp writes "Bitcoin byte order" which doesn't seem to be used elsewhere in the repo. I believe "reversed byte order" is a better fitIn "rpc: add getscripthistory"
cf9b981fccnit:
getscripthistoryhelp could saypruned_blocksblocks can be fetched withgetblockfrompeerand then retry. It also could also state thatpruned_blockscan contain false positives (blocks where no tx match the output script).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.
asofoptional 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 theasofblock.tx_offsetfromtxospenderindexand sort spenders with it.TxToJSONtorpc/rawtransaction.hI'm not sure it will make it much simpler. I think it's worth it to keep this for backwards compatibility.
Concept ACK
tACK
1fc5b618e3Re-reviewed the changes since
614302e7(same base, no rebase). Built it and rantxoscriptindex_tests,txospenderindex_tests,ordered_varint_tests,caches_tests,baseindex_tests,rpc_getscripthistory.py,rpc_misc.py,rpc_gettxspendingprevout.py,feature_init.pyandfeature_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 (
TxToJSONheader) are fixed:tx_to_jsonnow charges the serialized undo and block (rpc/blockchain.cpp:4154,:4159),test_undo_size_limitcovers 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:
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.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 atrpc/blockchain.cpp:4097and 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 viaTxToUniv, so a page stays identical while the tip moves.test_asofexercises all of this.Observations, none blocking:
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.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.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.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.
🐙 This pull request conflicts with the target branch and needs rebase.
tACK
1fc5b618e3Looks 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.
In "index: add txoscriptindex"
f9d4d0af81Out of curiosity. Why
Unserializehave the checkoffsets.size() >= MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHTbutSerializedoens't?In "rpc: add getscripthistory"
1fc5b618e3nit: 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"
1fc5b618e3nit: renaming ScriptHistoryMatch::outputs to output_indexes would make this clearer.
In "index: add txoscriptindex"
f9d4d0af81nit:
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:heightin 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. SinceScriptHistoryMatchalready hastx_offset, could each entry in bothtransactionsandspending_transactionslists includeheightandtx_offset? Second,get_historyand status only need txids and heights. An option to omithex(e.g.include_hex: false, alongsideinclude_spending_transactions) would keep responses small for long histories, and callers needing bodies could still fetch them. Third, addingvalueto each matchingvoutentry would letlistunspentandget_balancebe answered from the same response, so all the Electrum scripthash methods could be served without fetching transaction bodies.🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/42956321459/job/130312194844LLM reason (✨ experimental): CI failed because the lint check detected a new circular dependency between
rpc/blockchainandrpc/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.
Thanks @kravens, @ViniciusCestarii, @romanz, @craigraw and ralph for the reviews and suggestions!
heightandtx_offsetto confirmed entries,valueto matching outputs, andinclude_hexoption.Done.
Done.
Done.
Serializeonly 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 👍.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,
importdescriptorswith timestamp 0 and range 1000 on a fresh wallet, 2 runs):This was a quick test, so don't take the results too seriously.
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 sayInput is not a valid address, scripthash or descriptor.getindexinfonow has one branch per index.GetSummary()is defined inBaseIndex, so this could loop overnode.indexesinstead. I don't expect many more indexes soon, so this is mostly about readability. Fine to leave it as is.I have just realized this is already done in #35474, which turns
getindexinfointo a loop overnode.indexes. Whichever of the two is merged last will pick it up when resolving the conflict, so nothing to do here, sorry🐙 This pull request conflicts with the target branch and needs rebase.
Concept ACK
@arejula27, no-index inspected all blocks in 0.45s and blockfilterindex inspected 85 blocks in ~5s, hmm?
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 vsuint32_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.
@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,
MatchAnyhashes 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.I think the blockfilterindex vs txoscriptindex comparison still holds.
txoscriptindexonly 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 :pconcept 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
start_heightchanged 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,gettxoutshowed the new output with one confirmation, as expected.Here’s what
getscripthistoryreturned for output 0, with the mempool excluded throughout.asofset to the tip hash, both occurrencesasof, withstart_height=102The 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.
FindSpendercurrently 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=trueand noend_height, the RPC holdspool->cswhile 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?Done with the latest rebase.
Done.
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.
Thanks @arejula27, @vasild, and @jaromil for the reviews, and @Rob1Ham for the concept ACK!
git range-diff 6f1365e34f..d1f48f1e33 dd96035e03..7133c83615@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.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/46191461959/job/141122956489LLM 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.
I added another byte to the key, but shared it with both the prefix and height.
This adds an extra 2GB to the db though, but I think the tradeoff makes sense.
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.
txoscriptindexappend-only liketxindex, using a(height, gen) -> block_hashtable and an optionalVARINT(gen)suffix onDBKey. When a different block is indexed at the same height, it increments thegensuffix. 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.git range-diff dd96035e03..7133c83615 dd96035e03..88b7c0d903Yep, 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 :^)