txindex: allow running in pruned mode #36002

Open
andrewtoth wants to merge 7 commits from txindex-prune into master AGit
andrewtoth commented 2026-08-18 00:01:24 +00:00 (Migrated from github.com)

After #35531, each txindex entry now points to the block hash containing the tx instead of the file location of the block. The block hash is then used to find the file position of the block to read the tx from. This allows us to determine the hash of the containing block even if the block is later pruned, and also determine the location of the block on disk if it is later downloaded again via getblockfrompeer.

This PR enables maintaining a txindex while pruned. If a txid lookup tries to read a tx from a pruned block, the hash of the missing block is surfaced to the caller.

If desired, a user may call getblockfrompeer using the returned hash to download the block, then try again successfully. The downloaded block will be added to the front of the block queue, so won't be pruned again for at least 288 blocks. Of course a larger prune setting is desired if lots of historical blocks will be read, and there are privacy issues if the user is looking up their own transactions. Ideally the blocks can be fetched from a trusted node or from random peers with decoy blocks fetched occasionally.

Resolves https://github.com/bitcoin/bitcoin/issues/10609, https://github.com/bitcoin/bitcoin/issues/12651, https://github.com/bitcoin/bitcoin/issues/16182, https://github.com/bitcoin/bitcoin/issues/35240

After #35531, each txindex entry now points to the block hash containing the tx instead of the file location of the block. The block hash is then used to find the file position of the block to read the tx from. This allows us to determine the hash of the containing block even if the block is later pruned, and also determine the location of the block on disk if it is later downloaded again via `getblockfrompeer`. This PR enables maintaining a txindex while pruned. If a txid lookup tries to read a tx from a pruned block, the hash of the missing block is surfaced to the caller. If desired, a user may call `getblockfrompeer` using the returned hash to download the block, then try again successfully. The downloaded block will be added to the front of the block queue, so won't be pruned again for at least 288 blocks. Of course a larger prune setting is desired if lots of historical blocks will be read, and there are privacy issues if the user is looking up their own transactions. Ideally the blocks can be fetched from a trusted node or from random peers with decoy blocks fetched occasionally. Resolves https://github.com/bitcoin/bitcoin/issues/10609, https://github.com/bitcoin/bitcoin/issues/12651, https://github.com/bitcoin/bitcoin/issues/16182, https://github.com/bitcoin/bitcoin/issues/35240
DrahtBot commented 2026-08-18 00:01:32 +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
ACK fjahr, optout21
Concept ACK ajtowns, arejula27, l0rinc

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:

  • #36990 (test: replace hard-coded RPC error codes by l0rinc)
  • #34132 (coins,dbwrapper: make database point-read failures fatal 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.

<!--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/36002 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36002.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36002#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 | | ---- | --------- | | ACK | [fjahr](https://github.com/bitcoin/bitcoin/pull/36002#issuecomment-7189460179), [optout21](https://github.com/bitcoin/bitcoin/pull/36002#pullrequestreview-6073047139) | | Concept ACK | [ajtowns](https://github.com/bitcoin/bitcoin/pull/36002#issuecomment-5405875239), [arejula27](https://github.com/bitcoin/bitcoin/pull/36002#pullrequestreview-5419883453), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36002#pullrequestreview-5045986593) | 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: * [#36990](https://github.com/bitcoin/bitcoin/pull/36990) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36990.svg"></sub> (test: replace hard-coded RPC error codes by l0rinc) * [#34132](https://github.com/bitcoin/bitcoin/pull/34132) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34132.svg"></sub> (coins,dbwrapper: make database point-read failures fatal 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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
DrahtBot commented 2026-08-18 00:14:51 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/32082864144/job/95549090994
LLM reason (✨ experimental): CI failed because IWYU reported an include issue (“Failure generated from IWYU”) in src/index/txindex.cpp.

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 `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/32082864144/job/95549090994</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU reported an include issue (“Failure generated from IWYU”) in `src/index/txindex.cpp`.</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>
l0rinc commented 2026-08-18 00:20:45 +00:00 (Migrated from github.com)

Big concept ACK \:D/

Big concept ACK \\:D/
ajtowns commented 2026-08-25 05:24:37 +00:00 (Migrated from github.com)

This allows us to determine the hash of the containing block even if the block is later pruned,

Hmm, I think that means the txindex starts off at ~30GB and grows at ~2.5GB/year indefinitely, so in 40 years' time might be 130GB. I guess that makes sense for nodes wanting to run a local block-explorer type setup; particularly if they keep a significant range of real blocks around; I think expected block usage is about 100GB per year, so 5 years worth of history would be half a terabyte, and probably cover most lookups.

I'd definitely prefer to have a -prunetxindex=1 option I could set, so that my prune=2000 (~1 week worth of blocks) node could lookup txs without needing to be reprovisioned with extra disk though. (With such an option enabled, should be feasible to setup a txindex on an already pruned node without redownloading blocks, I think)

Concept ACK, looks okay to me at first glance.

What's the (intended) behaviour if you enable txindex on a node that is already pruned? I think it will just hit FatalErrorf in BaseIndex::ProcessBlock and shut the node down?

> This allows us to determine the hash of the containing block even if the block is later pruned, Hmm, I think that means the txindex starts off at ~30GB and grows at ~2.5GB/year indefinitely, so in 40 years' time might be 130GB. I guess that makes sense for nodes wanting to run a local block-explorer type setup; particularly if they keep a significant range of real blocks around; I think expected block usage is about 100GB per year, so 5 years worth of history would be half a terabyte, and probably cover most lookups. I'd definitely prefer to have a `-prunetxindex=1` option I could set, so that my `prune=2000` (~1 week worth of blocks) node could lookup txs without needing to be reprovisioned with extra disk though. (With such an option enabled, should be feasible to setup a txindex on an already pruned node without redownloading blocks, I think) Concept ACK, looks okay to me at first glance. What's the (intended) behaviour if you enable txindex on a node that is already pruned? I think it will just hit `FatalErrorf` in `BaseIndex::ProcessBlock` and shut the node down?
andrewtoth commented 2026-08-29 20:03:54 +00:00 (Migrated from github.com)

What's the (intended) behaviour if you enable txindex on a node that is already pruned?

It's the same behavior if you try and start coinstatsindex or blockfilterindex after you've pruned past their last indexed block - the startup error:
Error: <index> best block of the index goes beyond pruned data (including undo data).
Please disable the index or reindex (which will download the whole blockchain again)

I'd definitely prefer to have a -prunetxindex=1 option I could set

I think that could be added as a follow-up, and would not conflict with this approach. We could just delete entries by sequence until the last sequence maps to a block we have not yet pruned. We would have to compact the db afterwards though. That way though you will just get a "tx not found" response for a historical lookup where the index has also been pruned past, instead of the block hash.

> What's the (intended) behaviour if you enable txindex on a node that is already pruned? It's the same behavior if you try and start `coinstatsindex` or `blockfilterindex` after you've pruned past their last indexed block - the startup error: `Error: <index> best block of the index goes beyond pruned data (including undo data).` `Please disable the index or reindex (which will download the whole blockchain again)` > I'd definitely prefer to have a -prunetxindex=1 option I could set I think that could be added as a follow-up, and would not conflict with this approach. We could just delete entries by sequence until the last sequence maps to a block we have not yet pruned. We would have to compact the db afterwards though. That way though you will just get a "tx not found" response for a historical lookup where the index has also been pruned past, instead of the block hash.
mzumsande (Migrated from github.com) reviewed 2026-09-07 15:04:12 +00:00
mzumsande (Migrated from github.com) left a comment

I wonder if the current design would be more helpful for users - or a genuine partial index that would only report on data of the non-pruned range and clean up old entries every now and then.

The alternative design would have the downside that it wouldn't report the possible blocks pruned txns might be in. Plus, it would need changes to baseindex, so more complicated.

However, it would have the big upside that it could be enabled on an already pruned node.

I wonder if the current design would be more helpful for users - or a genuine partial index that would only report on data of the non-pruned range and clean up old entries every now and then. The alternative design would have the downside that it wouldn't report the possible blocks pruned txns might be in. Plus, it would need changes to `baseindex`, so more complicated. However, it would have the big upside that it could be enabled on an already pruned node.
andrewtoth commented 2026-09-07 15:28:51 +00:00 (Migrated from github.com)

should be feasible to setup a txindex on an already pruned node without redownloading blocks

it would need changes to baseindex, so more complicated.

I think we can come up with something that would be interesting for both use cases, but without the complexity if we removed the "cleanup" part.

If we start with an empty index and are pruned, we set the locator to the last pruned block we have and sync. This way we get all the blocks indexed that we have, and future blocks that are pruned we can still return the block hash. When we want to "cleanup", we can just delete the txindex folder and restart.

the downside that it wouldn't report the possible blocks pruned txns might be in

Indeed, this has the downside that some existing txs will return not found, and some will return the pruned block hash. So it introduces some ambiguity into the result if you create the index while already pruned. It also does not bound the txindex disk size, but that has already been reduced significantly via #35531.

> should be feasible to setup a txindex on an already pruned node without redownloading blocks > it would need changes to baseindex, so more complicated. I think we can come up with something that would be interesting for both use cases, but without the complexity if we removed the "cleanup" part. If we start with an empty index and are pruned, we set the locator to the last pruned block we have and sync. This way we get all the blocks indexed that we have, and future blocks that are pruned we can still return the block hash. When we want to "cleanup", we can just delete the txindex folder and restart. > the downside that it wouldn't report the possible blocks pruned txns might be in Indeed, this has the downside that some existing txs will return not found, and some will return the pruned block hash. So it introduces some ambiguity into the result if you create the index while already pruned. It also does not bound the txindex disk size, but that has already been reduced significantly via #35531.
andrewtoth commented 2026-09-09 00:34:43 +00:00 (Migrated from github.com)

Thanks @ajtowns @mzumsande for your thoughts.

I've updated this change to also allow starting an index with an already pruned node. For any tx lookup miss where we don't get a block hash and started indexing after genesis, the response returns context in the error message that the tx may have been in a block that we never indexed.

We also return the starting block of the index in getindexinfo.

Regarding cleaning up entries in the txindex that are pruned, I don't think the complexity of this is worth it. If you are running pruned, you need at least 11 GB, and the txindex grows at about 2.5 GB per year. So every few months you can just nuke your index directory and rebuild. If you're running with a very low prune target, this shouldn't take more than a few minutes max (likely under a minute for -prune=2000).

Wdyt?

Thanks @ajtowns @mzumsande for your thoughts. I've updated this change to also allow starting an index with an already pruned node. For any tx lookup miss where we don't get a block hash and started indexing after genesis, the response returns context in the error message that the tx may have been in a block that we never indexed. We also return the starting block of the index in `getindexinfo`. Regarding cleaning up entries in the txindex that are pruned, I don't think the complexity of this is worth it. If you are running pruned, you need at least 11 GB, and the txindex grows at about 2.5 GB per year. So every few months you can just nuke your index directory and rebuild. If you're running with a very low prune target, this shouldn't take more than a few minutes max (likely under a minute for `-prune=2000`). Wdyt?
DrahtBot commented 2026-09-09 16:17:23 +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).
andrewtoth commented 2026-09-10 01:50:25 +00:00 (Migrated from github.com)

Rebased due to include conflicts with #36116.

Rebased due to `include` conflicts with #36116.
DrahtBot commented 2026-09-10 02:41:42 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/34426977165/job/102714188149
LLM reason (✨ experimental): CI failed because IWYU reported include/header issues (generated “Failure generated from IWYU” and exited non-zero after applying include changes).

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 `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/34426977165/job/102714188149</sub> <sub>LLM reason (✨ experimental): CI failed because **IWYU reported include/header issues** (generated “Failure generated from IWYU” and exited non-zero after applying include changes).</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>
arejula27 (Migrated from github.com) reviewed 2026-09-13 13:59:40 +00:00
arejula27 (Migrated from github.com) left a comment

Concept ACK.

I'm excited about this PR and I love the idea and the approach.

I have to go deeper into the code (just did a first review to see the idea), but meanwhile I have some questions.

BaseIndex now has two prune-related flags, AllowPrune() and AllowPartialHistory(), and they aren't really independent. Partial history is only ever set up on a pruned node, so (as I understand it) an index with AllowPartialHistory() but not AllowPrune() can't work. Would a single enum value express that relationship better, so the invariant lives in the type instead of a convention that a future index could break? Something like an AllowPrune enum with values Disallowed, FullHistory and PartialHistory.

Another option would be to move AllowPartialHistory() to TxIndex instead. As far as I can understand no other current index could set it to true anyway. Maybe your idea was for future ones?

Finally, I think one big addition with this is that we can even access txs on pruned nodes, since #35531 the index stores the block "virtual" reference rather than a file position , so the node knows exactly which block is missing. From there the caller can fetch that block with getblockfrompeer and retry the lookup. Right now those hashes only reach the caller inside the error string, so automating the fetch and retry means parsing the message. Would returning them as structured data be worth it? Or even an optional flag on getrawtransaction that requests the block for us in the same rpc call?

Concept ACK. I'm excited about this PR and I love the idea and the approach. I have to go deeper into the code (just did a first review to see the idea), but meanwhile I have some questions. `BaseIndex` now has two prune-related flags, `AllowPrune()` and `AllowPartialHistory()`, and they aren't really independent. Partial history is only ever set up on a pruned node, so (as I understand it) an index with `AllowPartialHistory()` but not `AllowPrune()` can't work. Would a single enum value express that relationship better, so the invariant lives in the type instead of a convention that a future index could break? Something like an `AllowPrune` enum with values `Disallowed`, `FullHistory` and `PartialHistory`. Another option would be to move `AllowPartialHistory()` to `TxIndex` instead. As far as I can understand no other current index could set it to true anyway. Maybe your idea was for future ones? Finally, I think one big addition with this is that we can even access txs on pruned nodes, since #35531 the index stores the block "virtual" reference rather than a file position , so the node knows exactly which block is missing. From there the caller can fetch that block with `getblockfrompeer` and retry the lookup. Right now those hashes only reach the caller inside the error string, so automating the fetch and retry means parsing the message. Would returning them as structured data be worth it? Or even an optional flag on `getrawtransaction` that requests the block for us in the same rpc call?
andrewtoth commented 2026-09-18 03:39:40 +00:00 (Migrated from github.com)

Thanks @arejula27. Those are good suggestions.

I renamed AllowPrune to GetPrunePolicy which returns an enum.

Another option would be to move AllowPartialHistory() to TxIndex instead. As far as I can understand no other current index could set it to true anyway. Maybe your idea was for future ones?

Yes it is for now, but if these changes are accepted we could do the same exercise for txospenderindex.

I added returning the pruned block hashes in an optional data field of the JSON error response.
I kept the REST error response as a string. All REST errors are strings, and I didn't want to introduce a special case. That would be a more invasive change, since all existing clients likely always expect plain/text string error responses. Of course that can be done as a follow-up if there is interest.

Thanks @arejula27. Those are good suggestions. I renamed `AllowPrune` to `GetPrunePolicy` which returns an enum. > Another option would be to move AllowPartialHistory() to TxIndex instead. As far as I can understand no other current index could set it to true anyway. Maybe your idea was for future ones? Yes it is for now, but if these changes are accepted we could do the same exercise for `txospenderindex`. I added returning the pruned block hashes in an optional `data` field of the JSON error response. I kept the REST error response as a string. All REST errors are strings, and I didn't want to introduce a special case. That would be a more invasive change, since all existing clients likely always expect `plain/text` string error responses. Of course that can be done as a follow-up if there is interest.
arejula27 commented 2026-09-18 07:24:18 +00:00 (Migrated from github.com)

Thx! Will try the exercise!
I am finishing the (deeper) code review, hope to post it soon :D

Thx! Will try the exercise! I am finishing the (deeper) code review, hope to post it soon :D
arejula27 (Migrated from github.com) reviewed 2026-09-24 11:01:20 +00:00
arejula27 (Migrated from github.com) left a comment

Thanks for applying the changes I asked for in the first review. I've done a deeper pass now, built it and ran txindex_tests and feature_txindex_prune.py, and have a few more notes.

gettxoutproof only reports the pruned block hash when the tx is fully spent: with an unspent output the block comes from the UTXO set and the error is still "Block not available (pruned data)", even though pblockindex is right there. Would it make sense to report that hash too?

When an existing txindex falls behind pruned data, the error still offers only "disable the index or reindex (which will download the whole blockchain again)", while deleting the index directory now gives a working partial index without downloading anything. Would it be worth mentioning that for indexes that allow partial history? Something like "%s best block of the index goes beyond pruned data. Please disable the index, delete its directory to rebuild it from the earliest block still on disk, or reindex (which will download the whole blockchain again)".

On partial history ( which i really like the idea), some users prune only to save block storage but could afford a full txindex (around 30 GB plus ~2.5 GB per year, as mentioned earlier in this PR). Today they would need a full reindex, which on a pruned node means downloading and validating the chain again. Would a follow-up similar to the background chainstate in assumeutxo make sense? Serving lookups from the partial index while a background task fetches the missing historical blocks, indexes them and discards them, moving first_block_height down until it reaches genesis.

Thanks for applying the changes I asked for in the first review. I've done a deeper pass now, built it and ran `txindex_tests` and `feature_txindex_prune.py`, and have a few more notes. `gettxoutproof` only reports the pruned block hash when the tx is fully spent: with an unspent output the block comes from the UTXO set and the error is still "Block not available (pruned data)", even though `pblockindex` is right there. Would it make sense to report that hash too? When an existing txindex falls behind pruned data, the error still offers only "disable the index or reindex (which will download the whole blockchain again)", while deleting the index directory now gives a working partial index without downloading anything. Would it be worth mentioning that for indexes that allow partial history? Something like `"%s best block of the index goes beyond pruned data. Please disable the index, delete its directory to rebuild it from the earliest block still on disk, or reindex (which will download the whole blockchain again)"`. On partial history ( which i really like the idea), some users prune only to save block storage but could afford a full txindex (around 30 GB plus ~2.5 GB per year, as mentioned earlier in this PR). Today they would need a full reindex, which on a pruned node means downloading and validating the chain again. Would a follow-up similar to the background chainstate in assumeutxo make sense? Serving lookups from the partial index while a background task fetches the missing historical blocks, indexes them and discards them, moving `first_block_height` down until it reaches genesis.
arejula27 (Migrated from github.com) commented 2026-09-24 10:00:14 +00:00

This struct represents two possible outcomes, the tx was found or it wasn't, but the type doesn't keep its fields consistent: it can hold a tx together with pruned_block_hashes, or a block_hash without a tx. My proposal is to use std::variant<TxFound, TxMiss> rather than one struct where the outcome is implied by which fields are set.

For example, wallet::TxState in src/wallet/transaction.h models a transaction's state the same way, as a variant of structs.

I suggest something like:

/// A transaction found in the mempool or in a block.
struct TxFound {
    CTransactionRef tx;
    /// Null if the transaction was found in the mempool.
    uint256 block_hash;
};

/// A lookup that did not find the transaction.
struct TxMiss {
    /// Blocks that may contain the transaction but were pruned. They may be false positives.
    std::vector<uint256> pruned_block_hashes;
};
This struct represents two possible outcomes, the tx was found or it wasn't, but the type doesn't keep its fields consistent: it can hold a `tx` together with `pruned_block_hashes`, or a `block_hash` without a `tx`. My proposal is to use `std::variant<TxFound, TxMiss>` rather than one struct where the outcome is implied by which fields are set. For example,[ `wallet::TxState` in `src/wallet/transaction.h`](https://github.com/bitcoin/bitcoin/blob/5c726f2058a4d5ac2c7d0dc8753d4ff125d03f15/src/wallet/transaction.h#L81) models a transaction's state the same way, as a variant of structs. I suggest something like: ```cpp /// A transaction found in the mempool or in a block. struct TxFound { CTransactionRef tx; /// Null if the transaction was found in the mempool. uint256 block_hash; }; /// A lookup that did not find the transaction. struct TxMiss { /// Blocks that may contain the transaction but were pruned. They may be false positives. std::vector<uint256> pruned_block_hashes; }; ```
arejula27 (Migrated from github.com) commented 2026-09-24 10:09:03 +00:00

nit: result has no tx and no block_hash in this branch, so this builds the same object again. Is there a reason not to return result; directly?

nit: `result` has no `tx` and no `block_hash` in this branch, so this builds the same object again. Is there a reason not to `return result;` directly?
arejula27 (Migrated from github.com) commented 2026-09-24 10:10:06 +00:00

nit: with a partial index the full error reads "Transaction not yet in block. The transaction may be in an earlier block not covered by this index, which starts at height N". "Not yet in block" suggests the tx is unconfirmed, while the added sentence suggests it may be confirmed in an old block. It sounds weird. Maybe use a neutral base message here too when the partial history detail is appended, e.g. "Transaction not found"?

nit: with a partial index the full error reads "Transaction not yet in block. The transaction may be in an earlier block not covered by this index, which starts at height N". "Not yet in block" suggests the tx is unconfirmed, while the added sentence suggests it may be confirmed in an old block. It sounds weird. Maybe use a neutral base message here too when the partial history detail is appended, e.g. "Transaction not found"?
arejula27 (Migrated from github.com) commented 2026-09-24 10:04:09 +00:00

I would add two more scenarios, as I have tested them and they are not covered:

  • A pruned block outside the active chain must not be reported (dropping the if (in_active_chain) condition leaves txindex_tests and feature_txindex_prune.py passing). The test mines a tx, invalidates its block so it becomes stale, prunes that block and checks the lookup returns no candidates.

  • Several pruned candidates must all be returned, which is what makes pruned_block_hashes a vector (keeping only the first hash also leaves both suites passing). The test forges an entry with a colliding prefix pointing at another block, the way txindex_collision_scan_path does, prunes both blocks and checks that both hashes come back.

I checked both cases with mutation testing, and can share the diff if it helps.

I would add two more scenarios, as I have tested them and they are not covered: - A pruned block outside the active chain must not be reported (dropping the `if (in_active_chain)` condition leaves `txindex_tests` and `feature_txindex_prune.py` passing). The test mines a tx, invalidates its block so it becomes stale, prunes that block and checks the lookup returns no candidates. - Several pruned candidates must all be returned, which is what makes `pruned_block_hashes` a vector (keeping only the first hash also leaves both suites passing). The test forges an entry with a colliding prefix pointing at another block, the way `txindex_collision_scan_path` does, prunes both blocks and checks that both hashes come back. I checked both cases with mutation testing, and can share the diff if it helps.
arejula27 (Migrated from github.com) reviewed 2026-09-24 21:45:26 +00:00
arejula27 (Migrated from github.com) commented 2026-09-24 21:45:26 +00:00

I would personally prefer use util::expected, but i think the project approach is to use it only over real errors (like BlockReadFailed kind of errors)

I would personally prefer use `util::expected`, but i think the project approach is to use it only over real errors (like `BlockReadFailed `kind of errors)
fjahr (Migrated from github.com) reviewed 2026-09-28 11:01:58 +00:00
fjahr (Migrated from github.com) left a comment

Would you mind splitting the PR into enabling plain prune mode and keep the partial index and all the related refactorings for a follow-up to that? I see that you added it as response to feedback but the plain prune mode should be a much simpler change, pretty much uncontroversial and relatively quick to merge. For the partial index there are a lot of edge cases imaginable, and it needs to be explained to the user pretty well. I added some comments with examples (from a very shallow first pass) that indicate to me that the partial may require more discussion and shouldn't block the plain prune mode. @arejula27 also has raised some good, related questions as well.

Would you mind splitting the PR into enabling plain prune mode and keep the partial index and all the related refactorings for a follow-up to that? I see that you added it as response to feedback but the plain prune mode should be a much simpler change, pretty much uncontroversial and relatively quick to merge. For the partial index there are a lot of edge cases imaginable, and it needs to be explained to the user pretty well. I added some comments with examples (from a very shallow first pass) that indicate to me that the partial may require more discussion and shouldn't block the plain prune mode. @arejula27 also has raised some good, related questions as well.
fjahr (Migrated from github.com) commented 2026-09-28 10:45:48 +00:00

I am not sure if this is enough to communicate what is happening to the user. Starting with -prune=XXX -txindex=1 may give you a partial or full txindex depending on if you had the index on before. Possibly the partial index could use an explicit opt-in? Not sure if that is needed but it seems to be closer to what @ajtowns had in mind originally as well when he asked for -prunetxindex=1.

I am not sure if this is enough to communicate what is happening to the user. Starting with `-prune=XXX -txindex=1` may give you a partial or full txindex depending on if you had the index on before. Possibly the partial index could use an explicit opt-in? Not sure if that is needed but it seems to be closer to what @ajtowns had in mind originally as well when he asked for `-prunetxindex=1`.
fjahr (Migrated from github.com) commented 2026-09-28 10:42:07 +00:00

synced: true doesn't really mean the same thing as before. So some clients which are not checking the new first_block_height may not get what they think they are getting.

`synced: true` doesn't really mean the same thing as before. So some clients which are not checking the new `first_block_height` may not get what they think they are getting.
fjahr (Migrated from github.com) commented 2026-09-28 11:01:08 +00:00

Because of what we do with f_txindex_ready above I am not sure all the infos in TxIndexMissErrorDetails would ever be relevant or possible to hit, e.g. at least the synced check and added message.

Because of what we do with `f_txindex_ready` above I am not sure all the infos in `TxIndexMissErrorDetails` would ever be relevant or possible to hit, e.g. at least the `synced` check and added message.
First-time contributor

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

🔵 Suggestion · Fetch-and-retry guidance omits retention and peer-disclosure caveats

The new getrawtransaction and gettxoutproof recovery guidance omits that manually fetched blocks can be re-pruned before retry and that the chosen peer learns which historical block was requested.

Location: src/rpc/rawtransaction.cpp:263 (head).

🔵 Suggestion · The series enables pruning before pruned lookups are handled

The intermediate commit enabling -prune with -txindex still labels an ordinary pruned lookup as data corruption; later commits fix this, making it a series review-flow issue rather than a head defect.

Location: src/init.cpp:1033 (commit).

🔵 Suggestion · Legacy-index startup advice omits the non-rebuilding option

When no blocks have been pruned, disabling pruning preserves the legacy index, but the startup error offers only deleting and rebuilding it without naming the directory.

Location: src/init.cpp:2020 (head).

Review coverage was incomplete.


Reviewed: a215a43f0331 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:0e8f70a86314bc73539b110d947c41d40c4886fc --> <!-- ralph-head:a215a43f03313583625ad93596d8e1ac9516d09a --> <!-- ralph-case:1fd8388448a64ec8e6e321bbb7f1360963536c02945e0de1f8e0a25e3c97fc38 --> Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · Fetch-and-retry guidance omits retention and peer-disclosure caveats** The new `getrawtransaction` and `gettxoutproof` recovery guidance omits that manually fetched blocks can be re-pruned before retry and that the chosen peer learns which historical block was requested. Location: [`src/rpc/rawtransaction.cpp:263`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a215a43f03313583625ad93596d8e1ac9516d09a/src/rpc/rawtransaction.cpp#L263>) (head). **🔵 Suggestion · The series enables pruning before pruned lookups are handled** The intermediate commit enabling `-prune` with `-txindex` still labels an ordinary pruned lookup as data corruption; later commits fix this, making it a series review-flow issue rather than a head defect. Location: src/init.cpp:1033 (commit). **🔵 Suggestion · Legacy-index startup advice omits the non-rebuilding option** When no blocks have been pruned, disabling pruning preserves the legacy index, but the startup error offers only deleting and rebuilding it without naming the directory. Location: [`src/init.cpp:2020`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a215a43f03313583625ad93596d8e1ac9516d09a/src/init.cpp#L2020>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`a215a43f0331`](<https://git.fish.foo/bitcoin/bitcoin/commit/a215a43f03313583625ad93596d8e1ac9516d09a>) · [Review report](<https://review.fish.foo/report/36002-a215a43f03313583625ad93596d8e1ac9516d09a-3159-13.html>) · [Previous reports](<https://review.fish.foo/traces/36002/>) [permalink](<https://review.fish.foo/report/36002-a215a43f03313583625ad93596d8e1ac9516d09a-3159-13.html>)
andrewtoth (Migrated from github.com) reviewed 2026-09-29 18:29:47 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-29 18:29:47 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-09-29 18:30:03 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-29 18:30:03 +00:00

Added these cases.

Added these cases.
andrewtoth commented 2026-09-29 18:41:42 +00:00 (Migrated from github.com)

Thank you for your reviews @arejula27 @fjahr.

I have updated this to remove the partial index, so this can only work if synced from genesis. Partially pruned indexes are out of scope and can be left for a follow-up.

I took the suggestions that still made sense in light of no partial pruning.

Thank you for your reviews @arejula27 @fjahr. I have updated this to remove the partial index, so this can only work if synced from genesis. Partially pruned indexes are out of scope and can be left for a follow-up. I took the suggestions that still made sense in light of no partial pruning.
andrewtoth (Migrated from github.com) reviewed 2026-09-29 18:43:12 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-29 18:43:12 +00:00

Thanks, but this is no longer relevant since we will not support partial indexes in this change.

Thanks, but this is no longer relevant since we will not support partial indexes in this change.
andrewtoth (Migrated from github.com) reviewed 2026-09-29 18:43:33 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-29 18:43:33 +00:00

Thanks, but this is no longer relevant since we will not support partial indexes in this change.

Thanks, but this is no longer relevant since we will not support partial indexes in this change.
andrewtoth (Migrated from github.com) reviewed 2026-09-29 18:43:43 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-29 18:43:43 +00:00

Thanks, but this is no longer relevant since we will not support partial indexes in this change.

Thanks, but this is no longer relevant since we will not support partial indexes in this change.
andrewtoth (Migrated from github.com) reviewed 2026-09-29 18:45:43 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-29 18:45:43 +00:00

Removed this, but also it seems no longer relevant since we will not support partial indexes in this change.

Removed this, but also it seems no longer relevant since we will not support partial indexes in this change.
optout21 commented 2026-09-29 22:07:42 +00:00 (Migrated from github.com)

Concept ACK

The ability to have a txindex holding information of all transactions even in case of a pruned node is a huge improvement, it makes pruned nodes much more capable.

I agree that the space concern due to "full" txindex in case of a pruned node is secondary for now, and can be addressed later. A pruned txindex containing only TXs from the non-pruned blocks is of limited use in general, I would say.

I'm a bit concerned that the interplay of different dimensions could lead to a complexity explosion. To limit that, some combinations have to be excluded outright. This is outside of the scope of this PR, but it's good to have in sight.

Just so far these dimensions have been mentioned:

  • blocks full or pruned
  • txindex enabled or not
  • txindex enabled before/with block pruning or after
  • txindex contains legacy keys or not
  • txindex is wished to be full or pruned.
Concept ACK The ability to have a txindex holding information of _all_ transactions even in case of a pruned node is a huge improvement, it makes pruned nodes much more capable. I agree that the space concern due to "full" txindex in case of a pruned node is secondary for now, and can be addressed later. A pruned txindex containing only TXs from the non-pruned blocks is of limited use in general, I would say. I'm a bit concerned that the interplay of different dimensions could lead to a complexity explosion. To limit that, some combinations have to be excluded outright. This is outside of the scope of this PR, but it's good to have in sight. Just so far these dimensions have been mentioned: - blocks full or pruned - txindex enabled or not - txindex enabled before/with block pruning or after - txindex contains legacy keys or not - txindex is wished to be full or pruned.
optout21 (Migrated from github.com) reviewed 2026-09-29 22:27:19 +00:00
optout21 (Migrated from github.com) left a comment

Looked through (5047435466), LGTM, left some minor comments.

Looked through (5047435466062e2dec15f9649d904adc739d84df), LGTM, left some minor comments.
optout21 (Migrated from github.com) commented 2026-09-29 22:03:02 +00:00

601669b rpc: report pruned blocks from GetTransaction:

What about if it exists in a block that was not indexed? More correct would be "in a block that has not been indexed or that has been pruned"

> [601669b](https://github.com/bitcoin/bitcoin/pull/36002/changes/601669b5ebe8e1708335fc724856b6f656a4db34) _rpc: report pruned blocks from GetTransaction_: What about if it exists in a block that was not indexed? More correct would be "in a block that has not been indexed or that has been pruned"
optout21 (Migrated from github.com) commented 2026-09-29 22:11:10 +00:00

5a90ecc txindex: return pruned block hashes from FindTx:

Nit: null here is actually {} or uint256::ZERO.

> [5a90ecc](https://github.com/bitcoin/bitcoin/pull/36002/changes/5a90ecce1c4428069c71a233c31346c678276c06) _txindex: return pruned block hashes from FindTx_: Nit: `null` here is actually `{}` or `uint256::ZERO`.
optout21 (Migrated from github.com) commented 2026-09-29 21:48:50 +00:00

5a90ecc txindex: return pruned block hashes from FindTx:

This struct is used both when a TXID is not found in the index, and when it is found, but the block is not found (pruned). This could be mentioned in a doc comment on the struct.
Also, on the next line the "was not found but" is redundant and a bit misleading, as TxMiss is used only in case the TX was not found.

> [5a90ecc](https://github.com/bitcoin/bitcoin/pull/36002/changes/5a90ecce1c4428069c71a233c31346c678276c06) _txindex: return pruned block hashes from FindTx_: This struct is used both when a TXID is not found in the index, and when it is found, but the block is not found (pruned). This could be mentioned in a doc comment on the struct. Also, on the next line the "was not found but" is redundant and a bit misleading, as `TxMiss` is used only in case the TX was not found.
optout21 (Migrated from github.com) commented 2026-09-29 21:41:14 +00:00

5a90ecc txindex: return pruned block hashes from FindTx:

I think here we could also return tx_offset_in_block; it may be useful in some usage scenarios to pass this to the caller as well.

> [5a90ecc](https://github.com/bitcoin/bitcoin/pull/36002/changes/5a90ecce1c4428069c71a233c31346c678276c06) _txindex: return pruned block hashes from FindTx_: I think here we could also return `tx_offset_in_block`; it may be useful in some usage scenarios to pass this to the caller as well.
optout21 (Migrated from github.com) commented 2026-09-29 21:31:20 +00:00

5a90ecc txindex: return pruned block hashes from FindTx:

I just wonder in what cases can a TX hash be present in the active chain more than once? Only duplicate coinbase (BIP30)?

> [5a90ecc](https://github.com/bitcoin/bitcoin/pull/36002/changes/5a90ecce1c4428069c71a233c31346c678276c06) _txindex: return pruned block hashes from FindTx_: I just wonder in what cases can a TX hash be present in the active chain more than once? Only duplicate coinbase (BIP30)?
Lines 60-61
optout21 (Migrated from github.com) commented 2026-09-29 21:51:36 +00:00

5a90ecc txindex: return pruned block hashes from FindTx:

Nit: For clarity it would be better to separate 3 cases: found, found in pruned block, and not found at all in the index.

> [5a90ecc](https://github.com/bitcoin/bitcoin/pull/36002/changes/5a90ecce1c4428069c71a233c31346c678276c06) _txindex: return pruned block hashes from FindTx_: Nit: For clarity it would be better to separate 3 cases: found, found in pruned block, and not found at all in the index.
optout21 (Migrated from github.com) commented 2026-09-29 21:20:56 +00:00

d3bc095 txindex: allow prune mode when there are no legacy entries:

If blocks are pruned, the rebuilt txindex will be pruned. The other option is to also restart block download; that way the txindex will be full. If that's the case, is this worth mentioning as well?

> [d3bc095](https://github.com/bitcoin/bitcoin/pull/36002/changes/d3bc095ab219c8c0c92266483b2e02e8fa00d05e) _txindex: allow prune mode when there are no legacy entries_: If blocks are pruned, the rebuilt txindex will be pruned. The other option is to also restart block download; that way the txindex will be full. If that's the case, is this worth mentioning as well?
andrewtoth (Migrated from github.com) reviewed 2026-09-30 02:37:08 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-30 02:37:08 +00:00

I'm not sure I follow. If this line is reached, the txindex is necessarily full and the node has not yet had any blocks pruned. This error will throw when a user wants to prune but still has a legacy txindex. By "restart block download" you mean do a -reindex? If so, that's not necessary since all blocks are still present and indexed.

I'm not sure I follow. If this line is reached, the txindex is necessarily full and the node has not yet had any blocks pruned. This error will throw when a user wants to prune but still has a legacy txindex. By "restart block download" you mean do a `-reindex`? If so, that's not necessary since all blocks are still present and indexed.
andrewtoth (Migrated from github.com) reviewed 2026-09-30 02:41:28 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-30 02:41:28 +00:00

Yes, the BIP30 excepted duplicate coinbases is the only case.
However, multiple colliding entries can point to different pruned blocks in the active chain. We don't know which one actually contains our transaction without downloading it from a peer.

Yes, the BIP30 excepted duplicate coinbases is the only case. However, multiple colliding entries can point to different pruned blocks in the active chain. We don't know which one actually contains our transaction without downloading it from a peer.
andrewtoth (Migrated from github.com) reviewed 2026-09-30 02:44:52 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-30 02:44:52 +00:00

Can you expand on what scenarios this will be useful for?
Would it be better to introduce new data in the response in the change that actually consumes it? Otherwise we will potentially introduce dead code into the codebase.

Can you expand on what scenarios this will be useful for? Would it be better to introduce new data in the response in the change that actually consumes it? Otherwise we will potentially introduce dead code into the codebase.
andrewtoth (Migrated from github.com) reviewed 2026-09-30 02:48:50 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-30 02:48:50 +00:00

Technically it is used when the transaction is not found in the index, but it may be found in a specific block hash. We don't actually know if it is in that block. The node will have to download that block to find out. It is possible after downloading that the transaction does not actually exist in that block, and then the subsequent result will be a TxMiss with an empty pruned_block_hashes vector.

Technically it is used when the transaction is not found in the index, but it *may* be found in a specific block hash. We don't actually know if it is in that block. The node will have to download that block to find out. It is possible after downloading that the transaction does not actually exist in that block, and then the subsequent result will be a `TxMiss` with an empty `pruned_block_hashes` vector.
andrewtoth (Migrated from github.com) reviewed 2026-09-30 02:52:48 +00:00
Lines 60-61
andrewtoth (Migrated from github.com) commented 2026-09-30 02:52:48 +00:00

Technically the tx can be found, or not found. If not found and we return one or more block hashes, it may be in one of those blocks, or not.

Technically the tx can be found, or not found. If not found and we return one or more block hashes, it *may* be in one of those blocks, or not.
andrewtoth (Migrated from github.com) reviewed 2026-09-30 03:00:31 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-30 03:00:31 +00:00

We intend the caller to check for uint256::IsNull(), which is technically uint256::ZERO. But, I think it's clearer to specify null here for that reason.

We intend the caller to check for `uint256::IsNull()`, which is technically `uint256::ZERO`. But, I think it's clearer to specify `null` here for that reason.
optout21 (Migrated from github.com) reviewed 2026-09-30 08:17:07 +00:00
optout21 (Migrated from github.com) left a comment

Thanks for the replies, @andrewtoth. I've realized some of my comments make little sense, as I assumed a "partial txindex" is possible; a txindex that has not processed some block range (on a pruned, synced node). This state is not possible through any sequence of node restarts and feature enabling/disabling. (It may be possible through some forced inconsistent state on disk, but it's fair to treat those as error.)

To summarize in a table:

Pruned? TXID found?
(min. 1 TXID prefix matches)
TX found?
(and it matches)
Result, semantics
No No -- The TX is not present in any of the block of the active chain.
Miss is returned.
No Yes No The TXID match is a false positive. The TX is not present in any of the block of the active chain.
Miss is returned.
No Yes Yes The block exists, TX found.
TX and its block hash is returned.
Yes No -- The TX is not present in any of the block of the active chain.
Miss is returned.
Yes Yes No The block hash is known, but either the block is not found (pruned), or it is, but the tx does not match (false positive).
Miss with a list of potential block hashes is returned (may be empty, e.g. only false positives).
Yes Yes Yes The block hash is known, the block is found.
TX and its block hash is returned.

I went through the comments having in mind the impossibility of partial index, sorry for the burnt cycles.
The implementation is quite solid.

Thanks for the replies, @andrewtoth. I've realized some of my comments make little sense, as I assumed a "partial txindex" is possible; a txindex that has not processed some block range (on a pruned, synced node). This state is not possible through any sequence of node restarts and feature enabling/disabling. (It may be possible through some forced inconsistent state on disk, but it's fair to treat those as error.) To summarize in a table: | Pruned? | TXID found? <br>(min. 1 TXID prefix matches) | TX found?<br>(and it matches) | Result, semantics | |---------|-------------|-----------|--------------------| | No | No | -- | The TX is not present in any of the block of the active chain. <br>Miss is returned. | | No | Yes | No | The TXID match is a false positive. The TX is not present in any of the block of the active chain. <br>Miss is returned. | No | Yes | Yes | The block exists, TX found. <br>TX and its block hash is returned. | | Yes | No | -- | The TX is not present in any of the block of the active chain. <br>Miss is returned. | | Yes | Yes | No | The block hash is known, but either the block is not found (pruned), or it is, but the tx does not match (false positive). <br>Miss with a list of potential block hashes is returned (may be empty, e.g. only false positives). | | Yes | Yes | Yes | The block hash is known, the block is found. <br>TX and its block hash is returned. | I went through the comments having in mind the impossibility of partial index, sorry for the burnt cycles. The implementation is quite solid.
optout21 (Migrated from github.com) commented 2026-09-30 08:11:58 +00:00

Refined: "or is in a block that has been pruned (or has not been indexed yet)."

Refined: "or is in a block that has been pruned (or has not been indexed yet)."
optout21 (Migrated from github.com) commented 2026-09-30 08:12:52 +00:00

Fine as is, thanks.

Fine as is, thanks.
optout21 (Migrated from github.com) commented 2026-09-30 08:08:49 +00:00

I would've argued for a stronger conceptual distinction between "Not in the index" and the "In the index but in a pruned node", but I have realized, that, due to the potential prefix false positives, this is in fact not possible.

I would've argued for a stronger conceptual distinction between "Not in the index" and the "In the index but in a pruned node", but I have realized, that, due to the potential prefix false positives, this is in fact not possible.
optout21 (Migrated from github.com) commented 2026-09-30 08:01:57 +00:00

I've just recalled that TX pos has been added to our RPC to be able to return a specific part of the block data; and that electrs takes use of that.
A caller may want to retrieve blocks from another source, and need that information. But this doesn't make sense, as the node has all the infrastructure for redownloading blocks.
In conclusion, I'm not able to come up with a concrete use case for this, and you are right, then it's best to leave it.

I've just recalled that TX pos has been added to our RPC to be able to return a specific part of the block data; and that `electrs` takes use of that. A caller may want to retrieve blocks from another source, and need that information. But this doesn't make sense, as the node has all the infrastructure for redownloading blocks. In conclusion, I'm not able to come up with a concrete use case for this, and you are right, then it's best to leave it.
optout21 (Migrated from github.com) commented 2026-09-30 07:54:31 +00:00

Ok, so the main reason is potential false positives.
TXID duplication due to BIP30 may happen (but very unlikely).
TXID duplication in stale blocks is not the case, the in_active_chain check filters stale blocks.
Clear, thanks.

Ok, so the main reason is potential false positives. TXID duplication due to BIP30 may happen (but very unlikely). TXID duplication in stale blocks is not the case, the `in_active_chain` check filters stale blocks. Clear, thanks.
Lines 60-61
optout21 (Migrated from github.com) commented 2026-09-30 08:09:43 +00:00

Same as above: I would've argued for a stronger conceptual distinction between "Not in the index" and the "In the index but in a pruned node", but I have realized, that, due to the potential prefix false positives, this is in fact not possible.

Same as above: I would've argued for a stronger conceptual distinction between "Not in the index" and the "In the index but in a pruned node", but I have realized, that, due to the potential prefix false positives, this is in fact not possible.
optout21 (Migrated from github.com) commented 2026-09-30 07:49:36 +00:00

I was wrong, if blocks are pruned, and txindex is deleted, the node will fail with en error ("txindex best block of the index goes beyond pruned data").

To the claim "If this line is reached, the txindex is necessarily full and the node has not yet had any blocks pruned": I think some weird combinations can violate this.

Ex1: Old version, -txindex=1, no prune, fully synced to height H1; restart with -txindex=0 -prune=550 and sync for some time; upgrade and start with -txindex=1 -prune=550. There is an incomplete index with legacy entries, but blocks have been pruned.
Following the advice here will result in a node not starting (with "the index goes beyond pruned data").

Ex2: Start with an old synced unpruned node with no txindex; enable index (legacy); stop well before indexing completes; upgrade; restart with enabled prune.
In this case the if will be triggered with an incomplete index, but following the advice will work, because all blocks are still present.

The diagnostic and advice is not fully complete in Ex1 case, but since the sequence is very unlikely, and the result is non-critical (the node failure message will be shown), this should be fine.

Feel free to Resolve.

I was wrong, if blocks are pruned, and txindex is deleted, the node will fail with en error ("txindex best block of the index goes beyond pruned data"). To the claim "If this line is reached, the txindex is necessarily full and the node has not yet had any blocks pruned": I think some weird combinations can violate this. Ex1: Old version, -txindex=1, no prune, fully synced to height H1; restart with -txindex=0 -prune=550 and sync for some time; upgrade and start with -txindex=1 -prune=550. There is an incomplete index with legacy entries, but blocks have been pruned. Following the advice here will result in a node not starting (with "the index goes beyond pruned data"). Ex2: Start with an old synced unpruned node with no txindex; enable index (legacy); stop well before indexing completes; upgrade; restart with enabled prune. In this case the `if` will be triggered with an incomplete index, but following the advice will work, because all blocks are still present. The diagnostic and advice is not fully complete in Ex1 case, but since the sequence is very unlikely, and the result is non-critical (the node failure message will be shown), this should be fine. Feel free to Resolve.
andrewtoth (Migrated from github.com) reviewed 2026-09-30 14:55:33 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-30 14:55:33 +00:00

Ex1: Old version, -txindex=1, no prune, fully synced to height H1; restart with -txindex=0 -prune=550 and sync for some time; upgrade and start with -txindex=1 -prune=550. There is an incomplete index with legacy entries, but blocks have been pruned.
Following the advice here will result in a node not starting (with "the index goes beyond pruned data").

Thanks, this edge case makes sense to me. I updated the first commit to check for this and report the correct instructions, along with a regression test.

> Ex1: Old version, -txindex=1, no prune, fully synced to height H1; restart with -txindex=0 -prune=550 and sync for some time; upgrade and start with -txindex=1 -prune=550. There is an incomplete index with legacy entries, but blocks have been pruned. Following the advice here will result in a node not starting (with "the index goes beyond pruned data"). Thanks, this edge case makes sense to me. I updated the first commit to check for this and report the correct instructions, along with a regression test.
andrewtoth (Migrated from github.com) reviewed 2026-09-30 14:56:27 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-30 14:56:27 +00:00

Taken, thanks.

Taken, thanks.
andrewtoth commented 2026-09-30 15:47:15 +00:00 (Migrated from github.com)

Thanks @optout21 for your review. I took a few of your suggestions.

Thanks @optout21 for your review. I took a few of your suggestions.
optout21 (Migrated from github.com) reviewed 2026-10-05 11:01:57 +00:00
optout21 (Migrated from github.com) commented 2026-10-05 11:01:57 +00:00

9dfeaff txindex: allow prune mode when there are no legacy entries:

This string is not added to bitcoinstrings.cpp, while the next one is. May be missing.

> [9dfeaff](https://github.com/bitcoin/bitcoin/pull/36002/changes/9dfeaffd30ff21b8ad59f291bc32c898e260e4c7) _txindex: allow prune mode when there are no legacy entries_: This string is not added to `bitcoinstrings.cpp`, while the next one is. May be missing.
optout21 (Migrated from github.com) reviewed 2026-10-05 12:14:05 +00:00
optout21 (Migrated from github.com) left a comment

Reviewed be19bbac4e , left some comments.

Some general comments:

  • The RPC docs are not updated to explain the new behavior, and how possible block hashes are returned.
  • This change (esp. because of the RPC changes) may warrant a release note.
  • The REST interface has no structured return for possible block hashes.
  • The error.data doesn't show in bitcoin-cli output.
Reviewed be19bbac4eb7e6185c1113d4cc25632421fdba1d , left some comments. Some general comments: - The RPC docs are not updated to explain the new behavior, and how possible block hashes are returned. - This change (esp. because of the RPC changes) may warrant a release note. - The REST interface has no structured return for possible block hashes. - The error.data doesn't show in bitcoin-cli output.
optout21 (Migrated from github.com) commented 2026-10-05 12:08:27 +00:00

071a868 txindex: return pruned block hashes from FindTx:

Theoretically multiple false positives are possible for the same block, in which case a block hash will be included multiple times. The list could be de-duplicated.

> [071a868](https://github.com/bitcoin/bitcoin/pull/36002/changes/071a868de21e962f199094133fc1a4fe33c28e25) _txindex: return pruned block hashes from FindTx_: Theoretically multiple false positives are possible for the same block, in which case a block hash will be included multiple times. The list could be de-duplicated.
optout21 (Migrated from github.com) commented 2026-10-05 12:04:20 +00:00

3039c42 rpc: report pruned blocks from GetTransaction:

I wonder if this change may affect non-txindex cases as well, e.g. when a block has been downloaded by getblockfrompeer (block data but no undo), and the blockhash is provided.

> [3039c42](https://github.com/bitcoin/bitcoin/pull/36002/changes/3039c42b84a0ac3ce8e2dcc8e54866569f9e85fc) _rpc: report pruned blocks from GetTransaction_: I wonder if this change may affect non-txindex cases as well, e.g. when a block has been downloaded by `getblockfrompeer` (block data but no undo), and the blockhash is provided.
Lines 131-135
optout21 (Migrated from github.com) commented 2026-10-05 11:52:35 +00:00

3039c42 rpc: report pruned blocks from GetTransaction:

This if may trigger even in cases when txindex is not set at all, but hash is provided, or found in the UTXO set. In those cases the "Transaction may be in pruned block X." message is not correct. This looks like a changed error message, even in some cases independent of txindex. If the change is kept, it should be better documented.

> [3039c42](https://github.com/bitcoin/bitcoin/pull/36002/changes/3039c42b84a0ac3ce8e2dcc8e54866569f9e85fc) _rpc: report pruned blocks from GetTransaction_: This `if` may trigger even in cases when `txindex` is not set at all, but hash is provided, or found in the UTXO set. In those cases the "Transaction may be in pruned block X." message is not correct. This looks like a changed error message, even in some cases independent of txindex. If the change is kept, it should be better documented.
arejula27 (Migrated from github.com) reviewed 2026-10-05 20:46:52 +00:00
arejula27 (Migrated from github.com) left a comment

Tested be19bbac4e.

I agree with moving the partial index to a follow-up, it keeps this PR simpler. I still find it an interesting feature, I hope it isn't forgotten :D

I ran txindex_tests, feature_txindex_prune.py, feature_txindex_compatibility.py and feature_pruning.py, and they pass (except feature_pruning.py in a build without the wallet, see inline). I also went through the cases from @optout21's table manually on a testnet4 node synced from genesis with -prune=550 -txindex, at height 155266 with pruneheight 148133, and everything behaved as expected.

testnet4 commands and output

Node: bitcoind -testnet4 -prune=550 -txindex -rest, network disabled

# Node state
$ bitcoin-cli -testnet4 getblockchaininfo
  "blocks": 155266,
  "bestblockhash": "0000000009874248f2ff9bc8c6e26fe288a0e7e3bbb967bdab2ae6b8b0d553a1",
  "pruned": true,
  "pruneheight": 148133,

# A txid that is not in the index: plain not-found error (-5)
$ bitcoin-cli -testnet4 getrawtransaction 0000000000000000000000000000000000000000000000000000000000000001
error code: -5
error message:
No such mempool or blockchain transaction. Use gettransaction for wallet transactions.

# A tx in a recent block (155256) that still has its data on disk: returned normally
$ bitcoin-cli -testnet4 getrawtransaction df56e5ad93e9479ad96b4546c5d686c09ade3f1c1356a1035e3587dd90c14b4b 1
{
  "txid": "df56e5ad93e9479ad96b4546c5d686c09ade3f1c1356a1035e3587dd90c14b4b",
  ...
}

# A fully spent tx in a pruned block (122494): the txindex returns the block hash, from both getrawtransaction and gettxoutproof
$ bitcoin-cli -testnet4 getrawtransaction 01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac
error code: -1
error message:
Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e.

$ bitcoin-cli -testnet4 gettxoutproof '["01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac"]'
error code: -1
error message:
Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e.

# Same tx and block, passing the blockhash explicitly: gettxoutproof reports the pruned block, getrawtransaction does not
$ bitcoin-cli -testnet4 gettxoutproof '["01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac"]' 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e
error code: -1
error message:
Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e.

$ bitcoin-cli -testnet4 getrawtransaction 01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac 1 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e
error code: -1
error message:
Block not available

# A coinbase in a pruned block (147399) with an unspent output: gettxoutproof finds the block through the UTXO set and also reports it
$ bitcoin-cli -testnet4 gettxoutproof '["13d6d66879dacf0b0b2f2b8c3361399e15e5d81ad671d78e9a15bbeba9b6048a"]'
error code: -1
error message:
Transaction may be in pruned block 000000000000000286f38d79da8406e88f572b4298c9ef0c2879101b7b56757e.

# REST returns the same message as text, without the structured hash
$ curl -s http://127.0.0.1:48332/rest/tx/01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac.hex
Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e.
(HTTP 404)

# Fetch the pruned block from a peer and retry: the lookups now succeed
$ bitcoin-cli -testnet4 getblockfrompeer 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e 15
{
}
$ bitcoin-cli -testnet4 getrawtransaction 01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac 2
{
  "txid": "01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac",
  ...                      (no "fee" or "prevout", the block comes without undo data)
}
$ bitcoin-cli -testnet4 gettxoutproof '["01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac"]'
0060e42735e2e66485d2ab215e53a1ec2d34a8197e249e1398a8e64ba5fca705...

I also noticed that ProcessPSBT now goes through GetTransaction, so it looks in the mempool before the txindex (this is a behavioral change). I measured utxoupdatepsbt and descriptorprocesspsbt against the base commit with 2500 txs in the mempool . I saw no time difference, I'm not sure if this needs further analysis (I think it's fine, but let me know).

Left a couple of comments below, these should be my last ones. Once they're addressed I'm happy to ACK.

Tested be19bbac4eb7e6185c1113d4cc25632421fdba1d. I agree with moving the partial index to a follow-up, it keeps this PR simpler. I still find it an interesting feature, I hope it isn't forgotten :D I ran `txindex_tests`, `feature_txindex_prune.py`, `feature_txindex_compatibility.py` and `feature_pruning.py`, and they pass (except `feature_pruning.py` in a build without the wallet, see inline). I also went through the cases from @optout21's table manually on a testnet4 node synced from genesis with `-prune=550 -txindex`, at height 155266 with `pruneheight` 148133, and everything behaved as expected. <details> <summary>testnet4 commands and output</summary> Node: `bitcoind -testnet4 -prune=550 -txindex -rest`, network disabled ``` # Node state $ bitcoin-cli -testnet4 getblockchaininfo "blocks": 155266, "bestblockhash": "0000000009874248f2ff9bc8c6e26fe288a0e7e3bbb967bdab2ae6b8b0d553a1", "pruned": true, "pruneheight": 148133, # A txid that is not in the index: plain not-found error (-5) $ bitcoin-cli -testnet4 getrawtransaction 0000000000000000000000000000000000000000000000000000000000000001 error code: -5 error message: No such mempool or blockchain transaction. Use gettransaction for wallet transactions. # A tx in a recent block (155256) that still has its data on disk: returned normally $ bitcoin-cli -testnet4 getrawtransaction df56e5ad93e9479ad96b4546c5d686c09ade3f1c1356a1035e3587dd90c14b4b 1 { "txid": "df56e5ad93e9479ad96b4546c5d686c09ade3f1c1356a1035e3587dd90c14b4b", ... } # A fully spent tx in a pruned block (122494): the txindex returns the block hash, from both getrawtransaction and gettxoutproof $ bitcoin-cli -testnet4 getrawtransaction 01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac error code: -1 error message: Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e. $ bitcoin-cli -testnet4 gettxoutproof '["01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac"]' error code: -1 error message: Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e. # Same tx and block, passing the blockhash explicitly: gettxoutproof reports the pruned block, getrawtransaction does not $ bitcoin-cli -testnet4 gettxoutproof '["01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac"]' 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e error code: -1 error message: Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e. $ bitcoin-cli -testnet4 getrawtransaction 01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac 1 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e error code: -1 error message: Block not available # A coinbase in a pruned block (147399) with an unspent output: gettxoutproof finds the block through the UTXO set and also reports it $ bitcoin-cli -testnet4 gettxoutproof '["13d6d66879dacf0b0b2f2b8c3361399e15e5d81ad671d78e9a15bbeba9b6048a"]' error code: -1 error message: Transaction may be in pruned block 000000000000000286f38d79da8406e88f572b4298c9ef0c2879101b7b56757e. # REST returns the same message as text, without the structured hash $ curl -s http://127.0.0.1:48332/rest/tx/01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac.hex Transaction may be in pruned block 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e. (HTTP 404) # Fetch the pruned block from a peer and retry: the lookups now succeed $ bitcoin-cli -testnet4 getblockfrompeer 00000000000000000138e178873369c3b371331e29aa6038105f992ef539741e 15 { } $ bitcoin-cli -testnet4 getrawtransaction 01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac 2 { "txid": "01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac", ... (no "fee" or "prevout", the block comes without undo data) } $ bitcoin-cli -testnet4 gettxoutproof '["01da48b914d0c78825c9010654863d803c90d52cde9a0706997a9390725a24ac"]' 0060e42735e2e66485d2ab215e53a1ec2d34a8197e249e1398a8e64ba5fca705... ``` </details> I also noticed that `ProcessPSBT` now goes through `GetTransaction`, so it looks in the mempool before the txindex (this is a behavioral change). I measured `utxoupdatepsbt` and `descriptorprocesspsbt` against the base commit with 2500 txs in the mempool . I saw no time difference, I'm not sure if this needs further analysis (I think it's fine, but let me know). Left a couple of comments below, these should be my last ones. Once they're addressed I'm happy to ACK.
arejula27 (Migrated from github.com) commented 2026-10-05 20:07:27 +00:00

With an explicit blockhash whose block is pruned, gettxoutproof now returns Transaction may be in pruned block <hash>., while getrawtransaction still returns Block not available. Is there a reason to treat these two cases differently?

With an explicit blockhash whose block is pruned, `gettxoutproof` now returns `Transaction may be in pruned block <hash>.`, while `getrawtransaction` still returns `Block not available`. Is there a reason to treat these two cases differently?
arejula27 (Migrated from github.com) commented 2026-10-05 20:04:40 +00:00

I ran this test in a build without the wallet (-DENABLE_WALLET=OFF) and it fails. The reason is that this expectation now relies on node0 having pruned blocks before this step, which only happens in the wallet-only rescan tests, so without the wallet nothing gets pruned. Could this step prune explicitly first (e.g. with pruneblockchain), or move the case to feature_txindex_prune.py, which already prunes?

I ran this test in a build without the wallet (`-DENABLE_WALLET=OFF`) and it fails. The reason is that this expectation now relies on node0 having pruned blocks before this step, which only happens in the wallet-only rescan tests, so without the wallet nothing gets pruned. Could this step prune explicitly first (e.g. with `pruneblockchain`), or move the case to `feature_txindex_prune.py`, which already prunes?
DrahtBot commented 2026-10-06 00:26:56 +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).
andrewtoth (Migrated from github.com) reviewed 2026-10-09 00:03:27 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-09 00:03:27 +00:00

I removed them from bitcoinstrings.cpp. I believe that will be generated later.

I removed them from bitcoinstrings.cpp. I believe that will be generated later.
andrewtoth (Migrated from github.com) reviewed 2026-10-09 00:03:57 +00:00
Lines 134-138
andrewtoth (Migrated from github.com) commented 2026-10-09 00:03:57 +00:00

Updated documentation to reflect this.

Updated documentation to reflect this.
andrewtoth (Migrated from github.com) reviewed 2026-10-09 00:05:41 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-09 00:05:41 +00:00

I changed the TxMiss::pruned_block_hashes from a std::vector to a std::set to reflect this.

I changed the `TxMiss::pruned_block_hashes` from a `std::vector` to a `std::set` to reflect this.
andrewtoth (Migrated from github.com) reviewed 2026-10-09 00:07:48 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-09 00:07:48 +00:00

Yes, this fixes a bug without txindex as well. Previously, calling getrawtransaction with verbosity 2 and no undo data would result in an RPC error Undo data expected but can't be read. Now It will return the tx but without fee and prevout (these are listed as optional in the help text).

Yes, this fixes a bug without `txindex` as well. Previously, calling `getrawtransaction` with verbosity 2 and no undo data would result in an RPC error `Undo data expected but can't be read`. Now It will return the tx but without `fee` and `prevout` (these are listed as optional in the help text).
andrewtoth (Migrated from github.com) reviewed 2026-10-09 00:09:09 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-09 00:09:09 +00:00

Fixed this by using self.nodes[2] instead of self.nodes[0]. That node does always has pruned blocks.

Fixed this by using `self.nodes[2]` instead of `self.nodes[0]`. That node does always has pruned blocks.
andrewtoth (Migrated from github.com) reviewed 2026-10-09 00:11:26 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-09 00:11:26 +00:00

Fixed this so both cases return the same error.

Fixed this so both cases return the same error.
DrahtBot commented 2026-10-09 00:15:19 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/37862719885/job/113602028381
LLM reason (✨ experimental): CI failed because IWYU added a missing #include <set> in src/rest.cpp, leaving an uncommitted diff that the lint check rejects.

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 `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/37862719885/job/113602028381</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU added a missing `#include <set>` in `src/rest.cpp`, leaving an uncommitted diff that the lint check rejects.</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-10-09 00:23:56 +00:00 (Migrated from github.com)

Thanks @optout21 @arejula27 for your reviews. I have taken most of your suggestions.

Rebased due to https://github.com/bitcoin/bitcoin/pull/34729 and https://github.com/bitcoin/bitcoin/pull/36447.

  • Switched pruned_block_hashes from std::vector to std::set to ensure returned block hashes are unique.
  • Aligned behavior of getrawtransaction and gettxoutproof when a tx inside a pruned block is requested with either txindex or a provided block hash.
  • Updated help text for getrawtransaction and gettxoutproof.
  • Added release notes.

The REST interface has no structured return for possible block hashes.

I opted not to add structured errors for REST (https://github.com/bitcoin/bitcoin/pull/36002#issuecomment-5724803370):

I kept the REST error response as a string. All REST errors are strings, and I didn't want to introduce a special case. That would be a more invasive change, since all existing clients likely always expect plain/text string error responses. Of course that can be done as a follow-up if there is interest.

The error.data doesn't show in bitcoin-cli output.

I'm not sure this is necessary, since the error text will show the block hashes anyway. I left this alone.

I also noticed that ProcessPSBT now goes through GetTransaction, so it looks in the mempool before the txindex (this is a behavioral change). I measured utxoupdatepsbt and descriptorprocesspsbt against the base commit with 2500 txs in the mempool . I saw no time difference, I'm not sure if this needs further analysis (I think it's fine, but let me know).

Yes, I think this is ok. It aligns lookups with the other RPCs and REST endpoint.

git range-diff 619185d5ce..be19bbac4e acdb326934..23f14ab325

Thanks @optout21 @arejula27 for your reviews. I have taken most of your suggestions. Rebased due to https://github.com/bitcoin/bitcoin/pull/34729 and https://github.com/bitcoin/bitcoin/pull/36447. - Switched `pruned_block_hashes` from `std::vector` to `std::set` to ensure returned block hashes are unique. - Aligned behavior of `getrawtransaction` and `gettxoutproof` when a tx inside a pruned block is requested with either `txindex` or a provided block hash. - Updated help text for `getrawtransaction` and `gettxoutproof`. - Added release notes. > The REST interface has no structured return for possible block hashes. I opted not to add structured errors for REST (https://github.com/bitcoin/bitcoin/pull/36002#issuecomment-5724803370): > I kept the REST error response as a string. All REST errors are strings, and I didn't want to introduce a special case. That would be a more invasive change, since all existing clients likely always expect plain/text string error responses. Of course that can be done as a follow-up if there is interest. > The error.data doesn't show in bitcoin-cli output. I'm not sure this is necessary, since the error text will show the block hashes anyway. I left this alone. > I also noticed that ProcessPSBT now goes through GetTransaction, so it looks in the mempool before the txindex (this is a behavioral change). I measured utxoupdatepsbt and descriptorprocesspsbt against the base commit with 2500 txs in the mempool . I saw no time difference, I'm not sure if this needs further analysis (I think it's fine, but let me know). Yes, I think this is ok. It aligns lookups with the other RPCs and REST endpoint. `git range-diff 619185d5ce..be19bbac4e acdb326934..23f14ab325`
l0rinc (Migrated from github.com) requested changes 2026-10-14 02:43:11 +00:00
l0rinc (Migrated from github.com) left a comment

re-concept ACK, overall LGTM, left a few remaining suggestions, it's looks pretty good already.

re-concept ACK, overall LGTM, left a few remaining suggestions, it's looks pretty good already.
l0rinc (Migrated from github.com) commented 2026-10-12 12:36:13 +00:00

23f14ab doc: add release note for txindex pruning support:

This should probably be v32.

Name the first release without legacy entries
diff --git a/doc/release-notes-36002.md b/doc/release-notes-36002.md
index bbab16e2c9..ca4f96295f 100644
--- a/doc/release-notes-36002.md
+++ b/doc/release-notes-36002.md
@@ -2,7 +2,7 @@ Updated settings
 ----------------
 
 - The transaction index (`-txindex`) can now be used with pruning (`-prune`).
-  The index must be built from genesis; indexes built in a version prior to v31
+  The index must be built from genesis. Indexes built in a version prior to v32
   must be rebuilt first. (#36002)
 
 Updated RPCs
> [23f14ab](https://github.com/bitcoin/bitcoin/pull/36002/changes/23f14ab325054238b412d59ed5c4f319bfbadf17) _doc: add release note for txindex pruning support_: This should probably be v32. <details> <summary>Name the first release without legacy entries</summary> ```diff diff --git a/doc/release-notes-36002.md b/doc/release-notes-36002.md index bbab16e2c9..ca4f96295f 100644 --- a/doc/release-notes-36002.md +++ b/doc/release-notes-36002.md @@ -2,7 +2,7 @@ Updated settings ---------------- - The transaction index (`-txindex`) can now be used with pruning (`-prune`). - The index must be built from genesis; indexes built in a version prior to v31 + The index must be built from genesis. Indexes built in a version prior to v32 must be rebuilt first. (#36002) Updated RPCs ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:49:46 +00:00

23f14ab doc: add release note for txindex pruning support:

- `getrawtransaction` with verbosity 2 now omits `fee` and `prevout` instead of
  returning an error when the block is available but its undo data is not,
  e.g. after `getblockfrompeer`. (#36002)
> [23f14ab](https://github.com/bitcoin/bitcoin/pull/36002/changes/23f14ab325054238b412d59ed5c4f319bfbadf17) _doc: add release note for txindex pruning support_: ``` - `getrawtransaction` with verbosity 2 now omits `fee` and `prevout` instead of returning an error when the block is available but its undo data is not, e.g. after `getblockfrompeer`. (#36002) ```
l0rinc (Migrated from github.com) commented 2026-10-12 12:38:12 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

Given that GetTransaction also uses the result for mempool lookups we could move this one to node/.

Keep the shared lookup result under node
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index 4f26fa28ff..d14c02d88e 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -11,10 +11,10 @@
 #include <flatfile.h>
 #include <index/base.h>
 #include <index/disktxpos.h>
-#include <index/tx_lookup_result.h>
 #include <index/txindex_key.h>
 #include <interfaces/chain.h>
 #include <node/blockstorage.h>
+#include <node/tx_lookup_result.h>
 #include <primitives/block.h>
 #include <primitives/transaction.h>
 #include <random.h>
diff --git a/src/index/txindex.h b/src/index/txindex.h
index beb7d0e3db..c65a2433f0 100644
--- a/src/index/txindex.h
+++ b/src/index/txindex.h
@@ -6,7 +6,7 @@
 #define BITCOIN_INDEX_TXINDEX_H
 
 #include <index/base.h>
-#include <index/tx_lookup_result.h>
+#include <node/tx_lookup_result.h>
 #include <primitives/transaction.h>
 
 #include <cstddef>
diff --git a/src/node/transaction.cpp b/src/node/transaction.cpp
index 3e88d13d18..60338e9af0 100644
--- a/src/node/transaction.cpp
+++ b/src/node/transaction.cpp
@@ -6,18 +6,19 @@
 #include <node/transaction.h>
 
 #include <consensus/validation.h>
-#include <index/tx_lookup_result.h>
 #include <index/txindex.h>
 #include <net.h>
 #include <net_processing.h>
 #include <node/blockstorage.h>
 #include <node/context.h>
+#include <node/tx_lookup_result.h>
 #include <node/types.h>
 #include <policy/feerate.h>
 #include <txmempool.h>
 #include <validation.h>
 #include <validationinterface.h>
 
+#include <utility>
 #include <variant>
 
 namespace node {
diff --git a/src/node/transaction.h b/src/node/transaction.h
index 80149d0c0b..c05e6bd36b 100644
--- a/src/node/transaction.h
+++ b/src/node/transaction.h
@@ -6,7 +6,7 @@
 #define BITCOIN_NODE_TRANSACTION_H
 
 #include <common/messages.h>
-#include <index/tx_lookup_result.h>
+#include <node/tx_lookup_result.h>
 #include <node/types.h>
 #include <policy/feerate.h>
 #include <primitives/transaction.h>
diff --git a/src/index/tx_lookup_result.h b/src/node/tx_lookup_result.h
similarity index 87%
rename from src/index/tx_lookup_result.h
rename to src/node/tx_lookup_result.h
index 9cbb9f5312..9c1808d42c 100644
--- a/src/index/tx_lookup_result.h
+++ b/src/node/tx_lookup_result.h
@@ -2,8 +2,8 @@
 // Distributed under the MIT software license, see the accompanying
 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
 
-#ifndef BITCOIN_INDEX_TX_LOOKUP_RESULT_H
-#define BITCOIN_INDEX_TX_LOOKUP_RESULT_H
+#ifndef BITCOIN_NODE_TX_LOOKUP_RESULT_H
+#define BITCOIN_NODE_TX_LOOKUP_RESULT_H
 
 #include <primitives/transaction.h>
 #include <uint256.h>
@@ -28,4 +28,4 @@ struct TxMiss {
 /// Result of a transaction lookup that may be answered by the txindex.
 using TxLookupResult = std::variant<TxFound, TxMiss>;
 
-#endif // BITCOIN_INDEX_TX_LOOKUP_RESULT_H
+#endif // BITCOIN_NODE_TX_LOOKUP_RESULT_H
diff --git a/src/rest.cpp b/src/rest.cpp
index 7913c2d611..49676cf828 100644
--- a/src/rest.cpp
+++ b/src/rest.cpp
@@ -14,11 +14,11 @@
 #include <flatfile.h>
 #include <httpserver.h>
 #include <index/blockfilterindex.h>
-#include <index/tx_lookup_result.h>
 #include <index/txindex.h>
 #include <node/blockstorage.h>
 #include <node/context.h>
 #include <node/transaction.h>
+#include <node/tx_lookup_result.h>
 #include <primitives/block.h>
 #include <primitives/transaction.h>
 #include <rpc/blockchain.h>
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 8b94667857..1df1604803 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -15,7 +15,6 @@
 #include <crypto/common.h>
 #include <crypto/hex_base.h>
 #include <hash.h>
-#include <index/tx_lookup_result.h>
 #include <index/txindex.h>
 #include <kernel/chainparams.h>
 #include <key.h>
@@ -25,6 +24,7 @@
 #include <node/context.h>
 #include <node/psbt.h>
 #include <node/transaction.h>
+#include <node/tx_lookup_result.h>
 #include <policy/feerate.h>
 #include <primitives/block.h>
 #include <primitives/transaction.h>
diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp
index 8d2b0cb3c5..57f1cb2bb3 100644
--- a/src/rpc/txoutproof.cpp
+++ b/src/rpc/txoutproof.cpp
@@ -8,11 +8,11 @@
 #include <chain.h>
 #include <coins.h>
 #include <crypto/hex_base.h>
-#include <index/tx_lookup_result.h>
 #include <index/txindex.h>
 #include <merkleblock.h>
 #include <node/blockstorage.h>
 #include <node/transaction.h>
+#include <node/tx_lookup_result.h>
 #include <primitives/block.h>
 #include <primitives/transaction.h>
 #include <rpc/blockchain.h>
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index a2fe62b7a0..19bf438324 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -12,12 +12,12 @@
 #include <dbwrapper.h>
 #include <flatfile.h>
 #include <index/disktxpos.h>
-#include <index/tx_lookup_result.h>
 #include <index/txindex.h>
 #include <index/txindex_key.h>
 #include <interfaces/chain.h>
 #include <key.h>
 #include <node/blockstorage.h>
+#include <node/tx_lookup_result.h>
 #include <primitives/block.h>
 #include <script/script.h>
 #include <streams.h>
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: Given that `GetTransaction` also uses the result for mempool lookups we could move this one to `node/`. <details> <summary>Keep the shared lookup result under node</summary> ```diff diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp index 4f26fa28ff..d14c02d88e 100644 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -11,10 +11,10 @@ #include <flatfile.h> #include <index/base.h> #include <index/disktxpos.h> -#include <index/tx_lookup_result.h> #include <index/txindex_key.h> #include <interfaces/chain.h> #include <node/blockstorage.h> +#include <node/tx_lookup_result.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <random.h> diff --git a/src/index/txindex.h b/src/index/txindex.h index beb7d0e3db..c65a2433f0 100644 --- a/src/index/txindex.h +++ b/src/index/txindex.h @@ -6,7 +6,7 @@ #define BITCOIN_INDEX_TXINDEX_H #include <index/base.h> -#include <index/tx_lookup_result.h> +#include <node/tx_lookup_result.h> #include <primitives/transaction.h> #include <cstddef> diff --git a/src/node/transaction.cpp b/src/node/transaction.cpp index 3e88d13d18..60338e9af0 100644 --- a/src/node/transaction.cpp +++ b/src/node/transaction.cpp @@ -6,18 +6,19 @@ #include <node/transaction.h> #include <consensus/validation.h> -#include <index/tx_lookup_result.h> #include <index/txindex.h> #include <net.h> #include <net_processing.h> #include <node/blockstorage.h> #include <node/context.h> +#include <node/tx_lookup_result.h> #include <node/types.h> #include <policy/feerate.h> #include <txmempool.h> #include <validation.h> #include <validationinterface.h> +#include <utility> #include <variant> namespace node { diff --git a/src/node/transaction.h b/src/node/transaction.h index 80149d0c0b..c05e6bd36b 100644 --- a/src/node/transaction.h +++ b/src/node/transaction.h @@ -6,7 +6,7 @@ #define BITCOIN_NODE_TRANSACTION_H #include <common/messages.h> -#include <index/tx_lookup_result.h> +#include <node/tx_lookup_result.h> #include <node/types.h> #include <policy/feerate.h> #include <primitives/transaction.h> diff --git a/src/index/tx_lookup_result.h b/src/node/tx_lookup_result.h similarity index 87% rename from src/index/tx_lookup_result.h rename to src/node/tx_lookup_result.h index 9cbb9f5312..9c1808d42c 100644 --- a/src/index/tx_lookup_result.h +++ b/src/node/tx_lookup_result.h @@ -2,8 +2,8 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#ifndef BITCOIN_INDEX_TX_LOOKUP_RESULT_H -#define BITCOIN_INDEX_TX_LOOKUP_RESULT_H +#ifndef BITCOIN_NODE_TX_LOOKUP_RESULT_H +#define BITCOIN_NODE_TX_LOOKUP_RESULT_H #include <primitives/transaction.h> #include <uint256.h> @@ -28,4 +28,4 @@ struct TxMiss { /// Result of a transaction lookup that may be answered by the txindex. using TxLookupResult = std::variant<TxFound, TxMiss>; -#endif // BITCOIN_INDEX_TX_LOOKUP_RESULT_H +#endif // BITCOIN_NODE_TX_LOOKUP_RESULT_H diff --git a/src/rest.cpp b/src/rest.cpp index 7913c2d611..49676cf828 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -14,11 +14,11 @@ #include <flatfile.h> #include <httpserver.h> #include <index/blockfilterindex.h> -#include <index/tx_lookup_result.h> #include <index/txindex.h> #include <node/blockstorage.h> #include <node/context.h> #include <node/transaction.h> +#include <node/tx_lookup_result.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <rpc/blockchain.h> diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 8b94667857..1df1604803 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -15,7 +15,6 @@ #include <crypto/common.h> #include <crypto/hex_base.h> #include <hash.h> -#include <index/tx_lookup_result.h> #include <index/txindex.h> #include <kernel/chainparams.h> #include <key.h> @@ -25,6 +24,7 @@ #include <node/context.h> #include <node/psbt.h> #include <node/transaction.h> +#include <node/tx_lookup_result.h> #include <policy/feerate.h> #include <primitives/block.h> #include <primitives/transaction.h> diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index 8d2b0cb3c5..57f1cb2bb3 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -8,11 +8,11 @@ #include <chain.h> #include <coins.h> #include <crypto/hex_base.h> -#include <index/tx_lookup_result.h> #include <index/txindex.h> #include <merkleblock.h> #include <node/blockstorage.h> #include <node/transaction.h> +#include <node/tx_lookup_result.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <rpc/blockchain.h> diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp index a2fe62b7a0..19bf438324 100644 --- a/src/test/txindex_tests.cpp +++ b/src/test/txindex_tests.cpp @@ -12,12 +12,12 @@ #include <dbwrapper.h> #include <flatfile.h> #include <index/disktxpos.h> -#include <index/tx_lookup_result.h> #include <index/txindex.h> #include <index/txindex_key.h> #include <interfaces/chain.h> #include <key.h> #include <node/blockstorage.h> +#include <node/tx_lookup_result.h> #include <primitives/block.h> #include <script/script.h> #include <streams.h> ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 02:38:31 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

I find result.GetFound() and result.GetMiss() easier to read than repeating std::get_if at each call site. Deriving from the variant, like GenTxid does, keeps the found/miss distinction and the existing std::get calls.

Give the lookup result named accessors
diff --git a/src/node/transaction.cpp b/src/node/transaction.cpp
index 60338e9af0..48fe0016b7 100644
--- a/src/node/transaction.cpp
+++ b/src/node/transaction.cpp
@@ -19,7 +19,6 @@
 #include <validationinterface.h>
 
 #include <utility>
-#include <variant>
 
 namespace node {
 static TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out)
@@ -146,21 +145,15 @@ TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef t
 TxLookupResult GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const Txid& hash, const BlockManager& blockman)
 {
     if (mempool && !block_index) {
-        CTransactionRef ptx = mempool->get(hash);
-        if (ptx) return TxFound{std::move(ptx), {}};
+        if (auto ptx{mempool->get(hash)}) return TxFound{std::move(ptx), {}};
     }
     if (g_txindex) {
-        TxLookupResult result{g_txindex->FindTx(hash)};
-        if (const auto* found{std::get_if<TxFound>(&result)}) {
-            if (!block_index || block_index->GetBlockHash() == found->block_hash) {
-                // Don't return the transaction if the provided block hash doesn't match.
-                // The case where a transaction appears in multiple blocks (e.g. reorgs or
-                // BIP30) is handled by the block lookup below.
-                return result;
-            }
-        } else if (!block_index) {
-            return result;
-        }
+        auto result{g_txindex->FindTx(hash)};
+        if (!block_index) return result;
+        // Don't return the transaction if the provided block hash doesn't match.
+        // The case where a transaction appears in multiple blocks (e.g. reorgs or
+        // BIP30) is handled by the block lookup below.
+        if (const auto* found{result.GetFound()}; found && block_index->GetBlockHash() == found->block_hash) return result;
     }
     if (block_index) {
         CBlock block;
diff --git a/src/node/tx_lookup_result.h b/src/node/tx_lookup_result.h
index 9c1808d42c..e1c8e56b12 100644
--- a/src/node/tx_lookup_result.h
+++ b/src/node/tx_lookup_result.h
@@ -26,6 +26,14 @@ struct TxMiss {
 };
 
 /// Result of a transaction lookup that may be answered by the txindex.
-using TxLookupResult = std::variant<TxFound, TxMiss>;
+struct TxLookupResult : public std::variant<TxFound, TxMiss>
+{
+    using variant::variant;
+
+    TxFound* GetFound() { return std::get_if<TxFound>(this); }
+    const TxFound* GetFound() const { return std::get_if<TxFound>(this); }
+    TxMiss* GetMiss() { return std::get_if<TxMiss>(this); }
+    const TxMiss* GetMiss() const { return std::get_if<TxMiss>(this); }
+};
 
 #endif // BITCOIN_NODE_TX_LOOKUP_RESULT_H
diff --git a/src/rest.cpp b/src/rest.cpp
index b583bb1abe..004e31778a 100644
--- a/src/rest.cpp
+++ b/src/rest.cpp
@@ -903,7 +903,7 @@ static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string
     const NodeContext* const node = GetNodeContext(context, req);
     if (!node) return false;
     const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, node->mempool.get(), *hash, node->chainman->m_blockman)};
-    if (const auto* miss{std::get_if<TxMiss>(&result)}) {
+    if (const auto* miss{result.GetMiss()}) {
         if (!miss->pruned_block_hashes.empty()) {
             return RESTERR(req, HTTP_NOT_FOUND, PrunedBlocksErrorMessage(miss->pruned_block_hashes));
         }
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 3714ee26cc..77b75cb18b 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -178,8 +178,7 @@ PartiallySignedTransaction ProcessPSBT(const std::string& psbt_string, const std
         // The `non_witness_utxo` is the whole previous transaction
         if (psbt_input.non_witness_utxo) continue;
 
-        TxLookupResult result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), psbt_input.prev_txid, chainman.m_blockman)};
-        if (auto* found{std::get_if<TxFound>(&result)}) {
+        if (auto result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), psbt_input.prev_txid, chainman.m_blockman)}; auto* found{result.GetFound()}) {
             psbt_input.non_witness_utxo = std::move(found->tx);
         } else {
             coins[psbt_input.GetOutPoint()]; // Create empty map entry keyed by prevout
@@ -326,7 +325,7 @@ static RPCMethod getrawtransaction()
     }
 
     const TxLookupResult tx_result{GetTransaction(blockindex, node.mempool.get(), txid, chainman.m_blockman)};
-    if (const auto* miss{std::get_if<TxMiss>(&tx_result)}) {
+    if (const auto* miss{tx_result.GetMiss()}) {
         if (!miss->pruned_block_hashes.empty()) {
             throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes);
         }
diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp
index 57f1cb2bb3..e433578075 100644
--- a/src/rpc/txoutproof.cpp
+++ b/src/rpc/txoutproof.cpp
@@ -32,7 +32,6 @@
 #include <span>
 #include <string>
 #include <utility>
-#include <variant>
 #include <vector>
 
 using node::GetTransaction;
@@ -108,9 +107,9 @@ static RPCMethod gettxoutproof()
 
             if (pblockindex == nullptr) {
                 const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, *setTxids.begin(), chainman.m_blockman)};
-                const auto* found{std::get_if<TxFound>(&result)};
+                const auto* found{result.GetFound()};
                 if (!found || found->block_hash.IsNull()) {
-                    if (const auto* miss{std::get_if<TxMiss>(&result)}; miss && !miss->pruned_block_hashes.empty()) {
+                    if (const auto* miss{result.GetMiss()}; miss && !miss->pruned_block_hashes.empty()) {
                         throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes);
                     }
                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index d57a7074a4..e1a3666da1 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -35,7 +35,6 @@
 #include <string>
 #include <string_view>
 #include <utility>
-#include <variant>
 #include <vector>
 
 #include <boost/test/unit_test.hpp>
@@ -88,16 +87,15 @@ FlatFilePos BlockFilePos(const ChainstateManager& chainman, uint32_t height)
 uint256 LookupTx(const TxIndex& txindex, const Txid& txid)
 {
     const auto result{txindex.FindTx(txid)};
-    const auto* found{std::get_if<TxFound>(&result)};
-    BOOST_CHECK(Assert(found)->tx->GetHash() == txid);
-    return found->block_hash;
+    const auto& [tx, block_hash]{*Assert(result.GetFound())};
+    BOOST_CHECK(tx->GetHash() == txid);
+    return block_hash;
 }
 
 void CheckNotFound(const TxIndex& txindex, const Txid& txid, const std::set<uint256>& expected_pruned_block_hashes = {})
 {
     const auto result{txindex.FindTx(txid)};
-    const auto* miss{std::get_if<TxMiss>(&result)};
-    BOOST_CHECK(Assert(miss)->pruned_block_hashes == expected_pruned_block_hashes);
+    BOOST_CHECK(Assert(result.GetMiss())->pruned_block_hashes == expected_pruned_block_hashes);
 }
 
 void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash)
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: I find `result.GetFound()` and `result.GetMiss()` easier to read than repeating `std::get_if` at each call site. Deriving from the variant, like `GenTxid` does, keeps the found/miss distinction and the existing `std::get` calls. <details> <summary>Give the lookup result named accessors</summary> ```diff diff --git a/src/node/transaction.cpp b/src/node/transaction.cpp index 60338e9af0..48fe0016b7 100644 --- a/src/node/transaction.cpp +++ b/src/node/transaction.cpp @@ -19,7 +19,6 @@ #include <validationinterface.h> #include <utility> -#include <variant> namespace node { static TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out) @@ -146,21 +145,15 @@ TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef t TxLookupResult GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const Txid& hash, const BlockManager& blockman) { if (mempool && !block_index) { - CTransactionRef ptx = mempool->get(hash); - if (ptx) return TxFound{std::move(ptx), {}}; + if (auto ptx{mempool->get(hash)}) return TxFound{std::move(ptx), {}}; } if (g_txindex) { - TxLookupResult result{g_txindex->FindTx(hash)}; - if (const auto* found{std::get_if<TxFound>(&result)}) { - if (!block_index || block_index->GetBlockHash() == found->block_hash) { - // Don't return the transaction if the provided block hash doesn't match. - // The case where a transaction appears in multiple blocks (e.g. reorgs or - // BIP30) is handled by the block lookup below. - return result; - } - } else if (!block_index) { - return result; - } + auto result{g_txindex->FindTx(hash)}; + if (!block_index) return result; + // Don't return the transaction if the provided block hash doesn't match. + // The case where a transaction appears in multiple blocks (e.g. reorgs or + // BIP30) is handled by the block lookup below. + if (const auto* found{result.GetFound()}; found && block_index->GetBlockHash() == found->block_hash) return result; } if (block_index) { CBlock block; diff --git a/src/node/tx_lookup_result.h b/src/node/tx_lookup_result.h index 9c1808d42c..e1c8e56b12 100644 --- a/src/node/tx_lookup_result.h +++ b/src/node/tx_lookup_result.h @@ -26,6 +26,14 @@ struct TxMiss { }; /// Result of a transaction lookup that may be answered by the txindex. -using TxLookupResult = std::variant<TxFound, TxMiss>; +struct TxLookupResult : public std::variant<TxFound, TxMiss> +{ + using variant::variant; + + TxFound* GetFound() { return std::get_if<TxFound>(this); } + const TxFound* GetFound() const { return std::get_if<TxFound>(this); } + TxMiss* GetMiss() { return std::get_if<TxMiss>(this); } + const TxMiss* GetMiss() const { return std::get_if<TxMiss>(this); } +}; #endif // BITCOIN_NODE_TX_LOOKUP_RESULT_H diff --git a/src/rest.cpp b/src/rest.cpp index b583bb1abe..004e31778a 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -903,7 +903,7 @@ static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string const NodeContext* const node = GetNodeContext(context, req); if (!node) return false; const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, node->mempool.get(), *hash, node->chainman->m_blockman)}; - if (const auto* miss{std::get_if<TxMiss>(&result)}) { + if (const auto* miss{result.GetMiss()}) { if (!miss->pruned_block_hashes.empty()) { return RESTERR(req, HTTP_NOT_FOUND, PrunedBlocksErrorMessage(miss->pruned_block_hashes)); } diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 3714ee26cc..77b75cb18b 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -178,8 +178,7 @@ PartiallySignedTransaction ProcessPSBT(const std::string& psbt_string, const std // The `non_witness_utxo` is the whole previous transaction if (psbt_input.non_witness_utxo) continue; - TxLookupResult result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), psbt_input.prev_txid, chainman.m_blockman)}; - if (auto* found{std::get_if<TxFound>(&result)}) { + if (auto result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), psbt_input.prev_txid, chainman.m_blockman)}; auto* found{result.GetFound()}) { psbt_input.non_witness_utxo = std::move(found->tx); } else { coins[psbt_input.GetOutPoint()]; // Create empty map entry keyed by prevout @@ -326,7 +325,7 @@ static RPCMethod getrawtransaction() } const TxLookupResult tx_result{GetTransaction(blockindex, node.mempool.get(), txid, chainman.m_blockman)}; - if (const auto* miss{std::get_if<TxMiss>(&tx_result)}) { + if (const auto* miss{tx_result.GetMiss()}) { if (!miss->pruned_block_hashes.empty()) { throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes); } diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index 57f1cb2bb3..e433578075 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -32,7 +32,6 @@ #include <span> #include <string> #include <utility> -#include <variant> #include <vector> using node::GetTransaction; @@ -108,9 +107,9 @@ static RPCMethod gettxoutproof() if (pblockindex == nullptr) { const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, *setTxids.begin(), chainman.m_blockman)}; - const auto* found{std::get_if<TxFound>(&result)}; + const auto* found{result.GetFound()}; if (!found || found->block_hash.IsNull()) { - if (const auto* miss{std::get_if<TxMiss>(&result)}; miss && !miss->pruned_block_hashes.empty()) { + if (const auto* miss{result.GetMiss()}; miss && !miss->pruned_block_hashes.empty()) { throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes); } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp index d57a7074a4..e1a3666da1 100644 --- a/src/test/txindex_tests.cpp +++ b/src/test/txindex_tests.cpp @@ -35,7 +35,6 @@ #include <string> #include <string_view> #include <utility> -#include <variant> #include <vector> #include <boost/test/unit_test.hpp> @@ -88,16 +87,15 @@ FlatFilePos BlockFilePos(const ChainstateManager& chainman, uint32_t height) uint256 LookupTx(const TxIndex& txindex, const Txid& txid) { const auto result{txindex.FindTx(txid)}; - const auto* found{std::get_if<TxFound>(&result)}; - BOOST_CHECK(Assert(found)->tx->GetHash() == txid); - return found->block_hash; + const auto& [tx, block_hash]{*Assert(result.GetFound())}; + BOOST_CHECK(tx->GetHash() == txid); + return block_hash; } void CheckNotFound(const TxIndex& txindex, const Txid& txid, const std::set<uint256>& expected_pruned_block_hashes = {}) { const auto result{txindex.FindTx(txid)}; - const auto* miss{std::get_if<TxMiss>(&result)}; - BOOST_CHECK(Assert(miss)->pruned_block_hashes == expected_pruned_block_hashes); + BOOST_CHECK(Assert(result.GetMiss())->pruned_block_hashes == expected_pruned_block_hashes); } void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash) ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-12 12:39:12 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

Nit: a slightly simpler version:

Use the complement notation
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index d14c02d88e..b6e38d0abe 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -192,7 +192,7 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const
                 continue;
             }
             const bool in_active_chain{m_chainstate->m_chain.Contains(*block_index)};
-            if (!(block_index->nStatus & BLOCK_HAVE_DATA)) {
+            if (~block_index->nStatus & BLOCK_HAVE_DATA) {
                 if (in_active_chain) pruned_block_hashes.insert(candidate_block_hash);
                 continue;
             }
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: Nit: a slightly simpler version: <details> <summary>Use the complement notation</summary> ```diff diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp index d14c02d88e..b6e38d0abe 100644 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -192,7 +192,7 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const continue; } const bool in_active_chain{m_chainstate->m_chain.Contains(*block_index)}; - if (!(block_index->nStatus & BLOCK_HAVE_DATA)) { + if (~block_index->nStatus & BLOCK_HAVE_DATA) { if (in_active_chain) pruned_block_hashes.insert(candidate_block_hash); continue; } ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:55:28 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

This can be a bit shorter if we construct the transaction from the file and check its hash inside the try block. That also keeps tx local, and makes the continue unnecessary.

I'm conflicted about whether a read failure should just log a warning and try the next candidate - but that's preexisting.

Keep candidate reading and matching together
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index b6e38d0abe..a47727cdb8 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -218,15 +218,11 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const
             LogWarning("OpenBlockFile failed for txid %s", tx_hash.ToString());
             continue;
         }
-        CTransactionRef tx;
         try {
-            file >> TX_WITH_WITNESS(tx);
+            auto tx{std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, file)};
+            if (tx->GetHash() == tx_hash) return TxFound{std::move(tx), candidate.block_hash};
         } catch (const std::exception& e) {
             LogWarning("Deserialize or I/O error - %s", e.what());
-            continue;
-        }
-        if (tx->GetHash() == tx_hash) {
-            return TxFound{std::move(tx), candidate.block_hash};
         }
     }
     // Fall back to legacy if no hashed entry matched. This makes misses pay an
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: This can be a bit shorter if we construct the transaction from the file and check its hash inside the `try` block. That also keeps `tx` local, and makes the `continue` unnecessary. I'm conflicted about whether a read failure should just log a warning and try the next candidate - but that's preexisting. <details> <summary>Keep candidate reading and matching together</summary> ```diff diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp index b6e38d0abe..a47727cdb8 100644 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -218,15 +218,11 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const LogWarning("OpenBlockFile failed for txid %s", tx_hash.ToString()); continue; } - CTransactionRef tx; try { - file >> TX_WITH_WITNESS(tx); + auto tx{std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, file)}; + if (tx->GetHash() == tx_hash) return TxFound{std::move(tx), candidate.block_hash}; } catch (const std::exception& e) { LogWarning("Deserialize or I/O error - %s", e.what()); - continue; - } - if (tx->GetHash() == tx_hash) { - return TxFound{std::move(tx), candidate.block_hash}; } } // Fall back to legacy if no hashed entry matched. This makes misses pay an ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 02:39:05 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

This can be a bit shorter if we construct the transaction from the file and check its hash inside the try block. That also keeps tx local and makes the continue unnecessary.

Whether a read failure should just log a warning and try the next candidate is a separate question. That behavior predates this PR, and this suggestion leaves it unchanged.

Keep candidate reading and matching together
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index b6e38d0abe..a47727cdb8 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -218,15 +218,11 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const
             LogWarning("OpenBlockFile failed for txid %s", tx_hash.ToString());
             continue;
         }
-        CTransactionRef tx;
         try {
-            file >> TX_WITH_WITNESS(tx);
+            auto tx{std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, file)};
+            if (tx->GetHash() == tx_hash) return TxFound{std::move(tx), candidate.block_hash};
         } catch (const std::exception& e) {
             LogWarning("Deserialize or I/O error - %s", e.what());
-            continue;
-        }
-        if (tx->GetHash() == tx_hash) {
-            return TxFound{std::move(tx), candidate.block_hash};
         }
     }
     // Fall back to legacy if no hashed entry matched. This makes misses pay an
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: This can be a bit shorter if we construct the transaction from the file and check its hash inside the `try` block. That also keeps `tx` local and makes the `continue` unnecessary. Whether a read failure should just log a warning and try the next candidate is a separate question. That behavior predates this PR, and this suggestion leaves it unchanged. <details> <summary>Keep candidate reading and matching together</summary> ```diff diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp index b6e38d0abe..a47727cdb8 100644 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -218,15 +218,11 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const LogWarning("OpenBlockFile failed for txid %s", tx_hash.ToString()); continue; } - CTransactionRef tx; try { - file >> TX_WITH_WITNESS(tx); + auto tx{std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, file)}; + if (tx->GetHash() == tx_hash) return TxFound{std::move(tx), candidate.block_hash}; } catch (const std::exception& e) { LogWarning("Deserialize or I/O error - %s", e.what()); - continue; - } - if (tx->GetHash() == tx_hash) { - return TxFound{std::move(tx), candidate.block_hash}; } } // Fall back to legacy if no hashed entry matched. This makes misses pay an ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 02:36:40 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

Based on Ralph's review: could pruning remove the file between the scan above and OpenBlockFile?

It predates this PR, but this PR enables that combination, so the race becomes possible in normal use and belongs with this change.

Preserve the candidate after concurrent pruning
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index 00256b329f..b6e38d0abe 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -209,6 +209,12 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const
     for (const auto& candidate : candidates) {
         AutoFile file{m_chainstate->m_blockman.OpenBlockFile(candidate.tx_position, /*fReadOnly=*/true)};
         if (file.IsNull()) {
+            LOCK(cs_main);
+            const CBlockIndex* block_index{m_chainstate->m_blockman.LookupBlockIndex(candidate.block_hash)};
+            if (block_index && m_chainstate->m_chain.Contains(*block_index) && m_chainstate->m_blockman.IsBlockPruned(*block_index)) {
+                pruned_block_hashes.insert(candidate.block_hash);
+                continue;
+            }
             LogWarning("OpenBlockFile failed for txid %s", tx_hash.ToString());
             continue;
         }
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: Based on Ralph's review: could pruning remove the file between the scan above and `OpenBlockFile`? It predates this PR, but this PR enables that combination, so the race becomes possible in normal use and belongs with this change. <details> <summary>Preserve the candidate after concurrent pruning</summary> ```diff diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp index 00256b329f..b6e38d0abe 100644 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -209,6 +209,12 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const for (const auto& candidate : candidates) { AutoFile file{m_chainstate->m_blockman.OpenBlockFile(candidate.tx_position, /*fReadOnly=*/true)}; if (file.IsNull()) { + LOCK(cs_main); + const CBlockIndex* block_index{m_chainstate->m_blockman.LookupBlockIndex(candidate.block_hash)}; + if (block_index && m_chainstate->m_chain.Contains(*block_index) && m_chainstate->m_blockman.IsBlockPruned(*block_index)) { + pruned_block_hashes.insert(candidate.block_hash); + continue; + } LogWarning("OpenBlockFile failed for txid %s", tx_hash.ToString()); continue; } ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:39:12 +00:00

46542ed txindex: allow prune mode when there are no legacy entries:

Let's test this before pruning too. We currently only check the other error message.

AllowPrune() always returns true for the in-memory index because it assumes there are no legacy entries. Could we move this assertion to the existing on-disk test, where it actually checks the database?

Cover both sides of the legacy prune policy
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index 4e4cfbae1b..af3abb9806 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -149,7 +149,6 @@ BOOST_AUTO_TEST_CASE(txindex_hash_prefix)
 BOOST_FIXTURE_TEST_CASE(txindex_initial_sync, TestChain100Setup)
 {
     TxIndex txindex(interfaces::MakeChain(m_node), /*n_cache_size=*/1_MiB, /*f_memory=*/true);
-    BOOST_CHECK(txindex.AllowPrune());
     BOOST_REQUIRE(txindex.Init());
 
     // Transaction should not be found in the index before it is started.
@@ -192,6 +191,7 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup)
     // On-disk, so the legacy-entry probe at construction runs against a fresh
     // database, as it would on a node whose index was created by this version.
     TxIndex txindex(interfaces::MakeChain(m_node), /*n_cache_size=*/1_MiB, /*f_memory=*/false);
+    BOOST_CHECK(txindex.AllowPrune());
     BOOST_REQUIRE(txindex.Init());
     txindex.Sync();
 
diff --git a/test/functional/feature_txindex_compatibility.py b/test/functional/feature_txindex_compatibility.py
index 1949b3dcc9..94afffe498 100755
--- a/test/functional/feature_txindex_compatibility.py
+++ b/test/functional/feature_txindex_compatibility.py
@@ -53,6 +53,11 @@ class TxIndexTest(BitcoinTestFramework):
         self.stop_nodes()
         self.cleanup_folder(node.chain_path)
         shutil.copytree(legacy_node.chain_path, node.chain_path)
+        self.log.info("Ensure that prune mode rejects a legacy txindex")
+        node.assert_start_raises_init_error(
+            extra_args=["-prune=1", "-txindex"],
+            expected_msg="Error: Prune mode is incompatible with a txindex that still contains legacy entries. Stop the node, delete the txindex directory, and restart to rebuild the index.",
+        )
         msg = "txindex contains entries in the legacy format"
         with node.assert_debug_log(expected_msgs=[msg]):
             self.start_node(0)
> [46542ed](https://github.com/bitcoin/bitcoin/pull/36002/changes/46542edf6bc0afea178f86c89c4b67022b064e9e) _txindex: allow prune mode when there are no legacy entries_: Let's test this before pruning too. We currently only check the other error message. `AllowPrune()` always returns true for the in-memory index because it assumes there are no legacy entries. Could we move this assertion to the existing on-disk test, where it actually checks the database? <details> <summary>Cover both sides of the legacy prune policy</summary> ```diff diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp index 4e4cfbae1b..af3abb9806 100644 --- a/src/test/txindex_tests.cpp +++ b/src/test/txindex_tests.cpp @@ -149,7 +149,6 @@ BOOST_AUTO_TEST_CASE(txindex_hash_prefix) BOOST_FIXTURE_TEST_CASE(txindex_initial_sync, TestChain100Setup) { TxIndex txindex(interfaces::MakeChain(m_node), /*n_cache_size=*/1_MiB, /*f_memory=*/true); - BOOST_CHECK(txindex.AllowPrune()); BOOST_REQUIRE(txindex.Init()); // Transaction should not be found in the index before it is started. @@ -192,6 +191,7 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup) // On-disk, so the legacy-entry probe at construction runs against a fresh // database, as it would on a node whose index was created by this version. TxIndex txindex(interfaces::MakeChain(m_node), /*n_cache_size=*/1_MiB, /*f_memory=*/false); + BOOST_CHECK(txindex.AllowPrune()); BOOST_REQUIRE(txindex.Init()); txindex.Sync(); diff --git a/test/functional/feature_txindex_compatibility.py b/test/functional/feature_txindex_compatibility.py index 1949b3dcc9..94afffe498 100755 --- a/test/functional/feature_txindex_compatibility.py +++ b/test/functional/feature_txindex_compatibility.py @@ -53,6 +53,11 @@ class TxIndexTest(BitcoinTestFramework): self.stop_nodes() self.cleanup_folder(node.chain_path) shutil.copytree(legacy_node.chain_path, node.chain_path) + self.log.info("Ensure that prune mode rejects a legacy txindex") + node.assert_start_raises_init_error( + extra_args=["-prune=1", "-txindex"], + expected_msg="Error: Prune mode is incompatible with a txindex that still contains legacy entries. Stop the node, delete the txindex directory, and restart to rebuild the index.", + ) msg = "txindex contains entries in the legacy format" with node.assert_debug_log(expected_msgs=[msg]): self.start_node(0) ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:46:28 +00:00

012c384 rpc: report pruned blocks from GetTransaction:

gettxoutproof follows the same pruned check with CheckBlockDataAvailability, which we could reuse here. A block that was never downloaded would then report Block not available (not fully downloaded), as gettxoutproof and getblock do, which the existing header-only test can check:

Reuse the block availability check

(I prepared this locally in commits so the patches may not apply cleanly)

diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index ebf9f955e7..3714ee26cc 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -31,6 +31,7 @@
 #include <psbt.h>
 #include <pubkey.h>
 #include <random.h>
+#include <rpc/blockchain.h>
 #include <rpc/protocol.h>
 #include <rpc/rawtransaction_util.h>
 #include <rpc/request.h>
@@ -335,9 +336,7 @@ static RPCMethod getrawtransaction()
             if (chainman.m_blockman.IsBlockPruned(*blockindex)) {
                 throw JSONRPCPrunedBlocksError({blockindex->GetBlockHash()});
             }
-            if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
-                throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
-            }
+            CheckBlockDataAvailability(chainman.m_blockman, *blockindex, /*check_for_undo=*/false);
             errmsg = "No such transaction found in the provided block";
         } else if (!g_txindex) {
             errmsg = "No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries";
diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py
index c61b49c9fc..7b94d2d7e9 100755
--- a/test/functional/rpc_blockchain.py
+++ b/test/functional/rpc_blockchain.py
@@ -747,6 +747,7 @@ class BlockchainTest(BitcoinTestFramework):
         block.solve()
         node.submitheader(block.serialize().hex())
         assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", lambda: node.getblock(block.hash_hex))
+        assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", node.getrawtransaction, block.vtx[0].txid_hex, 0, block.hash_hex)
 
         self.log.info("Test getblock when block data is available but undo data isn't")
         # Submits a block building on the header-only block, so it can't be connected and has no undo data
> [012c384](https://github.com/bitcoin/bitcoin/pull/36002/changes/012c384cd72ba6cf01d065eedac7c14a1b364a08) _rpc: report pruned blocks from GetTransaction_: `gettxoutproof` follows the same pruned check with `CheckBlockDataAvailability`, which we could reuse here. A block that was never downloaded would then report `Block not available (not fully downloaded)`, as `gettxoutproof` and `getblock` do, which the existing header-only test can check: <details> <summary>Reuse the block availability check</summary> (I prepared this locally in commits so the patches may not apply cleanly) ```diff diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index ebf9f955e7..3714ee26cc 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -31,6 +31,7 @@ #include <psbt.h> #include <pubkey.h> #include <random.h> +#include <rpc/blockchain.h> #include <rpc/protocol.h> #include <rpc/rawtransaction_util.h> #include <rpc/request.h> @@ -335,9 +336,7 @@ static RPCMethod getrawtransaction() if (chainman.m_blockman.IsBlockPruned(*blockindex)) { throw JSONRPCPrunedBlocksError({blockindex->GetBlockHash()}); } - if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) { - throw JSONRPCError(RPC_MISC_ERROR, "Block not available"); - } + CheckBlockDataAvailability(chainman.m_blockman, *blockindex, /*check_for_undo=*/false); errmsg = "No such transaction found in the provided block"; } else if (!g_txindex) { errmsg = "No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries"; diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py index c61b49c9fc..7b94d2d7e9 100755 --- a/test/functional/rpc_blockchain.py +++ b/test/functional/rpc_blockchain.py @@ -747,6 +747,7 @@ class BlockchainTest(BitcoinTestFramework): block.solve() node.submitheader(block.serialize().hex()) assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", lambda: node.getblock(block.hash_hex)) + assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", node.getrawtransaction, block.vtx[0].txid_hex, 0, block.hash_hex) self.log.info("Test getblock when block data is available but undo data isn't") # Submits a block building on the header-only block, so it can't be connected and has no undo data ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:44:07 +00:00

012c384 rpc: report pruned blocks from GetTransaction:

nit: these three lines could be a structured binding, here and in rest_tx:

Use structured bindings for the found transaction
diff --git a/src/rest.cpp b/src/rest.cpp
index 49676cf828..b583bb1abe 100644
--- a/src/rest.cpp
+++ b/src/rest.cpp
@@ -909,9 +909,7 @@ static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string
         }
         return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
     }
-    const auto& found{std::get<TxFound>(result)};
-    const CTransactionRef& tx{found.tx};
-    const uint256& hashBlock{found.block_hash};
+    const auto& [tx, hashBlock]{std::get<TxFound>(result)};
     switch (rf) {
     case RESTResponseFormat::BINARY: {
         DataStream ssTx;
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 5e38401c48..ebf9f955e7 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -348,9 +348,7 @@ static RPCMethod getrawtransaction()
         }
         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
     }
-    const auto& found{std::get<TxFound>(tx_result)};
-    const CTransactionRef& tx{found.tx};
-    const uint256& hash_block{found.block_hash};
+    const auto& [tx, hash_block]{std::get<TxFound>(tx_result)};
 
     if (verbosity <= 0) {
         return EncodeHexTx(*tx);
> [012c384](https://github.com/bitcoin/bitcoin/pull/36002/changes/012c384cd72ba6cf01d065eedac7c14a1b364a08) _rpc: report pruned blocks from GetTransaction_: nit: these three lines could be a structured binding, here and in `rest_tx`: <details> <summary>Use structured bindings for the found transaction</summary> ```diff diff --git a/src/rest.cpp b/src/rest.cpp index 49676cf828..b583bb1abe 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -909,9 +909,7 @@ static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string } return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); } - const auto& found{std::get<TxFound>(result)}; - const CTransactionRef& tx{found.tx}; - const uint256& hashBlock{found.block_hash}; + const auto& [tx, hashBlock]{std::get<TxFound>(result)}; switch (rf) { case RESTResponseFormat::BINARY: { DataStream ssTx; diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 5e38401c48..ebf9f955e7 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -348,9 +348,7 @@ static RPCMethod getrawtransaction() } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions."); } - const auto& found{std::get<TxFound>(tx_result)}; - const CTransactionRef& tx{found.tx}; - const uint256& hash_block{found.block_hash}; + const auto& [tx, hash_block]{std::get<TxFound>(tx_result)}; if (verbosity <= 0) { return EncodeHexTx(*tx); ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:58:44 +00:00

012c384 rpc: report pruned blocks from GetTransaction:

I think this would be easier to review as smaller commits. I tried this split locally to help me with review, consider if you agree whether it separates concerns better:

  1. Move the missing-undo fix to the start of the PR. It fixes getrawtransaction without txindex too, so it could also go in a separate PR. I can push that PR if you want, but it would conflict with this one.
  2. Add the optional error.data argument to JSONRPCError on its own.
  3. Keep the pruned-block reporting in GetTransaction, RPC and REST together.
  4. Switch ProcessPSBT to GetTransaction separately, since that also changes the lookup order to mempool first.
> [012c384](https://github.com/bitcoin/bitcoin/pull/36002/changes/012c384cd72ba6cf01d065eedac7c14a1b364a08) _rpc: report pruned blocks from GetTransaction_: I think this would be easier to review as smaller commits. I tried this split locally to help me with review, consider if you agree whether it separates concerns better: 1. Move the missing-undo fix to the start of the PR. It fixes `getrawtransaction` without txindex too, so it could also go in a separate PR. I can push that PR if you want, but it would conflict with this one. 2. Add the optional `error.data` argument to `JSONRPCError` on its own. 3. Keep the pruned-block reporting in `GetTransaction`, RPC and REST together. 4. Switch `ProcessPSBT` to `GetTransaction` separately, since that also changes the lookup order to mempool first.
l0rinc (Migrated from github.com) commented 2026-10-14 01:43:22 +00:00

012c384 rpc: report pruned blocks from GetTransaction:

Returning the whole error here would save repeating the same code, message and data at all four call sites. JSONRPCTransactionError already does something similar.

Build the pruned-block error in one place
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 667f92f377..62069455eb 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -327,16 +327,13 @@ static RPCMethod getrawtransaction()
     const TxLookupResult tx_result{GetTransaction(blockindex, node.mempool.get(), txid, chainman.m_blockman)};
     if (const auto* miss{std::get_if<TxMiss>(&tx_result)}) {
         if (!miss->pruned_block_hashes.empty()) {
-            throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(miss->pruned_block_hashes),
-                               PrunedBlocksErrorData(miss->pruned_block_hashes));
+            throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes);
         }
         std::string errmsg;
         if (blockindex) {
             LOCK(cs_main);
             if (chainman.m_blockman.IsBlockPruned(*blockindex)) {
-                const std::set<uint256> block_hashes{blockindex->GetBlockHash()};
-                throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(block_hashes),
-                                   PrunedBlocksErrorData(block_hashes));
+                throw JSONRPCPrunedBlocksError({blockindex->GetBlockHash()});
             }
             if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
                 throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp
index b9ff37d93a..8d2b0cb3c5 100644
--- a/src/rpc/txoutproof.cpp
+++ b/src/rpc/txoutproof.cpp
@@ -111,8 +111,7 @@ static RPCMethod gettxoutproof()
                 const auto* found{std::get_if<TxFound>(&result)};
                 if (!found || found->block_hash.IsNull()) {
                     if (const auto* miss{std::get_if<TxMiss>(&result)}; miss && !miss->pruned_block_hashes.empty()) {
-                        throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(miss->pruned_block_hashes),
-                                           PrunedBlocksErrorData(miss->pruned_block_hashes));
+                        throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes);
                     }
                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
                 }
@@ -128,9 +127,7 @@ static RPCMethod gettxoutproof()
             {
                 LOCK(cs_main);
                 if (chainman.m_blockman.IsBlockPruned(*pblockindex)) {
-                    const std::set<uint256> block_hashes{pblockindex->GetBlockHash()};
-                    throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(block_hashes),
-                                       PrunedBlocksErrorData(block_hashes));
+                    throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()});
                 }
                 CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false);
             }
diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp
index fa4801ba8e..3a444097af 100644
--- a/src/rpc/util.cpp
+++ b/src/rpc/util.cpp
@@ -431,7 +431,7 @@ std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashe
     return strprintf("Transaction may be in one of the following pruned blocks: %s.", hashes);
 }
 
-UniValue PrunedBlocksErrorData(const std::set<uint256>& pruned_block_hashes)
+UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes)
 {
     UniValue hashes{UniValue::VARR};
     for (const auto& hash : pruned_block_hashes) {
@@ -439,7 +439,7 @@ UniValue PrunedBlocksErrorData(const std::set<uint256>& pruned_block_hashes)
     }
     UniValue data{UniValue::VOBJ};
     data.pushKV("pruned_block_hashes", std::move(hashes));
-    return data;
+    return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), data);
 }
 
 /**
diff --git a/src/rpc/util.h b/src/rpc/util.h
index 4acd77cf4b..d5ac400b31 100644
--- a/src/rpc/util.h
+++ b/src/rpc/util.h
@@ -149,8 +149,8 @@ UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string&
 
 //! Error message when a transaction lookup only matched blocks whose data was pruned.
 std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes);
-//! Structured JSON-RPC error.data for a pruned-block transaction lookup miss.
-UniValue PrunedBlocksErrorData(const std::set<uint256>& pruned_block_hashes);
+//! JSON-RPC error for a pruned-block transaction lookup miss.
+UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes);
 
 //! Parse a JSON range specified as int64, or [int64, int64]
 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
> [012c384](https://github.com/bitcoin/bitcoin/pull/36002/changes/012c384cd72ba6cf01d065eedac7c14a1b364a08) _rpc: report pruned blocks from GetTransaction_: Returning the whole error here would save repeating the same code, message and data at all four call sites. `JSONRPCTransactionError` already does something similar. <details> <summary>Build the pruned-block error in one place</summary> ```diff diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 667f92f377..62069455eb 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -327,16 +327,13 @@ static RPCMethod getrawtransaction() const TxLookupResult tx_result{GetTransaction(blockindex, node.mempool.get(), txid, chainman.m_blockman)}; if (const auto* miss{std::get_if<TxMiss>(&tx_result)}) { if (!miss->pruned_block_hashes.empty()) { - throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(miss->pruned_block_hashes), - PrunedBlocksErrorData(miss->pruned_block_hashes)); + throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes); } std::string errmsg; if (blockindex) { LOCK(cs_main); if (chainman.m_blockman.IsBlockPruned(*blockindex)) { - const std::set<uint256> block_hashes{blockindex->GetBlockHash()}; - throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(block_hashes), - PrunedBlocksErrorData(block_hashes)); + throw JSONRPCPrunedBlocksError({blockindex->GetBlockHash()}); } if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) { throw JSONRPCError(RPC_MISC_ERROR, "Block not available"); diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index b9ff37d93a..8d2b0cb3c5 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -111,8 +111,7 @@ static RPCMethod gettxoutproof() const auto* found{std::get_if<TxFound>(&result)}; if (!found || found->block_hash.IsNull()) { if (const auto* miss{std::get_if<TxMiss>(&result)}; miss && !miss->pruned_block_hashes.empty()) { - throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(miss->pruned_block_hashes), - PrunedBlocksErrorData(miss->pruned_block_hashes)); + throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes); } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); } @@ -128,9 +127,7 @@ static RPCMethod gettxoutproof() { LOCK(cs_main); if (chainman.m_blockman.IsBlockPruned(*pblockindex)) { - const std::set<uint256> block_hashes{pblockindex->GetBlockHash()}; - throw JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(block_hashes), - PrunedBlocksErrorData(block_hashes)); + throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()}); } CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false); } diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp index fa4801ba8e..3a444097af 100644 --- a/src/rpc/util.cpp +++ b/src/rpc/util.cpp @@ -431,7 +431,7 @@ std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashe return strprintf("Transaction may be in one of the following pruned blocks: %s.", hashes); } -UniValue PrunedBlocksErrorData(const std::set<uint256>& pruned_block_hashes) +UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes) { UniValue hashes{UniValue::VARR}; for (const auto& hash : pruned_block_hashes) { @@ -439,7 +439,7 @@ UniValue PrunedBlocksErrorData(const std::set<uint256>& pruned_block_hashes) } UniValue data{UniValue::VOBJ}; data.pushKV("pruned_block_hashes", std::move(hashes)); - return data; + return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), data); } /** diff --git a/src/rpc/util.h b/src/rpc/util.h index 4acd77cf4b..d5ac400b31 100644 --- a/src/rpc/util.h +++ b/src/rpc/util.h @@ -149,8 +149,8 @@ UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& //! Error message when a transaction lookup only matched blocks whose data was pruned. std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes); -//! Structured JSON-RPC error.data for a pruned-block transaction lookup miss. -UniValue PrunedBlocksErrorData(const std::set<uint256>& pruned_block_hashes); +//! JSON-RPC error for a pruned-block transaction lookup miss. +UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes); //! Parse a JSON range specified as int64, or [int64, int64] std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value); ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:45:34 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

nit: given that found is a prerequisite (i.e. part of the setup) and not the main assertion, I usually include it in the assertion. You're already using this pattern later, but resolve without comment if you disagree.

The pruning setup is repeated four times below, so it could also use a small helper next to InvalidateBlock.

Compact the lookup assertions and pruning setup
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index ed64b92b75..94de39b35c 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -89,8 +89,7 @@ uint256 LookupTx(const TxIndex& txindex, const Txid& txid)
 {
     const auto result{txindex.FindTx(txid)};
     const auto* found{std::get_if<TxFound>(&result)};
-    BOOST_REQUIRE(found);
-    BOOST_CHECK(found->tx->GetHash() == txid);
+    BOOST_CHECK(Assert(found)->tx->GetHash() == txid);
     return found->block_hash;
 }
 
@@ -98,8 +97,7 @@ void CheckNotFound(const TxIndex& txindex, const Txid& txid, const std::set<uint
 {
     const auto result{txindex.FindTx(txid)};
     const auto* miss{std::get_if<TxMiss>(&result)};
-    BOOST_REQUIRE(miss);
-    BOOST_CHECK(miss->pruned_block_hashes == expected_pruned_block_hashes);
+    BOOST_CHECK(Assert(miss)->pruned_block_hashes == expected_pruned_block_hashes);
 }
 
 void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash)
@@ -110,6 +108,12 @@ void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash)
     BOOST_REQUIRE(chainman.ActiveChainstate().InvalidateBlock(state, block_index));
 }
 
+void PruneBlock(ChainstateManager& chainman, const uint256& block_hash)
+{
+    LOCK(cs_main);
+    Assert(chainman.m_blockman.LookupBlockIndex(block_hash))->nStatus &= ~BLOCK_HAVE_DATA;
+}
+
 } // namespace
 
 BOOST_AUTO_TEST_CASE(txindex_position_encoding)
@@ -237,16 +241,10 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup)
     db.Write(txindex::LegacyTxKey(fake_txid), fake_physical);
     CheckNotFound(txindex, fake_txid);
 
-    {
-        LOCK(cs_main);
-        Assert(m_node.chainman->m_blockman.LookupBlockIndex(fake_block_hash))->nStatus &= ~BLOCK_HAVE_DATA;
-    }
+    PruneBlock(*m_node.chainman, fake_block_hash);
     BOOST_CHECK(LookupTx(txindex, target_txid) == target_block_hash);
 
-    {
-        LOCK(cs_main);
-        Assert(m_node.chainman->m_blockman.LookupBlockIndex(target_block_hash))->nStatus &= ~BLOCK_HAVE_DATA;
-    }
+    PruneBlock(*m_node.chainman, target_block_hash);
     CheckNotFound(txindex, target_txid, {target_block_hash, fake_block_hash});
 
     StopIndex(txindex, m_node);
@@ -376,11 +374,8 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup)
     BOOST_REQUIRE_EQUAL(reorg_bucket.size(), 2U);
     BOOST_CHECK(reorg_bucket.front() == original_bucket.front());
 
-    {
-        LOCK(cs_main);
-        Assert(chainman.m_blockman.LookupBlockIndex(stale_block_hash))->nStatus &= ~BLOCK_HAVE_DATA;
-        Assert(chainman.m_blockman.LookupBlockIndex(branch_block_hash))->nStatus &= ~BLOCK_HAVE_DATA;
-    }
+    PruneBlock(chainman, stale_block_hash);
+    PruneBlock(chainman, branch_block_hash);
     CheckNotFound(txindex, unique_txid, {stale_block_hash});
 
     StopIndex(txindex, m_node);
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: nit: given that `found` is a prerequisite (i.e. part of the setup) and not the main assertion, I usually include it in the assertion. You're already using this pattern later, but resolve without comment if you disagree. The pruning setup is repeated four times below, so it could also use a small helper next to `InvalidateBlock`. <details> <summary>Compact the lookup assertions and pruning setup</summary> ```diff diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp index ed64b92b75..94de39b35c 100644 --- a/src/test/txindex_tests.cpp +++ b/src/test/txindex_tests.cpp @@ -89,8 +89,7 @@ uint256 LookupTx(const TxIndex& txindex, const Txid& txid) { const auto result{txindex.FindTx(txid)}; const auto* found{std::get_if<TxFound>(&result)}; - BOOST_REQUIRE(found); - BOOST_CHECK(found->tx->GetHash() == txid); + BOOST_CHECK(Assert(found)->tx->GetHash() == txid); return found->block_hash; } @@ -98,8 +97,7 @@ void CheckNotFound(const TxIndex& txindex, const Txid& txid, const std::set<uint { const auto result{txindex.FindTx(txid)}; const auto* miss{std::get_if<TxMiss>(&result)}; - BOOST_REQUIRE(miss); - BOOST_CHECK(miss->pruned_block_hashes == expected_pruned_block_hashes); + BOOST_CHECK(Assert(miss)->pruned_block_hashes == expected_pruned_block_hashes); } void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash) @@ -110,6 +108,12 @@ void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash) BOOST_REQUIRE(chainman.ActiveChainstate().InvalidateBlock(state, block_index)); } +void PruneBlock(ChainstateManager& chainman, const uint256& block_hash) +{ + LOCK(cs_main); + Assert(chainman.m_blockman.LookupBlockIndex(block_hash))->nStatus &= ~BLOCK_HAVE_DATA; +} + } // namespace BOOST_AUTO_TEST_CASE(txindex_position_encoding) @@ -237,16 +241,10 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup) db.Write(txindex::LegacyTxKey(fake_txid), fake_physical); CheckNotFound(txindex, fake_txid); - { - LOCK(cs_main); - Assert(m_node.chainman->m_blockman.LookupBlockIndex(fake_block_hash))->nStatus &= ~BLOCK_HAVE_DATA; - } + PruneBlock(*m_node.chainman, fake_block_hash); BOOST_CHECK(LookupTx(txindex, target_txid) == target_block_hash); - { - LOCK(cs_main); - Assert(m_node.chainman->m_blockman.LookupBlockIndex(target_block_hash))->nStatus &= ~BLOCK_HAVE_DATA; - } + PruneBlock(*m_node.chainman, target_block_hash); CheckNotFound(txindex, target_txid, {target_block_hash, fake_block_hash}); StopIndex(txindex, m_node); @@ -376,11 +374,8 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup) BOOST_REQUIRE_EQUAL(reorg_bucket.size(), 2U); BOOST_CHECK(reorg_bucket.front() == original_bucket.front()); - { - LOCK(cs_main); - Assert(chainman.m_blockman.LookupBlockIndex(stale_block_hash))->nStatus &= ~BLOCK_HAVE_DATA; - Assert(chainman.m_blockman.LookupBlockIndex(branch_block_hash))->nStatus &= ~BLOCK_HAVE_DATA; - } + PruneBlock(chainman, stale_block_hash); + PruneBlock(chainman, branch_block_hash); CheckNotFound(txindex, unique_txid, {stale_block_hash}); StopIndex(txindex, m_node); ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:50:19 +00:00

2e9cf9d txindex: return pruned block hashes from FindTx:

What should happen when the active-chain copy is pruned but a stale copy is still readable? We return the stale block, so getrawtransaction shows zero confirmations and verifytxoutproof rejects the proof from gettxoutproof.

We cannot just prefer the pruned hash either, since it might be a prefix collision. Is the current fallback what we want? If so, we could cover it in the existing reorg test (using the PruneBlock helper from my other comment):

Cover the readable stale-block fallback
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index 538ada2caf..00256b329f 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -170,7 +170,7 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const
         uint32_t block_seq;
         //! Whether this candidate's block is currently in the active chain.
         //! Active chain candidates are attempted first, so duplicate entries
-        //! in both active and stale blocks will always return the active block hash.
+        //! in both active and stale blocks will return the active block hash if readable.
         bool in_active_chain;
     };
     std::vector<Candidate> candidates;
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index 94de39b35c..d57a7074a4 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -375,6 +375,8 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup)
     BOOST_CHECK(reorg_bucket.front() == original_bucket.front());
 
     PruneBlock(chainman, stale_block_hash);
+    // A readable stale copy still supplies the transaction when the active copy is pruned.
+    BOOST_CHECK(LookupTx(txindex, unique_txid) == branch_block_hash);
     PruneBlock(chainman, branch_block_hash);
     CheckNotFound(txindex, unique_txid, {stale_block_hash});
 
> [2e9cf9d](https://github.com/bitcoin/bitcoin/pull/36002/changes/2e9cf9d7eba20bb2d431ec13a69ce65a163390c9) _txindex: return pruned block hashes from FindTx_: What should happen when the active-chain copy is pruned but a stale copy is still readable? We return the stale block, so `getrawtransaction` shows zero confirmations and `verifytxoutproof` rejects the proof from `gettxoutproof`. We cannot just prefer the pruned hash either, since it might be a prefix collision. Is the current fallback what we want? If so, we could cover it in the existing reorg test (using the `PruneBlock` helper from my other comment): <details> <summary>Cover the readable stale-block fallback</summary> ```diff diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp index 538ada2caf..00256b329f 100644 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -170,7 +170,7 @@ TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const uint32_t block_seq; //! Whether this candidate's block is currently in the active chain. //! Active chain candidates are attempted first, so duplicate entries - //! in both active and stale blocks will always return the active block hash. + //! in both active and stale blocks will return the active block hash if readable. bool in_active_chain; }; std::vector<Candidate> candidates; diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp index 94de39b35c..d57a7074a4 100644 --- a/src/test/txindex_tests.cpp +++ b/src/test/txindex_tests.cpp @@ -375,6 +375,8 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup) BOOST_CHECK(reorg_bucket.front() == original_bucket.front()); PruneBlock(chainman, stale_block_hash); + // A readable stale copy still supplies the transaction when the active copy is pruned. + BOOST_CHECK(LookupTx(txindex, unique_txid) == branch_block_hash); PruneBlock(chainman, branch_block_hash); CheckNotFound(txindex, unique_txid, {stale_block_hash}); ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 02:41:10 +00:00

46542ed txindex: allow prune mode when there are no legacy entries:

nit: we already have sync_txindex for these three waits. This also gives us its sync logging.

Reuse the index-sync helper
diff --git a/test/functional/feature_txindex_compatibility.py b/test/functional/feature_txindex_compatibility.py
index 94afffe498..970dba47d5 100755
--- a/test/functional/feature_txindex_compatibility.py
+++ b/test/functional/feature_txindex_compatibility.py
@@ -9,7 +9,7 @@
 import shutil
 
 from test_framework.test_framework import BitcoinTestFramework
-from test_framework.util import assert_equal
+from test_framework.util import assert_equal, sync_txindex
 from test_framework.wallet import MiniWallet
 
 class TxIndexTest(BitcoinTestFramework):
@@ -43,7 +43,7 @@ class TxIndexTest(BitcoinTestFramework):
         txId1 = tx1['txid']
 
         for n in self.nodes:
-            self.wait_until(lambda: n.getindexinfo()['txindex']['synced'])
+            sync_txindex(self, n)
 
         self.log.info("Ensure that queries to the txindex are consistent between the different index versions")
         assert_equal(node.getrawtransaction(txId1), tx1['hex'])
@@ -61,14 +61,14 @@ class TxIndexTest(BitcoinTestFramework):
         msg = "txindex contains entries in the legacy format"
         with node.assert_debug_log(expected_msgs=[msg]):
             self.start_node(0)
-        self.wait_until(lambda: node.getindexinfo()['txindex']['synced'])
+        sync_txindex(self, node)
         assert_equal(node.getrawtransaction(txId1), tx1['hex'])
 
         self.log.info("Test that looking up a newly added transaction in a mixed-format db is possible")
         tx2 = self.wallet.send_self_transfer(from_node=self.nodes[0])
         self.generate(self.nodes[0], 1, sync_fun=self.no_op)
         txId2 = tx2['txid']
-        self.wait_until(lambda: node.getindexinfo()['txindex']['synced'])
+        sync_txindex(self, node)
         assert_equal(node.getrawtransaction(txId1), tx1['hex'])
         assert_equal(node.getrawtransaction(txId2), tx2['hex'])
 
> [46542ed](https://github.com/bitcoin/bitcoin/pull/36002/changes/46542edf6bc0afea178f86c89c4b67022b064e9e) _txindex: allow prune mode when there are no legacy entries_: nit: we already have `sync_txindex` for these three waits. This also gives us its sync logging. <details> <summary>Reuse the index-sync helper</summary> ```diff diff --git a/test/functional/feature_txindex_compatibility.py b/test/functional/feature_txindex_compatibility.py index 94afffe498..970dba47d5 100755 --- a/test/functional/feature_txindex_compatibility.py +++ b/test/functional/feature_txindex_compatibility.py @@ -9,7 +9,7 @@ import shutil from test_framework.test_framework import BitcoinTestFramework -from test_framework.util import assert_equal +from test_framework.util import assert_equal, sync_txindex from test_framework.wallet import MiniWallet class TxIndexTest(BitcoinTestFramework): @@ -43,7 +43,7 @@ class TxIndexTest(BitcoinTestFramework): txId1 = tx1['txid'] for n in self.nodes: - self.wait_until(lambda: n.getindexinfo()['txindex']['synced']) + sync_txindex(self, n) self.log.info("Ensure that queries to the txindex are consistent between the different index versions") assert_equal(node.getrawtransaction(txId1), tx1['hex']) @@ -61,14 +61,14 @@ class TxIndexTest(BitcoinTestFramework): msg = "txindex contains entries in the legacy format" with node.assert_debug_log(expected_msgs=[msg]): self.start_node(0) - self.wait_until(lambda: node.getindexinfo()['txindex']['synced']) + sync_txindex(self, node) assert_equal(node.getrawtransaction(txId1), tx1['hex']) self.log.info("Test that looking up a newly added transaction in a mixed-format db is possible") tx2 = self.wallet.send_self_transfer(from_node=self.nodes[0]) self.generate(self.nodes[0], 1, sync_fun=self.no_op) txId2 = tx2['txid'] - self.wait_until(lambda: node.getindexinfo()['txindex']['synced']) + sync_txindex(self, node) assert_equal(node.getrawtransaction(txId1), tx1['hex']) assert_equal(node.getrawtransaction(txId2), tx2['hex']) ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-14 01:41:06 +00:00

2cce7aa test: cover txindex lookups of pruned blocks:

With txindex enabled, its fallback returns the same error and can mask a broken UTXO lookup.

We could also check that we can still find the downloaded transaction after restarting. That part already works today, so feel free to leave it out.

We could also reuse try_rpc for the download wait and check the hex from the verbose response.

Exercise no-txindex lookups and recovery across restart
diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py
index 3b9981f9d9..d330f3a8e3 100755
--- a/test/functional/feature_txindex_prune.py
+++ b/test/functional/feature_txindex_prune.py
@@ -10,7 +10,9 @@ from urllib.parse import urlparse
 from test_framework.test_framework import BitcoinTestFramework
 from test_framework.util import (
     assert_equal,
+    assert_raises_rpc_error,
     sync_txindex,
+    try_rpc,
     JSONRPCException,
 )
 from test_framework.wallet import MiniWallet, getnewdestination
@@ -50,6 +52,10 @@ class TxIndexPruneTest(BitcoinTestFramework):
         self.log.info("Mine enough blocks to prune the transaction's block")
         self.generate(full, 600)
         pruned.pruneblockchain(pruned.getblockcount())
+
+        self.log.info("Pruned UTXO lookups work without txindex")
+        self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"])
+        assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [txid])
         self.restart_node(0)
         sync_txindex(self, pruned)
         self.connect_nodes(0, 1)
@@ -67,9 +73,7 @@ class TxIndexPruneTest(BitcoinTestFramework):
                 rpc(*rpc_args)
                 raise AssertionError("Expected pruned transaction lookup failure")
             except JSONRPCException as error:
-                assert_equal(error.error["code"], -1)
-                assert_equal(error.error["message"], f"Transaction may be in pruned block {expected_blockhash}.")
-                assert_equal(error.error["data"]["pruned_block_hashes"], [expected_blockhash])
+                assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {expected_blockhash}.", "data": {"pruned_block_hashes": [expected_blockhash]}})
 
         self.log.info("REST /tx returns the pruned block's hash")
         assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.")
@@ -82,13 +86,9 @@ class TxIndexPruneTest(BitcoinTestFramework):
         self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups")
         pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"])
 
-        def tx_available():
-            try:
-                return pruned.getrawtransaction(txid) == tx["hex"]
-            except JSONRPCException:
-                return False
-        self.wait_until(tx_available)
+        self.wait_until(lambda: not try_rpc(None, None, pruned.getrawtransaction, txid))
         tx_verbose = pruned.getrawtransaction(txid, 2)
+        assert_equal(tx_verbose["hex"], tx["hex"])
         # verbose fields are missing because there's no undo fetched from peer
         assert "fee" not in tx_verbose
         assert "prevout" not in tx_verbose["vin"][0]
@@ -97,5 +97,9 @@ class TxIndexPruneTest(BitcoinTestFramework):
         updated = pruned.utxoupdatepsbt(psbt)
         assert "non_witness_utxo" in pruned.decodepsbt(updated)["inputs"][0]
 
+        self.log.info("Recovered transaction lookup survives a restart")
+        self.restart_node(0)
+        assert_equal(pruned.getrawtransaction(txid), tx["hex"])
+
 if __name__ == '__main__':
     TxIndexPruneTest(__file__).main()
> [2cce7aa](https://github.com/bitcoin/bitcoin/pull/36002/changes/2cce7aad2afd9e2fcbef8ec5ebaa8238aa0517d7) _test: cover txindex lookups of pruned blocks_: With txindex enabled, its fallback returns the same error and can mask a broken UTXO lookup. We could also check that we can still find the downloaded transaction after restarting. That part already works today, so feel free to leave it out. We could also reuse `try_rpc` for the download wait and check the hex from the verbose response. <details> <summary>Exercise no-txindex lookups and recovery across restart</summary> ```diff diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py index 3b9981f9d9..d330f3a8e3 100755 --- a/test/functional/feature_txindex_prune.py +++ b/test/functional/feature_txindex_prune.py @@ -10,7 +10,9 @@ from urllib.parse import urlparse from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, + assert_raises_rpc_error, sync_txindex, + try_rpc, JSONRPCException, ) from test_framework.wallet import MiniWallet, getnewdestination @@ -50,6 +52,10 @@ class TxIndexPruneTest(BitcoinTestFramework): self.log.info("Mine enough blocks to prune the transaction's block") self.generate(full, 600) pruned.pruneblockchain(pruned.getblockcount()) + + self.log.info("Pruned UTXO lookups work without txindex") + self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"]) + assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [txid]) self.restart_node(0) sync_txindex(self, pruned) self.connect_nodes(0, 1) @@ -67,9 +73,7 @@ class TxIndexPruneTest(BitcoinTestFramework): rpc(*rpc_args) raise AssertionError("Expected pruned transaction lookup failure") except JSONRPCException as error: - assert_equal(error.error["code"], -1) - assert_equal(error.error["message"], f"Transaction may be in pruned block {expected_blockhash}.") - assert_equal(error.error["data"]["pruned_block_hashes"], [expected_blockhash]) + assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {expected_blockhash}.", "data": {"pruned_block_hashes": [expected_blockhash]}}) self.log.info("REST /tx returns the pruned block's hash") assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.") @@ -82,13 +86,9 @@ class TxIndexPruneTest(BitcoinTestFramework): self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups") pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"]) - def tx_available(): - try: - return pruned.getrawtransaction(txid) == tx["hex"] - except JSONRPCException: - return False - self.wait_until(tx_available) + self.wait_until(lambda: not try_rpc(None, None, pruned.getrawtransaction, txid)) tx_verbose = pruned.getrawtransaction(txid, 2) + assert_equal(tx_verbose["hex"], tx["hex"]) # verbose fields are missing because there's no undo fetched from peer assert "fee" not in tx_verbose assert "prevout" not in tx_verbose["vin"][0] @@ -97,5 +97,9 @@ class TxIndexPruneTest(BitcoinTestFramework): updated = pruned.utxoupdatepsbt(psbt) assert "non_witness_utxo" in pruned.decodepsbt(updated)["inputs"][0] + self.log.info("Recovered transaction lookup survives a restart") + self.restart_node(0) + assert_equal(pruned.getrawtransaction(txid), tx["hex"]) + if __name__ == '__main__': TxIndexPruneTest(__file__).main() ``` </details>
andrewtoth commented 2026-10-18 18:42:45 +00:00 (Migrated from github.com)

Thanks @l0rinc for your detailed review. I took all your suggestions.

Thanks @l0rinc for your detailed review. I took all your suggestions.
optout21 commented 2026-10-27 15:54:08 +00:00 (Migrated from github.com)

crACK 4ab48b8276

Building on previous reviews, looks good! Thanks for the updates!

The only contentious case is the unlikely edge case when a TX matches an active-chain block, but that's pruned, and also a stale block that is not pruned. In this case the active block can't be verified for false-positive, so it's placed in pruned_block_hashes. However, the stale block can be verified, and it is returned as Found. This is a bit unintuitive, not ideal, the active-chain pruned hash is not returned at all. However, due to the need for false-positive check, I can see no better solution. Since this is a very unlikely edge case, I think it's acceptable.

UPDATE (Nov-2): Also tried this branch on a pruned node, ran reindex on it. Worked as expected. I tested it by querying several TXs, some recent (unpruned), some old, and some very old. Correct blockhash was returned for pruned blocks as well.

crACK 4ab48b827691ade8ceaa78b5125e9bb610d37aa6 Building on previous reviews, looks good! Thanks for the updates! The only contentious case is the unlikely edge case when a TX matches an active-chain block, but that's pruned, and also a stale block that is not pruned. In this case the active block can't be verified for false-positive, so it's placed in `pruned_block_hashes`. However, the stale block can be verified, and it is returned as Found. This is a bit unintuitive, not ideal, the active-chain pruned hash is not returned at all. However, due to the need for false-positive check, I can see no better solution. Since this is a very unlikely edge case, I think it's acceptable. UPDATE (Nov-2): Also tried this branch on a pruned node, ran reindex on it. Worked as expected. I tested it by querying several TXs, some recent (unpruned), some old, and some very old. Correct blockhash was returned for pruned blocks as well.
DrahtBot commented 2026-11-02 11:56: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).
andrewtoth commented 2026-11-02 15:09:06 +00:00 (Migrated from github.com)
Thanks for the review @optout21! Rebased due to https://github.com/bitcoin/bitcoin/pull/36618.
optout21 commented 2026-11-02 15:12:49 +00:00 (Migrated from github.com)

reACK 322cbbf4d0
Reviewed rebase changes (git range-diff 4ab48b827691ade8ceaa78b5125e9bb610d37aa6...322cbbf4d0c6c4c0abf920ac53814c1507c7e4b6).

reACK 322cbbf4d0c6c4c0abf920ac53814c1507c7e4b6 Reviewed rebase changes (`git range-diff 4ab48b827691ade8ceaa78b5125e9bb610d37aa6...322cbbf4d0c6c4c0abf920ac53814c1507c7e4b6`).
DrahtBot commented 2026-11-03 19:09:33 +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).
andrewtoth commented 2026-11-03 22:14:28 +00:00 (Migrated from github.com)

Thanks again @optout21.

Rebased due to https://github.com/bitcoin/bitcoin/pull/35728.

git range-diff e310efb202..322cbbf4d0 fb19fed3df..8aa03c78de

Thanks again @optout21. Rebased due to https://github.com/bitcoin/bitcoin/pull/35728. `git range-diff e310efb202..322cbbf4d0 fb19fed3df..8aa03c78de`
l0rinc (Migrated from github.com) approved these changes 2026-11-18 10:29:36 +00:00
l0rinc (Migrated from github.com) left a comment

I went a bit deeper into the pruning and recovery paths on this second pass. I only had time to review the cases I commented on.

I think we still need a few test cases and should fix the reorg case where a two-transaction proof request fails without telling the caller which pruned block to fetch. LGTM overall.

I went a bit deeper into the pruning and recovery paths on this second pass. I only had time to review the cases I commented on. I think we still need a few test cases and should fix the reorg case where a two-transaction proof request fails without telling the caller which pruned block to fetch. LGTM overall.
l0rinc (Migrated from github.com) commented 2026-11-18 10:18:49 +00:00

8aa03c7 doc: add release note for txindex pruning support:

Based on the disk-space discussion we could mention in the release note that txindex keeps growing outside the prune target.

Clarify transaction-index storage
diff --git a/doc/release-notes-36002.md b/doc/release-notes-36002.md
index ba6f1d2ce7..fc83d9d744 100644
--- a/doc/release-notes-36002.md
+++ b/doc/release-notes-36002.md
@@ -3,7 +3,8 @@ Updated settings
 
 - The transaction index (`-txindex`) can now be used with pruning (`-prune`).
   The index must be built from genesis. Indexes built in a version prior to v32
-  must be rebuilt first. (#36002)
+  must be rebuilt first. The transaction index continues to grow and does not
+  count toward the prune target. (#36002)
 
 Updated RPCs
 ------------
> [8aa03c7](https://github.com/bitcoin/bitcoin/pull/36002/changes/8aa03c78de62448fc9f0223631844dc29f0cddb0) _doc: add release note for txindex pruning support_: Based on [the disk-space discussion](https://github.com/bitcoin/bitcoin/pull/36002#issuecomment-5405875239) we could mention in the release note that txindex keeps growing outside the prune target. <details> <summary>Clarify transaction-index storage</summary> ```diff diff --git a/doc/release-notes-36002.md b/doc/release-notes-36002.md index ba6f1d2ce7..fc83d9d744 100644 --- a/doc/release-notes-36002.md +++ b/doc/release-notes-36002.md @@ -3,7 +3,8 @@ Updated settings - The transaction index (`-txindex`) can now be used with pruning (`-prune`). The index must be built from genesis. Indexes built in a version prior to v32 - must be rebuilt first. (#36002) + must be rebuilt first. The transaction index continues to grow and does not + count toward the prune target. (#36002) Updated RPCs ------------ ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 09:40:57 +00:00

Could we handle the miss first in gettxoutproof? That lookup skips the mempool, so a hit always has a block hash - the code could be simplified significantly if we invert this.

Handle lookup misses first
diff --git a/src/node/tx_lookup_result.h b/src/node/tx_lookup_result.h
index e1c8e56b12..9e83ce7f42 100644
--- a/src/node/tx_lookup_result.h
+++ b/src/node/tx_lookup_result.h
@@ -32,7 +32,6 @@ struct TxLookupResult : public std::variant<TxFound, TxMiss>
 
     TxFound* GetFound() { return std::get_if<TxFound>(this); }
     const TxFound* GetFound() const { return std::get_if<TxFound>(this); }
-    TxMiss* GetMiss() { return std::get_if<TxMiss>(this); }
     const TxMiss* GetMiss() const { return std::get_if<TxMiss>(this); }
 };
 
diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp
index 8eec81a15d..ce59441e46 100644
--- a/src/rpc/txoutproof.cpp
+++ b/src/rpc/txoutproof.cpp
@@ -76,12 +76,10 @@ static RPCMethod gettxoutproof()
             }
 
             const CBlockIndex* pblockindex = nullptr;
-            uint256 hashBlock;
             ChainstateManager& chainman = EnsureAnyChainman(request.context);
             if (!request.params[1].isNull()) {
                 LOCK(cs_main);
-                hashBlock = ParseHashV(request.params[1], "blockhash");
-                pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock);
+                pblockindex = chainman.m_blockman.LookupBlockIndex(ParseHashV(request.params[1], "blockhash"));
                 if (!pblockindex) {
                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
                 }
@@ -107,20 +105,15 @@ static RPCMethod gettxoutproof()
 
             if (pblockindex == nullptr) {
                 const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, *setTxids.begin(), chainman.m_blockman)};
-                const auto* found{result.GetFound()};
-                if (!found || found->block_hash.IsNull()) {
-                    if (const auto* miss{result.GetMiss()}; miss && miss->pruned_block_hashes.size()) {
-                        throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes);
-                    }
-                    throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
+                if (const auto* miss{result.GetMiss()}) {
+                    throw miss->pruned_block_hashes.empty()
+                              ? JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block")
+                              : JSONRPCPrunedBlocksError(miss->pruned_block_hashes);
                 }
-                hashBlock = found->block_hash;
 
                 LOCK(cs_main);
-                pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock);
-                if (!pblockindex) {
-                    throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
-                }
+                pblockindex = chainman.m_blockman.LookupBlockIndex(result.GetFound()->block_hash);
+                if (!pblockindex) throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
             }
 
             {
Could we handle the miss first in `gettxoutproof`? That lookup skips the mempool, so a hit always has a block hash - the code could be simplified significantly if we invert this. <details> <summary>Handle lookup misses first</summary> ```diff diff --git a/src/node/tx_lookup_result.h b/src/node/tx_lookup_result.h index e1c8e56b12..9e83ce7f42 100644 --- a/src/node/tx_lookup_result.h +++ b/src/node/tx_lookup_result.h @@ -32,7 +32,6 @@ struct TxLookupResult : public std::variant<TxFound, TxMiss> TxFound* GetFound() { return std::get_if<TxFound>(this); } const TxFound* GetFound() const { return std::get_if<TxFound>(this); } - TxMiss* GetMiss() { return std::get_if<TxMiss>(this); } const TxMiss* GetMiss() const { return std::get_if<TxMiss>(this); } }; diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index 8eec81a15d..ce59441e46 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -76,12 +76,10 @@ static RPCMethod gettxoutproof() } const CBlockIndex* pblockindex = nullptr; - uint256 hashBlock; ChainstateManager& chainman = EnsureAnyChainman(request.context); if (!request.params[1].isNull()) { LOCK(cs_main); - hashBlock = ParseHashV(request.params[1], "blockhash"); - pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock); + pblockindex = chainman.m_blockman.LookupBlockIndex(ParseHashV(request.params[1], "blockhash")); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } @@ -107,20 +105,15 @@ static RPCMethod gettxoutproof() if (pblockindex == nullptr) { const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, *setTxids.begin(), chainman.m_blockman)}; - const auto* found{result.GetFound()}; - if (!found || found->block_hash.IsNull()) { - if (const auto* miss{result.GetMiss()}; miss && miss->pruned_block_hashes.size()) { - throw JSONRPCPrunedBlocksError(miss->pruned_block_hashes); - } - throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); + if (const auto* miss{result.GetMiss()}) { + throw miss->pruned_block_hashes.empty() + ? JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block") + : JSONRPCPrunedBlocksError(miss->pruned_block_hashes); } - hashBlock = found->block_hash; LOCK(cs_main); - pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock); - if (!pblockindex) { - throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); - } + pblockindex = chainman.m_blockman.LookupBlockIndex(result.GetFound()->block_hash); + if (!pblockindex) throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); } { ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 08:59:42 +00:00

b2f7546 txindex: allow prune mode when there are no legacy entries:

I'd reuse the getblockfrompeer test for txindex, too - to check that we can resume after fetching missing block bodies without undo data.

Resume txindex after restoring missing block bodies
diff --git a/test/functional/feature_index_prune.py b/test/functional/feature_index_prune.py
index 7b8dbd34f5..935c8c212a 100755
--- a/test/functional/feature_index_prune.py
+++ b/test/functional/feature_index_prune.py
@@ -34,7 +34,7 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
         self.extra_args = [
             ["-fastprune", "-prune=1", "-blockfilterindex=1"],
             ["-fastprune", "-prune=1", "-coinstatsindex=1"],
-            ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1"],
+            ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1", "-txindex=1"],
             [],
         ]
 
@@ -142,9 +142,8 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
             self.nodes[i].assert_start_raises_init_error(extra_args=self.extra_args[i], expected_msg=msg+end_msg)
 
         self.log.info("fetching the missing blocks with getblockfrompeer doesn't work for block filter index and coinstatsindex")
-        # Only checking the first two nodes since this test takes a long time
-        # and the third node is kind of redundant in this context
-        for i, msg in enumerate([filter_msg, stats_msg]):
+        last_indexed_height = 1500
+        for i, msg in enumerate([filter_msg, stats_msg, filter_msg]):
             self.restart_node(i, extra_args=["-prune=1", "-fastprune"])
             node = self.nodes[i]
             prune_height = node.getblockchaininfo()["pruneheight"]
@@ -153,8 +152,7 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
             assert_equal(len(peers), 1)
             peer_id = peers[0]["id"]
 
-            # 1500 is the height to where the indices were able to sync previously
-            hashes = send_batch_request(node, "getblockhash", [[a] for a in range(1500, prune_height)])
+            hashes = send_batch_request(node, "getblockhash", [[a] for a in range(last_indexed_height, prune_height)])
             send_batch_request(node, "getblockfrompeer", [[bh, peer_id] for bh in hashes])
             # Ensure all necessary blocks have been fetched before proceeding
             for bh in hashes:
@@ -167,6 +165,12 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
             self.stop_node(i)
             node.assert_start_raises_init_error(extra_args=self.extra_args[i], expected_msg=msg+end_msg)
 
+        self.log.info("txindex can resume after fetching missing block bodies without undo data")
+        txindex_node = self.nodes[2]
+        self.start_node(2, extra_args=["-prune=1", "-fastprune", "-txindex=1"])
+        refetched_block = txindex_node.getblock(txindex_node.getblockhash(last_indexed_height + 1))
+        assert_equal(txindex_node.getrawtransaction(refetched_block['tx'][0], 1)['blockhash'], refetched_block['hash'])
+
         self.log.info("make sure the nodes start again with the indices and an additional -reindex arg")
         for i in range(3):
             restart_args = self.extra_args[i] + ["-reindex"]
> [b2f7546](https://github.com/bitcoin/bitcoin/pull/36002/changes/b2f7546b596bc99dab81eeac2f24490360f7b082) _txindex: allow prune mode when there are no legacy entries_: I'd reuse the `getblockfrompeer` test for txindex, too - to check that we can resume after fetching missing block bodies without undo data. <details> <summary>Resume txindex after restoring missing block bodies</summary> ```diff diff --git a/test/functional/feature_index_prune.py b/test/functional/feature_index_prune.py index 7b8dbd34f5..935c8c212a 100755 --- a/test/functional/feature_index_prune.py +++ b/test/functional/feature_index_prune.py @@ -34,7 +34,7 @@ class FeatureIndexPruneTest(BitcoinTestFramework): self.extra_args = [ ["-fastprune", "-prune=1", "-blockfilterindex=1"], ["-fastprune", "-prune=1", "-coinstatsindex=1"], - ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1"], + ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1", "-txindex=1"], [], ] @@ -142,9 +142,8 @@ class FeatureIndexPruneTest(BitcoinTestFramework): self.nodes[i].assert_start_raises_init_error(extra_args=self.extra_args[i], expected_msg=msg+end_msg) self.log.info("fetching the missing blocks with getblockfrompeer doesn't work for block filter index and coinstatsindex") - # Only checking the first two nodes since this test takes a long time - # and the third node is kind of redundant in this context - for i, msg in enumerate([filter_msg, stats_msg]): + last_indexed_height = 1500 + for i, msg in enumerate([filter_msg, stats_msg, filter_msg]): self.restart_node(i, extra_args=["-prune=1", "-fastprune"]) node = self.nodes[i] prune_height = node.getblockchaininfo()["pruneheight"] @@ -153,8 +152,7 @@ class FeatureIndexPruneTest(BitcoinTestFramework): assert_equal(len(peers), 1) peer_id = peers[0]["id"] - # 1500 is the height to where the indices were able to sync previously - hashes = send_batch_request(node, "getblockhash", [[a] for a in range(1500, prune_height)]) + hashes = send_batch_request(node, "getblockhash", [[a] for a in range(last_indexed_height, prune_height)]) send_batch_request(node, "getblockfrompeer", [[bh, peer_id] for bh in hashes]) # Ensure all necessary blocks have been fetched before proceeding for bh in hashes: @@ -167,6 +165,12 @@ class FeatureIndexPruneTest(BitcoinTestFramework): self.stop_node(i) node.assert_start_raises_init_error(extra_args=self.extra_args[i], expected_msg=msg+end_msg) + self.log.info("txindex can resume after fetching missing block bodies without undo data") + txindex_node = self.nodes[2] + self.start_node(2, extra_args=["-prune=1", "-fastprune", "-txindex=1"]) + refetched_block = txindex_node.getblock(txindex_node.getblockhash(last_indexed_height + 1)) + assert_equal(txindex_node.getrawtransaction(refetched_block['tx'][0], 1)['blockhash'], refetched_block['hash']) + self.log.info("make sure the nodes start again with the indices and an additional -reindex arg") for i in range(3): restart_args = self.extra_args[i] + ["-reindex"] ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 08:59:35 +00:00

b2f7546 txindex: allow prune mode when there are no legacy entries:

Could we use the existing new-index test for this - added a characterization suggestion below, in this commit we should let that same startup succeed (to demonstrate the behavior change).

Characterize startup with a fresh txindex and automatic pruning
diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py
index db06f24d92..5f72907f8e 100755
--- a/test/functional/feature_pruning.py
+++ b/test/functional/feature_pruning.py
@@ -471,7 +471,9 @@ class PruneTest(BitcoinTestFramework):
         self.sync_blocks([self.nodes[0], self.nodes[5]], wait=5, timeout=300)
 
         self.log.info("Test prune with a new index")
-        self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1"])
+        self.stop_node(0)
+        self.nodes[0].assert_start_raises_init_error(extra_args=["-prune=550", "-blockfilterindex=1", "-txindex=1"], expected_msg="Error: Prune mode is incompatible with -txindex.")  # TODO: Allow a fresh txindex to synchronize with automatic pruning
+        self.start_node(0, extra_args=["-prune=550", "-blockfilterindex=1"])
         node = self.nodes[0]
         self.wait_until(lambda: node.getindexinfo()["basic block filter index"]["best_block_height"] >= 10, timeout=300)
 
> [b2f7546](https://github.com/bitcoin/bitcoin/pull/36002/changes/b2f7546b596bc99dab81eeac2f24490360f7b082) _txindex: allow prune mode when there are no legacy entries_: Could we use the existing new-index test for this - added a characterization suggestion below, in this commit we should let that same startup succeed (to demonstrate the behavior change). <details> <summary>Characterize startup with a fresh txindex and automatic pruning</summary> ```diff diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py index db06f24d92..5f72907f8e 100755 --- a/test/functional/feature_pruning.py +++ b/test/functional/feature_pruning.py @@ -471,7 +471,9 @@ class PruneTest(BitcoinTestFramework): self.sync_blocks([self.nodes[0], self.nodes[5]], wait=5, timeout=300) self.log.info("Test prune with a new index") - self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1"]) + self.stop_node(0) + self.nodes[0].assert_start_raises_init_error(extra_args=["-prune=550", "-blockfilterindex=1", "-txindex=1"], expected_msg="Error: Prune mode is incompatible with -txindex.") # TODO: Allow a fresh txindex to synchronize with automatic pruning + self.start_node(0, extra_args=["-prune=550", "-blockfilterindex=1"]) node = self.nodes[0] self.wait_until(lambda: node.getindexinfo()["basic block filter index"]["best_block_height"] >= 10, timeout=300) ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 09:18:36 +00:00

Could we check the log in the header-only test too? We still try to read the block before returning the error.

Characterize the header-only lookup before the fix
diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py
index 8346c868a8..fb83a39950 100755
--- a/test/functional/rpc_blockchain.py
+++ b/test/functional/rpc_blockchain.py
@@ -747,6 +747,8 @@ class BlockchainTest(BitcoinTestFramework):
         block.solve()
         node.submitheader(block.serialize().hex())
         assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", lambda: node.getblock(block.hash_hex))
+        with node.assert_debug_log(["while reading raw block storage header"]):  # TODO: Reject header-only requests before attempting disk I/O
+            assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", node.getrawtransaction, block.vtx[0].txid_hex, 0, block.hash_hex)
 
         self.log.info("Test getblock when block data is available but undo data isn't")
         # Submits a block building on the header-only block, so it can't be connected and has no undo data
Could we check the log in the header-only test too? We still try to read the block before returning the error. <details> <summary>Characterize the header-only lookup before the fix</summary> ```diff diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py index 8346c868a8..fb83a39950 100755 --- a/test/functional/rpc_blockchain.py +++ b/test/functional/rpc_blockchain.py @@ -747,6 +747,8 @@ class BlockchainTest(BitcoinTestFramework): block.solve() node.submitheader(block.serialize().hex()) assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", lambda: node.getblock(block.hash_hex)) + with node.assert_debug_log(["while reading raw block storage header"]): # TODO: Reject header-only requests before attempting disk I/O + assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", node.getrawtransaction, block.vtx[0].txid_hex, 0, block.hash_hex) self.log.info("Test getblock when block data is available but undo data isn't") # Submits a block building on the header-only block, so it can't be connected and has no undo data ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 08:36:55 +00:00

Seems to me we could easily extend the existing block-without-undo test to cover the no-txindex case.

Characterize missing undo without txindex
diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py
index 17eebd5907..bc70c59b0d 100755
--- a/test/functional/rpc_blockchain.py
+++ b/test/functional/rpc_blockchain.py
@@ -760,6 +760,8 @@ class BlockchainTest(BitcoinTestFramework):
         assert_vin_does_not_contain_prevout(block_noundo.hash_hex, 2)
         assert_vin_does_not_contain_prevout(block_noundo.hash_hex, 3)
 
+        assert_raises_rpc_error(-32603, "Undo data expected but can't be read", node.getrawtransaction, tx.txid_hex, 2, block_noundo.hash_hex)  # TODO: Return the transaction without fee or prevout when undo data is unavailable
+
         self.log.info("Test getblock when block is missing")
         move_block_file('blk00000.dat', 'blk00000.dat.bak')
         assert_raises_rpc_error(-1, "Block not found on disk", node.getblock, blockhash)
Seems to me we could easily extend the existing block-without-undo test to cover the no-txindex case. <details> <summary>Characterize missing undo without txindex</summary> ```diff diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py index 17eebd5907..bc70c59b0d 100755 --- a/test/functional/rpc_blockchain.py +++ b/test/functional/rpc_blockchain.py @@ -760,6 +760,8 @@ class BlockchainTest(BitcoinTestFramework): assert_vin_does_not_contain_prevout(block_noundo.hash_hex, 2) assert_vin_does_not_contain_prevout(block_noundo.hash_hex, 3) + assert_raises_rpc_error(-32603, "Undo data expected but can't be read", node.getrawtransaction, tx.txid_hex, 2, block_noundo.hash_hex) # TODO: Return the transaction without fee or prevout when undo data is unavailable + self.log.info("Test getblock when block is missing") move_block_file('blk00000.dat', 'blk00000.dat.bak') assert_raises_rpc_error(-1, "Block not found on disk", node.getblock, blockhash) ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 08:59:49 +00:00

6eb28cf txindex: return pruned block hashes from FindTx:

Now that #36091 was merged, let's use the failure friendly comparisons instead.

Print values for the new txindex comparisons
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index 9a185cd8f9..0c7bc87b0a 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -22,6 +22,7 @@
 #include <script/script.h>
 #include <streams.h>
 #include <sync.h>
+#include <test/util/common.h>
 #include <test/util/setup_common.h>
 #include <test/util/validation.h>
 #include <util/byte_units.h>
@@ -88,14 +89,15 @@ uint256 LookupTx(const TxIndex& txindex, const Txid& txid)
 {
     const auto result{txindex.FindTx(txid)};
     const auto& [tx, block_hash]{*Assert(result.GetFound())};
-    BOOST_CHECK(tx->GetHash() == txid);
+    BOOST_REQUIRE_EQUAL(tx->GetHash(), txid);
     return block_hash;
 }
 
 void CheckNotFound(const TxIndex& txindex, const Txid& txid, const std::set<uint256>& expected_pruned_block_hashes = {})
 {
     const auto result{txindex.FindTx(txid)};
-    BOOST_CHECK(Assert(result.GetMiss())->pruned_block_hashes == expected_pruned_block_hashes);
+    const auto& hashes{Assert(result.GetMiss())->pruned_block_hashes};
+    BOOST_CHECK_EQUAL_COLLECTIONS(hashes.begin(), hashes.end(), expected_pruned_block_hashes.begin(), expected_pruned_block_hashes.end());
 }
 
 void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash)
@@ -241,7 +243,7 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup)
     CheckNotFound(txindex, fake_txid);
 
     PruneBlock(*m_node.chainman, fake_block_hash);
-    BOOST_CHECK(LookupTx(txindex, target_txid) == target_block_hash);
+    BOOST_CHECK_EQUAL(LookupTx(txindex, target_txid), target_block_hash);
 
     PruneBlock(*m_node.chainman, target_block_hash);
     CheckNotFound(txindex, target_txid, {target_block_hash, fake_block_hash});
@@ -375,7 +377,7 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup)
 
     PruneBlock(chainman, stale_block_hash);
     // A readable stale copy still supplies the transaction when the active copy is pruned.
-    BOOST_CHECK(LookupTx(txindex, unique_txid) == branch_block_hash);
+    BOOST_CHECK_EQUAL(LookupTx(txindex, unique_txid), branch_block_hash);
     PruneBlock(chainman, branch_block_hash);
     CheckNotFound(txindex, unique_txid, {stale_block_hash});
 
> [6eb28cf](https://github.com/bitcoin/bitcoin/pull/36002/changes/6eb28cf61a4a0638ac95d8360383976ec0b4139a) _txindex: return pruned block hashes from FindTx_: Now that #36091 was merged, let's use the failure friendly comparisons instead. <details> <summary>Print values for the new txindex comparisons</summary> ```diff diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp index 9a185cd8f9..0c7bc87b0a 100644 --- a/src/test/txindex_tests.cpp +++ b/src/test/txindex_tests.cpp @@ -22,6 +22,7 @@ #include <script/script.h> #include <streams.h> #include <sync.h> +#include <test/util/common.h> #include <test/util/setup_common.h> #include <test/util/validation.h> #include <util/byte_units.h> @@ -88,14 +89,15 @@ uint256 LookupTx(const TxIndex& txindex, const Txid& txid) { const auto result{txindex.FindTx(txid)}; const auto& [tx, block_hash]{*Assert(result.GetFound())}; - BOOST_CHECK(tx->GetHash() == txid); + BOOST_REQUIRE_EQUAL(tx->GetHash(), txid); return block_hash; } void CheckNotFound(const TxIndex& txindex, const Txid& txid, const std::set<uint256>& expected_pruned_block_hashes = {}) { const auto result{txindex.FindTx(txid)}; - BOOST_CHECK(Assert(result.GetMiss())->pruned_block_hashes == expected_pruned_block_hashes); + const auto& hashes{Assert(result.GetMiss())->pruned_block_hashes}; + BOOST_CHECK_EQUAL_COLLECTIONS(hashes.begin(), hashes.end(), expected_pruned_block_hashes.begin(), expected_pruned_block_hashes.end()); } void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash) @@ -241,7 +243,7 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup) CheckNotFound(txindex, fake_txid); PruneBlock(*m_node.chainman, fake_block_hash); - BOOST_CHECK(LookupTx(txindex, target_txid) == target_block_hash); + BOOST_CHECK_EQUAL(LookupTx(txindex, target_txid), target_block_hash); PruneBlock(*m_node.chainman, target_block_hash); CheckNotFound(txindex, target_txid, {target_block_hash, fake_block_hash}); @@ -375,7 +377,7 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup) PruneBlock(chainman, stale_block_hash); // A readable stale copy still supplies the transaction when the active copy is pruned. - BOOST_CHECK(LookupTx(txindex, unique_txid) == branch_block_hash); + BOOST_CHECK_EQUAL(LookupTx(txindex, unique_txid), branch_block_hash); PruneBlock(chainman, branch_block_hash); CheckNotFound(txindex, unique_txid, {stale_block_hash}); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 10:17:43 +00:00

The test sets up a reorg and resubmits a stale block containing only the first txid gettxoutproof looks up.
With the active-chain block containing both txids pruned, the RPC picks the stale block and fails without telling us which block to fetch.
Could gettxoutproof report the pruned candidate on this mismatch? FindTx already collects it.

Cover recovery of a multi-transaction proof
diff --git a/test/functional/rpc_txoutproof.py b/test/functional/rpc_txoutproof.py
index 6bb3da070f..38bfd56e6a 100755
--- a/test/functional/rpc_txoutproof.py
+++ b/test/functional/rpc_txoutproof.py
@@ -21,7 +21,7 @@ class MerkleBlockTest(BitcoinTestFramework):
         self.num_nodes = 2
         self.extra_args = [
             [],
-            ["-txindex"],
+            ["-txindex", "-prune=1", "-fastprune"],
         ]
 
     def run_test(self):
@@ -107,5 +107,24 @@ class MerkleBlockTest(BitcoinTestFramework):
         # TODO: try more variants, eg transactions at different depths, and
         # verify that the proofs are invalid
 
+        self.log.info("Check multi-transaction proof recovery with a readable stale duplicate")
+        full, pruned = self.nodes
+        # Match C++ txid ordering so the stale copy is tried first
+        first_txid, second_txid = sorted([txid1, txid2], key=lambda txid: bytes.fromhex(txid)[::-1])
+        for node in self.nodes:
+            node.invalidateblock(blockhash)
+        stale_hash = self.generateblock(full, output=miniwallet.get_address(), transactions=[first_txid])["hash"]
+        for node in self.nodes:
+            node.reconsiderblock(blockhash)
+            assert_equal(node.getblockhash(chain_height + 1), blockhash)
+        miniwallet.send_self_transfer(from_node=full, utxo_to_spend=miniwallet.get_utxo(txid=txid_unspent))
+        self.generate(full, 600)
+        pruned.pruneblockchain(pruned.getblockcount())
+        pruned.submitblock(full.getblock(stale_hash, 0))
+        assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [second_txid])
+        assert_raises_rpc_error(-5, "Not all transactions found in specified or retrieved block", pruned.gettxoutproof, [first_txid, second_txid])  # TODO: Report pruned candidates so the caller can recover this proof
+        pruned.submitblock(full.getblock(blockhash, 0))
+        assert_equal(pruned.verifytxoutproof(pruned.gettxoutproof([first_txid, second_txid])), txlist)
+
 if __name__ == '__main__':
     MerkleBlockTest(__file__).main()
The test sets up a reorg and resubmits a stale block containing only the first txid `gettxoutproof` looks up. With the active-chain block containing both txids pruned, the RPC picks the stale block and fails without telling us which block to fetch. Could `gettxoutproof` report the pruned candidate on this mismatch? `FindTx` already collects it. <details> <summary>Cover recovery of a multi-transaction proof</summary> ```diff diff --git a/test/functional/rpc_txoutproof.py b/test/functional/rpc_txoutproof.py index 6bb3da070f..38bfd56e6a 100755 --- a/test/functional/rpc_txoutproof.py +++ b/test/functional/rpc_txoutproof.py @@ -21,7 +21,7 @@ class MerkleBlockTest(BitcoinTestFramework): self.num_nodes = 2 self.extra_args = [ [], - ["-txindex"], + ["-txindex", "-prune=1", "-fastprune"], ] def run_test(self): @@ -107,5 +107,24 @@ class MerkleBlockTest(BitcoinTestFramework): # TODO: try more variants, eg transactions at different depths, and # verify that the proofs are invalid + self.log.info("Check multi-transaction proof recovery with a readable stale duplicate") + full, pruned = self.nodes + # Match C++ txid ordering so the stale copy is tried first + first_txid, second_txid = sorted([txid1, txid2], key=lambda txid: bytes.fromhex(txid)[::-1]) + for node in self.nodes: + node.invalidateblock(blockhash) + stale_hash = self.generateblock(full, output=miniwallet.get_address(), transactions=[first_txid])["hash"] + for node in self.nodes: + node.reconsiderblock(blockhash) + assert_equal(node.getblockhash(chain_height + 1), blockhash) + miniwallet.send_self_transfer(from_node=full, utxo_to_spend=miniwallet.get_utxo(txid=txid_unspent)) + self.generate(full, 600) + pruned.pruneblockchain(pruned.getblockcount()) + pruned.submitblock(full.getblock(stale_hash, 0)) + assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [second_txid]) + assert_raises_rpc_error(-5, "Not all transactions found in specified or retrieved block", pruned.gettxoutproof, [first_txid, second_txid]) # TODO: Report pruned candidates so the caller can recover this proof + pruned.submitblock(full.getblock(blockhash, 0)) + assert_equal(pruned.verifytxoutproof(pruned.gettxoutproof([first_txid, second_txid])), txlist) + if __name__ == '__main__': MerkleBlockTest(__file__).main() ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-18 09:42:32 +00:00

10d79c8 test: cover txindex lookups of pruned blocks:

Could we spend the SegWit change too? Its coin is still in the UTXO set, so utxoupdatepsbt should fill in witness_utxo even after the block is pruned.

Extend the existing PSBT with its SegWit change output
diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py
index d1ba388198..78cfb1b0a5 100755
--- a/test/functional/feature_txindex_prune.py
+++ b/test/functional/feature_txindex_prune.py
@@ -45,7 +45,8 @@ class TxIndexPruneTest(BitcoinTestFramework):
         tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000)
         blockhash = self.generate(pruned, 1)[0]
         txid = tx["txid"]
-        parent_txid = pruned.decoderawtransaction(tx["hex"])["vin"][0]["txid"]
+        decoded_tx = pruned.decoderawtransaction(tx["hex"])
+        parent_txid = decoded_tx["vin"][0]["txid"]
         parent_blockhash = pruned.getrawtransaction(parent_txid, 1)["blockhash"]
 
         self.log.info("Mine enough blocks to prune the transaction's block")
@@ -78,9 +79,17 @@ class TxIndexPruneTest(BitcoinTestFramework):
         assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.")
 
         self.log.info("utxoupdatepsbt skips previous transactions in pruned blocks")
-        psbt = pruned.createpsbt([{"txid": txid, "vout": tx["sent_vout"]}], [{getnewdestination()[2]: 0.0009}])
+        # The same transaction also has a native SegWit change output.
+        psbt = pruned.createpsbt([{"txid": txid, "vout": tx["sent_vout"]}, {"txid": txid, "vout": 0}], [{getnewdestination()[2]: 0.0009}])
+        change = decoded_tx["vout"][0]
         updated = pruned.utxoupdatepsbt(psbt)
-        assert "non_witness_utxo" not in pruned.decodepsbt(updated)["inputs"][0]
+        legacy_input, segwit_input = pruned.decodepsbt(updated)["inputs"]
+        assert "non_witness_utxo" not in legacy_input
+        assert "witness_utxo" not in legacy_input
+        assert "non_witness_utxo" not in segwit_input
+        witness_utxo = segwit_input["witness_utxo"]
+        assert_equal(witness_utxo["amount"], change["value"])
+        assert_equal(witness_utxo["scriptPubKey"]["hex"], change["scriptPubKey"]["hex"])
 
         self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups")
         pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"])
> [10d79c8](https://github.com/bitcoin/bitcoin/pull/36002/changes/10d79c89449508f600e7ab84e70f197523866d6f) _test: cover txindex lookups of pruned blocks_: Could we spend the SegWit change too? Its coin is still in the UTXO set, so `utxoupdatepsbt` should fill in `witness_utxo` even after the block is pruned. <details> <summary>Extend the existing PSBT with its SegWit change output</summary> ```diff diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py index d1ba388198..78cfb1b0a5 100755 --- a/test/functional/feature_txindex_prune.py +++ b/test/functional/feature_txindex_prune.py @@ -45,7 +45,8 @@ class TxIndexPruneTest(BitcoinTestFramework): tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000) blockhash = self.generate(pruned, 1)[0] txid = tx["txid"] - parent_txid = pruned.decoderawtransaction(tx["hex"])["vin"][0]["txid"] + decoded_tx = pruned.decoderawtransaction(tx["hex"]) + parent_txid = decoded_tx["vin"][0]["txid"] parent_blockhash = pruned.getrawtransaction(parent_txid, 1)["blockhash"] self.log.info("Mine enough blocks to prune the transaction's block") @@ -78,9 +79,17 @@ class TxIndexPruneTest(BitcoinTestFramework): assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.") self.log.info("utxoupdatepsbt skips previous transactions in pruned blocks") - psbt = pruned.createpsbt([{"txid": txid, "vout": tx["sent_vout"]}], [{getnewdestination()[2]: 0.0009}]) + # The same transaction also has a native SegWit change output. + psbt = pruned.createpsbt([{"txid": txid, "vout": tx["sent_vout"]}, {"txid": txid, "vout": 0}], [{getnewdestination()[2]: 0.0009}]) + change = decoded_tx["vout"][0] updated = pruned.utxoupdatepsbt(psbt) - assert "non_witness_utxo" not in pruned.decodepsbt(updated)["inputs"][0] + legacy_input, segwit_input = pruned.decodepsbt(updated)["inputs"] + assert "non_witness_utxo" not in legacy_input + assert "witness_utxo" not in legacy_input + assert "non_witness_utxo" not in segwit_input + witness_utxo = segwit_input["witness_utxo"] + assert_equal(witness_utxo["amount"], change["value"]) + assert_equal(witness_utxo["scriptPubKey"]["hex"], change["scriptPubKey"]["hex"]) self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups") pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"]) ``` </details>
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:04:17 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:04:17 +00:00

Added a test covering no fee/prevout returned instead of an error if we call getrawtransaction verbosity 2 with a block hash of a block with no undo file.

Added a test covering no `fee`/`prevout` returned instead of an error if we call `getrawtransaction` verbosity 2 with a block hash of a block with no undo file.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:05:54 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:05:54 +00:00

Updated the new-index test to also use txindex.

Updated the new-index test to also use `txindex`.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:07:30 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:07:30 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:07:52 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:07:52 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:11:48 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:11:48 +00:00

Done, reused node0 for this.

Done, reused node0 for this.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:12:30 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:12:30 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:12:47 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:12:47 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:14:47 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:14:47 +00:00

Fixed this in FindTx by not looking up stale txs if we have any pruned block hashes. In the unlikely case that a user looks up a tx in a stale block where the prefix collides with a tx in a pruned block, the user will have to fetch the pruned block or provide the stale block hash.

Fixed this in `FindTx` by not looking up stale txs if we have any pruned block hashes. In the unlikely case that a user looks up a tx in a stale block where the prefix collides with a tx in a pruned block, the user will have to fetch the pruned block or provide the stale block hash.
andrewtoth (Migrated from github.com) reviewed 2026-11-19 21:15:04 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-19 21:15:04 +00:00

Done.

Done.
andrewtoth commented 2026-11-19 22:30:32 +00:00 (Migrated from github.com)

Thanks for the detailed review @l0rinc! I've addressed all your suggestions.

The main issue is a behavior change for the unlikely case where a tx is in both an active-chain and stale block, and the active-chain block has been pruned but the stale block has not. In the previous version, we would return the tx from the stale block along with the stale block's hash. Now we return the pruned block hash.

I believe this is the correct behavior, but it has a trade-off. In the previous version the user would still get the tx, even if the correct block was pruned. Now the user will have to fetch the pruned block before being able to get the tx. This has an implication for the unlikely case where a tx in only a stale block is looked up, but the tx prefix collides with a tx in an active-chain pruned block. In this case the false-positive block hash will be returned, even though the user wants the tx in the stale block. In this case the user can fetch the false-positive block, or pass the stale block hash in the request.

Other changes are some more test coverage and documentation updates. The CI failures do not seem related.

git diff 8aa03c78de62448fc9f0223631844dc29f0cddb0..c612ccc378e66f663e80b9b4fb409a92fdb11b89

Thanks for the detailed review @l0rinc! I've addressed all your suggestions. The main issue is a behavior change for the unlikely case where a tx is in both an active-chain and stale block, and the active-chain block has been pruned but the stale block has not. In the previous version, we would return the tx from the stale block along with the stale block's hash. Now we return the pruned block hash. I believe this is the correct behavior, but it has a trade-off. In the previous version the user would still get the tx, even if the correct block was pruned. Now the user will have to fetch the pruned block before being able to get the tx. This has an implication for the unlikely case where a tx in only a stale block is looked up, but the tx prefix collides with a tx in an active-chain pruned block. In this case the false-positive block hash will be returned, even though the user wants the tx in the stale block. In this case the user can fetch the false-positive block, or pass the stale block hash in the request. Other changes are some more test coverage and documentation updates. The CI failures do not seem related. `git diff 8aa03c78de62448fc9f0223631844dc29f0cddb0..c612ccc378e66f663e80b9b4fb409a92fdb11b89`
DrahtBot commented 2026-11-23 10:42:00 +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).
andrewtoth commented 2026-11-23 16:29:17 +00:00 (Migrated from github.com)

Rebased due to #35474. Also rebased on top of #36890 to fix the CI failures.

git range-diff fb19fed3df..c612ccc378 08ca210a92..46bfd40244

Rebased due to #35474. Also rebased on top of #36890 to fix the CI failures. `git range-diff fb19fed3df..c612ccc378 08ca210a92..46bfd40244`
fjahr (Migrated from github.com) reviewed 2026-11-23 21:39:20 +00:00
fjahr (Migrated from github.com) left a comment

Code review ACK c3de4d7dc7

I added a list of suggestions and a couple neutral notes. I don't consider any of them strictly blocking but I think addressing some of the more interesting ones would be good improvements.

Code review ACK c3de4d7dc7dd509ae68a29dfd08a6d517a38835a I added a list of suggestions and a couple neutral notes. I don't consider any of them strictly blocking but I think addressing some of the more interesting ones would be good improvements.
fjahr (Migrated from github.com) commented 2026-11-23 17:59:29 +00:00

nit: Could mention why this is the case, may not be obvious to newer devs

nit: Could mention why this is the case, may not be obvious to newer devs
fjahr (Migrated from github.com) commented 2026-11-23 20:40:52 +00:00

nit: Using an optional here would have been more explicit but feel free to ignore

nit: Using an optional here would have been more explicit but feel free to ignore
fjahr (Migrated from github.com) commented 2026-11-23 20:52:32 +00:00

nit: Just noting that using util::Expected<TxFound, TxMiss> here instead of this would have been an option too but I don't have strict preference for that.

nit: Just noting that using `util::Expected<TxFound, TxMiss>` here instead of this would have been an option too but I don't have strict preference for that.
fjahr (Migrated from github.com) commented 2026-11-23 17:29:47 +00:00

nit: At verbosity 2 the call would still fail because of the missing undo data. But also fine to not mention it if we don't want the RPC help on verbosity 2 ;)

nit: At verbosity 2 the call would still fail because of the missing undo data. But also fine to not mention it if we don't want the RPC help on verbosity 2 ;)
fjahr (Migrated from github.com) commented 2026-11-23 17:25:13 +00:00

No need to change ::cs_main, we prefer that version

No need to change `::cs_main`, we prefer that version
fjahr (Migrated from github.com) commented 2026-11-23 17:47:27 +00:00

nit: I would prefer the following since we really need both block and undo data and the change only always works because we never prune undo data before it's block data. But I think this would be clearer:

    if (tx->IsCoinBase() || !blockindex || WITH_LOCK(::cs_main, return (nStatus & BLOCK_HAVE_MASK) != BLOCK_HAVE_MASK)) {

I think this is the intended code here anyway. Alternatively there could also be a one-line comment that mentions that this works because undo data presence always implies block data presence.

nit: I would prefer the following since we really need both block and undo data and the change only always works because we never prune undo data before it's block data. But I think this would be clearer: ```suggestion if (tx->IsCoinBase() || !blockindex || WITH_LOCK(::cs_main, return (nStatus & BLOCK_HAVE_MASK) != BLOCK_HAVE_MASK)) { ``` I think this is the intended code here anyway. Alternatively there could also be a one-line comment that mentions that this works because undo data presence always implies block data presence.
fjahr (Migrated from github.com) commented 2026-10-29 15:07:20 +00:00

nit: This error reads a bit odd if the user supplied the block hash themselves. IMO the old "Block not available." was better in that case. But not worth adding more ifs for a bit nicer message, only if you feel like addressing it.

nit: This error reads a bit odd if the user supplied the block hash themselves. IMO the old "Block not available." was better in that case. But not worth adding more ifs for a bit nicer message, only if you feel like addressing it.
fjahr (Migrated from github.com) commented 2026-11-23 17:33:21 +00:00

Extending this feedback: Since the list of the block hashes is in the data field which is the more parsable version anyway I don't think we need to have the hashes inside the error string. We could save a few lines of code by making the error message more generic and just sending the user to the data list.

Extending this feedback: Since the list of the block hashes is in the data field which is the more parsable version anyway I don't think we need to have the hashes inside the error string. We could save a few lines of code by making the error message more generic and just sending the user to the data list.
fjahr (Migrated from github.com) commented 2026-11-23 20:14:03 +00:00

Could unset both data and undo (~BLOCK_HAVE_MASK) here? Just seems more correct behavior.

Could unset both data and undo (`~BLOCK_HAVE_MASK`) here? Just seems more correct behavior.
fjahr (Migrated from github.com) commented 2026-11-23 20:17:20 +00:00

nit: Also why use Assert instead of BOOST_REQUIRE here?

nit: Also why use `Assert` instead of `BOOST_REQUIRE` here?
fjahr (Migrated from github.com) commented 2026-10-29 14:51:10 +00:00

Would make sense to fail early with a better error message where the previous init error was raised in this case where someone tries to enable txindex on an already pruned node. I would suspect that this happens a bit more often when this merged since some users may just read the headline "txindex now works with pruning" or something and try this out.

Would make sense to fail early with a better error message where the previous init error was raised in this case where someone tries to enable txindex on an already pruned node. I would suspect that this happens a bit more often when this merged since some users may just read the headline "txindex now works with pruning" or something and try this out.
arejula27 (Migrated from github.com) reviewed 2026-11-24 17:26:22 +00:00
arejula27 (Migrated from github.com) commented 2026-11-24 17:26:22 +00:00

I agree with you (I prefer util::Expected<TxFound, TxMiss>) , no strong opinion either. I raised the same question in #35570, and the preferred option was to use the error channel of util::Expected only for errors, not for normal results (1). #35646 was built on that idea (2, 3). Following that, I would say that a TxMiss is a normal result of a lookup, not an error.

However, I think we should document when to use util::Expected, otherwise this discussion will come up again in every PR.

I agree with you (I prefer `util::Expected<TxFound, TxMiss>`) , no strong opinion either. I raised the same question in [#35570](https://github.com/bitcoin/bitcoin/pull/35570#pullrequestreview-4555262677), and the preferred option was to use the error channel of `util::Expected` only for errors, not for normal results ([1](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4783419874)). #35646 was built on that idea ([2](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-6119770094), [3](https://github.com/bitcoin/bitcoin/pull/35646#pullrequestreview-4650703493)). Following that, I would say that a `TxMiss` is a normal result of a lookup, not an error. However, I think we should document when to use `util::Expected`, otherwise this discussion will come up again in every PR.
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:14:13 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:14:13 +00:00

Done. We now fail if we're already pruned, and show a message to the user to run with -reindex.

Done. We now fail if we're already pruned, and show a message to the user to run with `-reindex`.
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:17:40 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:17:40 +00:00

I kept the shared error message with the hashes in the wording. For bitcoin-cli and REST the structured data is not displayed, so we need the hashes in the message for these cases.

I kept the shared error message with the hashes in the wording. For `bitcoin-cli` and REST the structured data is not displayed, so we need the hashes in the message for these cases.
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:19:33 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:19:33 +00:00

It does not fail anymore because of the missing undo data. This is handled in the first commit :).

It does not fail anymore because of the missing undo data. This is handled in the first commit :).
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:19:53 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:19:53 +00:00

Taken, thanks.

Taken, thanks.
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:20:15 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:20:15 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:20:33 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:20:33 +00:00

Done.

Done.
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:21:12 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:21:12 +00:00

Kept the existing null convention here. That's used generally throughout the codebase for uint256 types.

Kept the existing null convention here. That's used generally throughout the codebase for `uint256` types.
andrewtoth (Migrated from github.com) reviewed 2026-11-26 03:22:57 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-26 03:22:57 +00:00

I kept this as a variant. I agree with @arejula27 that TxMiss is a normal result and not an error, so this is the more appropriate type here.

I kept this as a variant. I agree with @arejula27 that `TxMiss` is a normal result and not an error, so this is the more appropriate type here.
andrewtoth commented 2026-11-26 03:28:13 +00:00 (Migrated from github.com)

Thanks @fjahr @arejula27 for your review and comments!

@fjahr I have taken several of your suggestions.

The main user facing change is when enabling a new txindex with already pruned blocks we fail early with advice to use -reindex.

git range-diff 08ca210a92..c3de4d7dc7 08ca210a92..a215a43f03

Thanks @fjahr @arejula27 for your review and comments! @fjahr I have taken several of your suggestions. The main user facing change is when enabling a new txindex with already pruned blocks we fail early with advice to use `-reindex`. `git range-diff 08ca210a92..c3de4d7dc7 08ca210a92..a215a43f03`
fjahr commented 2026-11-26 10:30:35 +00:00 (Migrated from github.com)
ACK a215a43f03313583625ad93596d8e1ac9516d09a
optout21 (Migrated from github.com) reviewed 2026-11-26 11:13:10 +00:00
optout21 (Migrated from github.com) left a comment

reACK a215a43f03
Reviewed changes since my last review, glanced over the whole set, checked build and test locally. All is fine, found only two non-blocking minor issues.

(git range-diff e310efb..322cbbf 08ca210..a215a43)

reACK a215a43f03313583625ad93596d8e1ac9516d09a Reviewed changes since my last review, glanced over the whole set, checked build and test locally. All is fine, found only two non-blocking minor issues. (`git range-diff e310efb..322cbbf 08ca210..a215a43`)
optout21 (Migrated from github.com) commented 2026-11-26 11:07:04 +00:00

30916d4 txindex: return pruned block hashes from FindTx:

Nit: A default-constructed TxLookupResult struct will be TxFound, which is not explicit and not entirely intuitive. A constructor would make this more explicit.

> [30916d4](https://github.com/bitcoin/bitcoin/pull/36002/changes/30916d4f870227bf9a23032db8c36a1d440bd190) _txindex: return pruned block hashes from FindTx_: Nit: A default-constructed `TxLookupResult` struct will be `TxFound`, which is not explicit and not entirely intuitive. A constructor would make this more explicit.
optout21 (Migrated from github.com) commented 2026-11-26 11:11:05 +00:00

ef380b4 txindex: allow prune mode when there are no legacy entries:

Nit: node0 will start a resource-intensive full txindex build here, in an already very heavy test. Is this really needed? Is its result checked?

> [ef380b4](https://github.com/bitcoin/bitcoin/pull/36002/changes/ef380b48a65e3c4ab990256f754d17262735e4bc) _txindex: allow prune mode when there are no legacy entries_: Nit: `node0` will start a resource-intensive full txindex build here, in an already very heavy test. Is this really needed? Is its result checked?
andrewtoth (Migrated from github.com) reviewed 2026-11-27 18:16:52 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-27 18:16:52 +00:00

Will do if I push again.

Will do if I push again.
andrewtoth (Migrated from github.com) reviewed 2026-11-27 18:16:58 +00:00
andrewtoth (Migrated from github.com) commented 2026-11-27 18:16:58 +00:00

This is tested implicitly by restart_node. It waits until it is fully synced.

This was requested by l0rinc: enabling a fresh txindex on an existing blockchain with automatic pruning.

I don't see any noticeable runtime speed issue locally.

This is tested implicitly by `restart_node`. It waits until it is fully synced. This was requested by l0rinc: enabling a fresh txindex on an existing blockchain with automatic pruning. I don't see any noticeable runtime speed issue locally.
l0rinc (Migrated from github.com) requested changes 2026-12-03 18:22:31 +00:00
l0rinc (Migrated from github.com) left a comment

Did another manual and AI round: I had to jump between commits to tell which lookup changes affect behavior.
It would be easier to review the result-type refactor together and see the first use of error.data in the commit that adds it.
The series also enables pruning before the lookup and RPC paths are ready, so a normal lookup can still report possible corruption at that point.

I'm still unsure about throwing for a pruned lookup when fetching the block and retrying is expected. The other suggestions are about testing each index's prune lock on its own and simplifying the RPC test.

Did another manual and AI round: I had to jump between commits to tell which lookup changes affect behavior. It would be easier to review the result-type refactor together and see the first use of `error.data` in the commit that adds it. The series also enables pruning before the lookup and RPC paths are ready, so a normal lookup can still report possible corruption at that point. I'm still unsure about throwing for a pruned lookup when fetching the block and retrying is expected. The other suggestions are about testing each index's prune lock on its own and simplifying the RPC test.
l0rinc (Migrated from github.com) commented 2026-12-03 15:33:51 +00:00

With both indexes on node 0, txindex can mask a missing filter-index prune lock. Running blockfilterindex on its own would let us test its prune lock, and the txindex resume check could run on node 2.

Fetch the blocks on node 2
diff --git a/test/functional/feature_index_prune.py b/test/functional/feature_index_prune.py
index 67d50b4b20..cf55d6a791 100755
--- a/test/functional/feature_index_prune.py
+++ b/test/functional/feature_index_prune.py
@@ -32,9 +32,9 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
     def set_test_params(self):
         self.num_nodes = 4
         self.extra_args = [
-            ["-fastprune", "-prune=1", "-blockfilterindex=1", "-txindex=1"],
+            ["-fastprune", "-prune=1", "-blockfilterindex=1"],
             ["-fastprune", "-prune=1", "-coinstatsindex=1"],
-            ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1"],
+            ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1", "-txindex=1"],
             [],
         ]
 
@@ -143,9 +143,8 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
 
         self.log.info("fetching the missing blocks with getblockfrompeer doesn't work for block filter index and coinstatsindex")
         last_indexed_height = 1500
-        # Only checking the first two nodes since this test takes a long time
-        # and the third node is kind of redundant in this context
-        for i, msg in enumerate([filter_msg, stats_msg]):
+        # Fetch the blocks on node 2 so we can use it for the txindex check below.
+        for i, msg in [(1, stats_msg), (2, filter_msg)]:
             self.restart_node(i, extra_args=["-prune=1", "-fastprune"])
             node = self.nodes[i]
             prune_height = node.getblockchaininfo()["pruneheight"]
@@ -168,8 +167,8 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
             node.assert_start_raises_init_error(extra_args=self.extra_args[i], expected_msg=msg+end_msg)
 
         self.log.info("txindex can resume after fetching missing block bodies without undo data")
-        txindex_node = self.nodes[0]
-        self.start_node(0, extra_args=["-prune=1", "-fastprune", "-txindex=1"])
+        txindex_node = self.nodes[2]
+        self.start_node(2, extra_args=["-prune=1", "-fastprune", "-txindex=1"])
         refetched_block = txindex_node.getblock(txindex_node.getblockhash(last_indexed_height + 1))
         assert_equal(txindex_node.getrawtransaction(refetched_block["tx"][0], 1)["blockhash"], refetched_block["hash"])
 
With both indexes on node 0, txindex can mask a missing filter-index prune lock. Running `blockfilterindex` on its own would let us test its prune lock, and the txindex resume check could run on node 2. <details> <summary>Fetch the blocks on node 2</summary> ```diff diff --git a/test/functional/feature_index_prune.py b/test/functional/feature_index_prune.py index 67d50b4b20..cf55d6a791 100755 --- a/test/functional/feature_index_prune.py +++ b/test/functional/feature_index_prune.py @@ -32,9 +32,9 @@ class FeatureIndexPruneTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 self.extra_args = [ - ["-fastprune", "-prune=1", "-blockfilterindex=1", "-txindex=1"], + ["-fastprune", "-prune=1", "-blockfilterindex=1"], ["-fastprune", "-prune=1", "-coinstatsindex=1"], - ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1"], + ["-fastprune", "-prune=1", "-blockfilterindex=1", "-coinstatsindex=1", "-txindex=1"], [], ] @@ -143,9 +143,8 @@ class FeatureIndexPruneTest(BitcoinTestFramework): self.log.info("fetching the missing blocks with getblockfrompeer doesn't work for block filter index and coinstatsindex") last_indexed_height = 1500 - # Only checking the first two nodes since this test takes a long time - # and the third node is kind of redundant in this context - for i, msg in enumerate([filter_msg, stats_msg]): + # Fetch the blocks on node 2 so we can use it for the txindex check below. + for i, msg in [(1, stats_msg), (2, filter_msg)]: self.restart_node(i, extra_args=["-prune=1", "-fastprune"]) node = self.nodes[i] prune_height = node.getblockchaininfo()["pruneheight"] @@ -168,8 +167,8 @@ class FeatureIndexPruneTest(BitcoinTestFramework): node.assert_start_raises_init_error(extra_args=self.extra_args[i], expected_msg=msg+end_msg) self.log.info("txindex can resume after fetching missing block bodies without undo data") - txindex_node = self.nodes[0] - self.start_node(0, extra_args=["-prune=1", "-fastprune", "-txindex=1"]) + txindex_node = self.nodes[2] + self.start_node(2, extra_args=["-prune=1", "-fastprune", "-txindex=1"]) refetched_block = txindex_node.getblock(txindex_node.getblockhash(last_indexed_height + 1)) assert_equal(txindex_node.getrawtransaction(refetched_block["tx"][0], 1)["blockhash"], refetched_block["hash"]) ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 15:20:21 +00:00

30916d4 txindex: return pruned block hashes from FindTx:

I had to read both commits to tell which GetTransaction changes affect lookup behavior.
I’d switch FindTx, FindLegacyTx, and GetTransaction to TxLookupResult together, updating their callers while keeping the same lookup order and errors. When only a stale copy is readable, the lookup now reports the pruned active-chain candidate hash. That behavior change can then stand on its own, followed by reporting those hashes through RPC and REST.

Ralph also noticed that pruning is enabled before these lookups can handle it. Moving enablement after the lookup and RPC changes would avoid an intermediate commit reporting ordinary pruning as possible corruption.

Example: characterize the existing lookup behavior before changing it
diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp
index 2949c0e8b8..7e02166662 100644
--- a/src/test/txindex_tests.cpp
+++ b/src/test/txindex_tests.cpp
@@ -33,6 +33,7 @@
 #include <cstdint>
 #include <memory>
 #include <set>
+#include <stdexcept>
 #include <string>
 #include <string_view>
 #include <utility>
@@ -108,6 +109,15 @@ void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash)
     BOOST_REQUIRE(chainman.ActiveChainstate().InvalidateBlock(state, block_index));
 }
 
+void PruneBlock(ChainstateManager& chainman, const uint256& block_hash)
+{
+    LOCK(cs_main);
+    chainman.m_blockman.m_have_pruned = true;
+    CBlockIndex* block_index{chainman.m_blockman.LookupBlockIndex(block_hash)};
+    BOOST_REQUIRE(block_index);
+    block_index->nStatus &= ~BLOCK_HAVE_MASK;
+}
+
 } // namespace
 
 BOOST_AUTO_TEST_CASE(txindex_position_encoding)
@@ -220,7 +230,8 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup)
     BOOST_CHECK(target_bucket[0] != fake_pos);
     BOOST_CHECK(target_bucket[1] == fake_pos);
 
-    LookupTx(txindex, target_txid);
+    const uint256 target_block_hash{LookupTx(txindex, target_txid)};
+    const uint256 fake_block_hash{LookupTx(txindex, fake_txid)};
 
     // A database created fresh by this version cannot contain legacy entries, so
     // lookups skip the legacy fallback: drop the last coinbase's hashed entry and
@@ -233,6 +244,12 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup)
     db.Write(txindex::LegacyTxKey(fake_txid), fake_physical);
     CheckNotFound(txindex, fake_txid);
 
+    PruneBlock(*m_node.chainman, fake_block_hash);
+    BOOST_CHECK_THROW(txindex.FindTx(target_txid), std::runtime_error); // TODO: Find the readable match.
+
+    PruneBlock(*m_node.chainman, target_block_hash);
+    BOOST_CHECK_THROW(txindex.FindTx(target_txid), std::runtime_error); // TODO: Return both pruned hashes.
+
     StopIndex(txindex, m_node);
 }
 
@@ -359,6 +376,11 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup)
     BOOST_REQUIRE_EQUAL(reorg_bucket.size(), 2U);
     BOOST_CHECK(reorg_bucket.front() == original_bucket.front());
 
+    PruneBlock(chainman, stale_block_hash);
+    BOOST_CHECK_THROW(txindex.FindTx(unique_txid), std::runtime_error); // TODO: Report the pruned candidate.
+    PruneBlock(chainman, branch_block_hash);
+    BOOST_CHECK_THROW(txindex.FindTx(unique_txid), std::runtime_error); // TODO: Report only the active chain candidate.
+
     StopIndex(txindex, m_node);
 }
 
> [30916d4](https://github.com/bitcoin/bitcoin/pull/36002/changes/30916d4f870227bf9a23032db8c36a1d440bd190) _txindex: return pruned block hashes from FindTx_: I had to read both commits to tell which `GetTransaction` changes affect lookup behavior. I’d switch `FindTx`, `FindLegacyTx`, and `GetTransaction` to `TxLookupResult` together, updating their callers while keeping the same lookup order and errors. When only a stale copy is readable, the lookup now reports the pruned active-chain candidate hash. That behavior change can then stand on its own, followed by reporting those hashes through RPC and REST. [Ralph also noticed](https://review.fish.foo/report/36002-a215a43f03313583625ad93596d8e1ac9516d09a-3159-13.html#finding-finding%3A3) that pruning is enabled before these lookups can handle it. Moving enablement after the lookup and RPC changes would avoid an intermediate commit reporting ordinary pruning as possible corruption. <details> <summary>Example: characterize the existing lookup behavior before changing it</summary> ```diff diff --git a/src/test/txindex_tests.cpp b/src/test/txindex_tests.cpp index 2949c0e8b8..7e02166662 100644 --- a/src/test/txindex_tests.cpp +++ b/src/test/txindex_tests.cpp @@ -33,6 +33,7 @@ #include <cstdint> #include <memory> #include <set> +#include <stdexcept> #include <string> #include <string_view> #include <utility> @@ -108,6 +109,15 @@ void InvalidateBlock(ChainstateManager& chainman, const uint256& block_hash) BOOST_REQUIRE(chainman.ActiveChainstate().InvalidateBlock(state, block_index)); } +void PruneBlock(ChainstateManager& chainman, const uint256& block_hash) +{ + LOCK(cs_main); + chainman.m_blockman.m_have_pruned = true; + CBlockIndex* block_index{chainman.m_blockman.LookupBlockIndex(block_hash)}; + BOOST_REQUIRE(block_index); + block_index->nStatus &= ~BLOCK_HAVE_MASK; +} + } // namespace BOOST_AUTO_TEST_CASE(txindex_position_encoding) @@ -220,7 +230,8 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup) BOOST_CHECK(target_bucket[0] != fake_pos); BOOST_CHECK(target_bucket[1] == fake_pos); - LookupTx(txindex, target_txid); + const uint256 target_block_hash{LookupTx(txindex, target_txid)}; + const uint256 fake_block_hash{LookupTx(txindex, fake_txid)}; // A database created fresh by this version cannot contain legacy entries, so // lookups skip the legacy fallback: drop the last coinbase's hashed entry and @@ -233,6 +244,12 @@ BOOST_FIXTURE_TEST_CASE(txindex_collision_scan_path, TestChain100Setup) db.Write(txindex::LegacyTxKey(fake_txid), fake_physical); CheckNotFound(txindex, fake_txid); + PruneBlock(*m_node.chainman, fake_block_hash); + BOOST_CHECK_THROW(txindex.FindTx(target_txid), std::runtime_error); // TODO: Find the readable match. + + PruneBlock(*m_node.chainman, target_block_hash); + BOOST_CHECK_THROW(txindex.FindTx(target_txid), std::runtime_error); // TODO: Return both pruned hashes. + StopIndex(txindex, m_node); } @@ -359,6 +376,11 @@ BOOST_FIXTURE_TEST_CASE(txindex_reorg_keeps_stale_entries, TestChain100Setup) BOOST_REQUIRE_EQUAL(reorg_bucket.size(), 2U); BOOST_CHECK(reorg_bucket.front() == original_bucket.front()); + PruneBlock(chainman, stale_block_hash); + BOOST_CHECK_THROW(txindex.FindTx(unique_txid), std::runtime_error); // TODO: Report the pruned candidate. + PruneBlock(chainman, branch_block_hash); + BOOST_CHECK_THROW(txindex.FindTx(unique_txid), std::runtime_error); // TODO: Report only the active chain candidate. + StopIndex(txindex, m_node); } ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 17:14:49 +00:00

ef380b4 txindex: allow prune mode when there are no legacy entries:

As I mentioned in the FindTx comment, this commit enables pruning while a lookup can still report a normally pruned block as possible corruption. I’d split out the AllowPrune() change and its unit checks to a separate simple commit, then keep the switch & startup errors together only once the lookup and RPC paths can handle pruned blocks.

> [ef380b4](https://github.com/bitcoin/bitcoin/pull/36002/changes/ef380b48a65e3c4ab990256f754d17262735e4bc) _txindex: allow prune mode when there are no legacy entries_: As I mentioned in the FindTx comment, this commit enables pruning while a lookup can still report a normally pruned block as possible corruption. I’d split out the `AllowPrune()` change and its unit checks to a separate simple commit, then keep the switch & startup errors together only once the lookup and RPC paths can handle pruned blocks.
l0rinc (Migrated from github.com) commented 2026-12-03 17:26:09 +00:00

63ecdae rpc: report pruned blocks from GetTransaction:

Both conditions return result - a single short-circuiting condition would make the fallback easier to see and keep the getter out of the path where no block was specified. The PSBT caller can also use the getter directly, it's very cheap, no need to extract it to a dedicated variable.

Simplify the txindex result checks
diff --git a/src/node/transaction.cpp b/src/node/transaction.cpp
index 5184a18073..faa0636fba 100644
--- a/src/node/transaction.cpp
+++ b/src/node/transaction.cpp
@@ -150,12 +150,11 @@ TxLookupResult GetTransaction(const CBlockIndex* const block_index, const CTxMem
         if (auto ptx{mempool->get(hash)}) return TxFound{std::move(ptx), {}};
     }
     if (txindex) {
-        auto result{txindex->FindTx(hash)};
-        if (!block_index) return result;
         // Don't return the transaction if the provided block hash doesn't match.
         // The case where a transaction appears in multiple blocks (e.g. reorgs or
         // BIP30) is handled by the block lookup below.
-        if (const auto* found{result.GetFound()}; found && block_index->GetBlockHash() == found->block_hash) return result;
+        if (auto result{txindex->FindTx(hash)};
+            !block_index || (result.GetFound() && result.GetFound()->block_hash == block_index->GetBlockHash())) return result;
     }
     if (block_index) {
         CBlock block;
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 66c48cab65..9329116d13 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -177,8 +177,8 @@ PartiallySignedTransaction ProcessPSBT(const std::string& psbt_string, const std
         // The `non_witness_utxo` is the whole previous transaction
         if (psbt_input.non_witness_utxo) continue;
 
-        if (auto result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), node.txindex.get(), psbt_input.prev_txid, chainman.m_blockman)}; auto* found{result.GetFound()}) {
-            psbt_input.non_witness_utxo = std::move(found->tx);
+        if (auto result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), node.txindex.get(), psbt_input.prev_txid, chainman.m_blockman)}; result.GetFound()) {
+            psbt_input.non_witness_utxo = std::move(result.GetFound()->tx);
         } else {
             coins[psbt_input.GetOutPoint()]; // Create empty map entry keyed by prevout
         }
> [63ecdae](https://github.com/bitcoin/bitcoin/pull/36002/changes/63ecdaec0a3831db9b17d0d40adfc71bb18ef7c3) _rpc: report pruned blocks from GetTransaction_: Both conditions return `result` - a single short-circuiting condition would make the fallback easier to see and keep the getter out of the path where no block was specified. The PSBT caller can also use the getter directly, it's very cheap, no need to extract it to a dedicated variable. <details> <summary>Simplify the txindex result checks</summary> ```diff diff --git a/src/node/transaction.cpp b/src/node/transaction.cpp index 5184a18073..faa0636fba 100644 --- a/src/node/transaction.cpp +++ b/src/node/transaction.cpp @@ -150,12 +150,11 @@ TxLookupResult GetTransaction(const CBlockIndex* const block_index, const CTxMem if (auto ptx{mempool->get(hash)}) return TxFound{std::move(ptx), {}}; } if (txindex) { - auto result{txindex->FindTx(hash)}; - if (!block_index) return result; // Don't return the transaction if the provided block hash doesn't match. // The case where a transaction appears in multiple blocks (e.g. reorgs or // BIP30) is handled by the block lookup below. - if (const auto* found{result.GetFound()}; found && block_index->GetBlockHash() == found->block_hash) return result; + if (auto result{txindex->FindTx(hash)}; + !block_index || (result.GetFound() && result.GetFound()->block_hash == block_index->GetBlockHash())) return result; } if (block_index) { CBlock block; diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 66c48cab65..9329116d13 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -177,8 +177,8 @@ PartiallySignedTransaction ProcessPSBT(const std::string& psbt_string, const std // The `non_witness_utxo` is the whole previous transaction if (psbt_input.non_witness_utxo) continue; - if (auto result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), node.txindex.get(), psbt_input.prev_txid, chainman.m_blockman)}; auto* found{result.GetFound()}) { - psbt_input.non_witness_utxo = std::move(found->tx); + if (auto result{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), node.txindex.get(), psbt_input.prev_txid, chainman.m_blockman)}; result.GetFound()) { + psbt_input.non_witness_utxo = std::move(result.GetFound()->tx); } else { coins[psbt_input.GetOutPoint()]; // Create empty map entry keyed by prevout } ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 14:59:23 +00:00

I was a bit confused here at first, I expected Expected<T, E> (pun intended), but the positions don’t mean value and error - and std::variant actually default-constructs its first alternative, so putting TxMiss first gives us an empty miss instead of a TxFound with a null transaction. Reordering also changes the numeric indices, but existing callers select by type, so they don’t need adjusting.

I was a bit confused here at first, I expected `Expected<T, E>` (pun intended), but the positions don’t mean value and error - and `std::variant` actually default-constructs its first alternative, so putting `TxMiss` first gives us an empty miss instead of a `TxFound` with a null transaction. Reordering also changes the numeric indices, but existing callers select by type, so they don’t need adjusting.
l0rinc (Migrated from github.com) commented 2026-12-03 15:21:41 +00:00

After arejula27’s review, both RPCs now report the known pruned block before trying to read it - we could dedup it for simplicity and maintainability.

Share the check for block data
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index 0962994676..6e7718e77e 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -717,6 +717,15 @@ void CheckBlockDataAvailability(BlockManager& blockman, const CBlockIndex& block
     }
 }
 
+void CheckTxBlockDataAvailability(BlockManager& blockman, const CBlockIndex& blockindex)
+{
+    AssertLockHeld(cs_main);
+    if (blockman.IsBlockPruned(blockindex)) {
+        throw JSONRPCPrunedBlocksError({blockindex.GetBlockHash()});
+    }
+    CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false);
+}
+
 static CBlock GetBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex)
 {
     CBlock block;
diff --git a/src/rpc/blockchain.h b/src/rpc/blockchain.h
index 61f5e51b4c..67f0e40103 100644
--- a/src/rpc/blockchain.h
+++ b/src/rpc/blockchain.h
@@ -62,4 +62,7 @@ UniValue CreateUTXOSnapshot(
 std::optional<int> GetPruneHeight(const node::BlockManager& blockman, const CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
 void CheckBlockDataAvailability(node::BlockManager& blockman, const CBlockIndex& blockindex, bool check_for_undo) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
 
+//! Check block data for a transaction lookup and report the hash of a pruned block for refetching.
+void CheckTxBlockDataAvailability(node::BlockManager& blockman, const CBlockIndex& blockindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
+
 #endif // BITCOIN_RPC_BLOCKCHAIN_H
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 715a0388c8..8e4962c0c8 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -308,13 +308,6 @@ static RPCMethod getrawtransaction()
 
     int verbosity{ParseVerbosity(request.params[1], /*default_verbosity=*/0, /*allow_bool=*/true)};
 
-    const auto check_block_data{[&](const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
-        if (chainman.m_blockman.IsBlockPruned(index)) {
-            throw JSONRPCPrunedBlocksError({index.GetBlockHash()});
-        }
-        CheckBlockDataAvailability(chainman.m_blockman, index, /*check_for_undo=*/false);
-    }};
-
     if (!request.params[2].isNull()) {
         LOCK(cs_main);
 
@@ -323,7 +316,7 @@ static RPCMethod getrawtransaction()
         if (!blockindex) {
             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
         }
-        check_block_data(*blockindex);
+        CheckTxBlockDataAvailability(chainman.m_blockman, *blockindex);
     }
 
     bool f_txindex_ready = false;
@@ -335,7 +328,7 @@ static RPCMethod getrawtransaction()
     try {
         tx_result = GetTransaction(blockindex, node.mempool.get(), node.txindex.get(), txid, chainman.m_blockman);
     } catch (const std::runtime_error&) {
-        if (blockindex) WITH_LOCK(::cs_main, check_block_data(*blockindex));
+        if (blockindex) WITH_LOCK(::cs_main, CheckTxBlockDataAvailability(chainman.m_blockman, *blockindex));
         throw;
     }
     if (const auto* miss{tx_result.GetMiss()}) {
diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp
index 6d5e2e75bc..81ae708508 100644
--- a/src/rpc/txoutproof.cpp
+++ b/src/rpc/txoutproof.cpp
@@ -126,10 +126,7 @@ static RPCMethod gettxoutproof()
 
             {
                 LOCK(cs_main);
-                if (chainman.m_blockman.IsBlockPruned(*pblockindex)) {
-                    throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()});
-                }
-                CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false);
+                CheckTxBlockDataAvailability(chainman.m_blockman, *pblockindex);
             }
             CBlock block;
             if (!chainman.m_blockman.ReadBlock(block, *pblockindex)) {
After [arejula27’s review](https://github.com/bitcoin/bitcoin/pull/36002#pullrequestreview-5419883453), both RPCs now report the known pruned block before trying to read it - we could dedup it for simplicity and maintainability. <details> <summary>Share the check for block data</summary> ```diff diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 0962994676..6e7718e77e 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -717,6 +717,15 @@ void CheckBlockDataAvailability(BlockManager& blockman, const CBlockIndex& block } } +void CheckTxBlockDataAvailability(BlockManager& blockman, const CBlockIndex& blockindex) +{ + AssertLockHeld(cs_main); + if (blockman.IsBlockPruned(blockindex)) { + throw JSONRPCPrunedBlocksError({blockindex.GetBlockHash()}); + } + CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false); +} + static CBlock GetBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex) { CBlock block; diff --git a/src/rpc/blockchain.h b/src/rpc/blockchain.h index 61f5e51b4c..67f0e40103 100644 --- a/src/rpc/blockchain.h +++ b/src/rpc/blockchain.h @@ -62,4 +62,7 @@ UniValue CreateUTXOSnapshot( std::optional<int> GetPruneHeight(const node::BlockManager& blockman, const CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); void CheckBlockDataAvailability(node::BlockManager& blockman, const CBlockIndex& blockindex, bool check_for_undo) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); +//! Check block data for a transaction lookup and report the hash of a pruned block for refetching. +void CheckTxBlockDataAvailability(node::BlockManager& blockman, const CBlockIndex& blockindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + #endif // BITCOIN_RPC_BLOCKCHAIN_H diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 715a0388c8..8e4962c0c8 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -308,13 +308,6 @@ static RPCMethod getrawtransaction() int verbosity{ParseVerbosity(request.params[1], /*default_verbosity=*/0, /*allow_bool=*/true)}; - const auto check_block_data{[&](const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { - if (chainman.m_blockman.IsBlockPruned(index)) { - throw JSONRPCPrunedBlocksError({index.GetBlockHash()}); - } - CheckBlockDataAvailability(chainman.m_blockman, index, /*check_for_undo=*/false); - }}; - if (!request.params[2].isNull()) { LOCK(cs_main); @@ -323,7 +316,7 @@ static RPCMethod getrawtransaction() if (!blockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found"); } - check_block_data(*blockindex); + CheckTxBlockDataAvailability(chainman.m_blockman, *blockindex); } bool f_txindex_ready = false; @@ -335,7 +328,7 @@ static RPCMethod getrawtransaction() try { tx_result = GetTransaction(blockindex, node.mempool.get(), node.txindex.get(), txid, chainman.m_blockman); } catch (const std::runtime_error&) { - if (blockindex) WITH_LOCK(::cs_main, check_block_data(*blockindex)); + if (blockindex) WITH_LOCK(::cs_main, CheckTxBlockDataAvailability(chainman.m_blockman, *blockindex)); throw; } if (const auto* miss{tx_result.GetMiss()}) { diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index 6d5e2e75bc..81ae708508 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -126,10 +126,7 @@ static RPCMethod gettxoutproof() { LOCK(cs_main); - if (chainman.m_blockman.IsBlockPruned(*pblockindex)) { - throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()}); - } - CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false); + CheckTxBlockDataAvailability(chainman.m_blockman, *pblockindex); } CBlock block; if (!chainman.m_blockman.ReadBlock(block, *pblockindex)) { ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 14:53:25 +00:00

Add the optional error.data argument to JSONRPCError on its own.

This introduces dead code now. By moving JSONRPCPrunedBlocksError and the gettxoutproof check for a known pruned block into this commit, reviewers would see why this change is needed without having to read ahead and jump back.

Since we’ve extracted this to a new commit, we might as well use pushKVEnd for all three keys here and use Join to transform it directly.

Use the new argument in gettxoutproof
diff --git a/src/rpc/request.cpp b/src/rpc/request.cpp
index dacb687c54..cedb97f3cc 100644
--- a/src/rpc/request.cpp
+++ b/src/rpc/request.cpp
@@ -75,11 +75,9 @@ UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue
 UniValue JSONRPCError(int code, const std::string& message, const UniValue& data)
 {
     UniValue error(UniValue::VOBJ);
-    error.pushKV("code", code);
-    error.pushKV("message", message);
-    if (!data.isNull()) {
-        error.pushKV("data", data);
-    }
+    error.pushKVEnd("code", code);
+    error.pushKVEnd("message", message);
+    if (!data.isNull()) error.pushKVEnd("data", data);
     return error;
 }
 
diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp
index 09837c5d20..a837973f28 100644
--- a/src/rpc/txoutproof.cpp
+++ b/src/rpc/txoutproof.cpp
@@ -118,6 +118,9 @@ static RPCMethod gettxoutproof()
 
             {
                 LOCK(cs_main);
+                if (chainman.m_blockman.IsBlockPruned(*pblockindex)) {
+                    throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()});
+                }
                 CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false);
             }
             CBlock block;
diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp
index e2cf363a97..409c816091 100644
--- a/src/rpc/util.cpp
+++ b/src/rpc/util.cpp
@@ -30,6 +30,7 @@
 #include <util/translation.h>
 
 #include <algorithm>
+#include <functional>
 #include <memory>
 #include <ranges>
 #include <set>
@@ -422,6 +423,25 @@ UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_s
     }
 }
 
+std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes)
+{
+    const std::string hashes{Join(pruned_block_hashes, ", ", std::mem_fn(&uint256::GetHex))};
+    if (pruned_block_hashes.size() == 1) {
+        return strprintf("Transaction may be in pruned block %s.", hashes);
+    }
+    return strprintf("Transaction may be in one of the following pruned blocks: %s.", hashes);
+}
+
+UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes)
+{
+    UniValue hashes{UniValue::VARR};
+    const auto hex_hashes{pruned_block_hashes | std::views::transform(&uint256::GetHex)};
+    hashes.push_backV(hex_hashes.begin(), hex_hashes.end());
+    UniValue data{UniValue::VOBJ};
+    data.pushKV("pruned_block_hashes", std::move(hashes));
+    return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), data);
+}
+
 /**
  * A pair of strings that can be aligned (through padding) with other Sections
  * later on
diff --git a/src/rpc/util.h b/src/rpc/util.h
index f3d9ecc870..8cd9bbb33a 100644
--- a/src/rpc/util.h
+++ b/src/rpc/util.h
@@ -21,6 +21,7 @@
 #include <functional>
 #include <map>
 #include <optional>
+#include <set>
 #include <stdexcept>
 #include <string>
 #include <string_view>
@@ -146,6 +147,11 @@ RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr);
 UniValue JSONRPCPSBTError(common::PSBTError err);
 UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");
 
+//! Error message when a transaction lookup only matched blocks whose data was pruned.
+std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes);
+//! JSON-RPC error for a pruned-block transaction lookup miss.
+UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes);
+
 //! Parse a JSON range specified as int64, or [int64, int64]
 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
 
> Add the optional error.data argument to JSONRPCError on its own. This introduces dead code now. By moving `JSONRPCPrunedBlocksError` and the `gettxoutproof` check for a known pruned block into this commit, reviewers would see why this change is needed without having to read ahead and jump back. Since we’ve extracted this to a new commit, we might as well use `pushKVEnd` for all three keys here and use `Join` to transform it directly. <details> <summary>Use the new argument in gettxoutproof</summary> ```diff diff --git a/src/rpc/request.cpp b/src/rpc/request.cpp index dacb687c54..cedb97f3cc 100644 --- a/src/rpc/request.cpp +++ b/src/rpc/request.cpp @@ -75,11 +75,9 @@ UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue UniValue JSONRPCError(int code, const std::string& message, const UniValue& data) { UniValue error(UniValue::VOBJ); - error.pushKV("code", code); - error.pushKV("message", message); - if (!data.isNull()) { - error.pushKV("data", data); - } + error.pushKVEnd("code", code); + error.pushKVEnd("message", message); + if (!data.isNull()) error.pushKVEnd("data", data); return error; } diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index 09837c5d20..a837973f28 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -118,6 +118,9 @@ static RPCMethod gettxoutproof() { LOCK(cs_main); + if (chainman.m_blockman.IsBlockPruned(*pblockindex)) { + throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()}); + } CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false); } CBlock block; diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp index e2cf363a97..409c816091 100644 --- a/src/rpc/util.cpp +++ b/src/rpc/util.cpp @@ -30,6 +30,7 @@ #include <util/translation.h> #include <algorithm> +#include <functional> #include <memory> #include <ranges> #include <set> @@ -422,6 +423,25 @@ UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_s } } +std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes) +{ + const std::string hashes{Join(pruned_block_hashes, ", ", std::mem_fn(&uint256::GetHex))}; + if (pruned_block_hashes.size() == 1) { + return strprintf("Transaction may be in pruned block %s.", hashes); + } + return strprintf("Transaction may be in one of the following pruned blocks: %s.", hashes); +} + +UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes) +{ + UniValue hashes{UniValue::VARR}; + const auto hex_hashes{pruned_block_hashes | std::views::transform(&uint256::GetHex)}; + hashes.push_backV(hex_hashes.begin(), hex_hashes.end()); + UniValue data{UniValue::VOBJ}; + data.pushKV("pruned_block_hashes", std::move(hashes)); + return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), data); +} + /** * A pair of strings that can be aligned (through padding) with other Sections * later on diff --git a/src/rpc/util.h b/src/rpc/util.h index f3d9ecc870..8cd9bbb33a 100644 --- a/src/rpc/util.h +++ b/src/rpc/util.h @@ -21,6 +21,7 @@ #include <functional> #include <map> #include <optional> +#include <set> #include <stdexcept> #include <string> #include <string_view> @@ -146,6 +147,11 @@ RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr); UniValue JSONRPCPSBTError(common::PSBTError err); UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = ""); +//! Error message when a transaction lookup only matched blocks whose data was pruned. +std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes); +//! JSON-RPC error for a pruned-block transaction lookup miss. +UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes); + //! Parse a JSON range specified as int64, or [int64, int64] std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value); ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 15:51:38 +00:00

63ecdae rpc: report pruned blocks from GetTransaction:

A pruned block is a normal outcome for this lookup now, since the caller can fetch it and retry. I'd prefer to return it as a result rather than throw here. An opt-in mode could return an object with either proof or pruned_block_hashes, while existing callers keep getting the hex string on success. I don't like using exceptions for control flow, and it doesn't fit the existing exceptional cases here either.

Example opt-in result
diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp
index 4ad85cbb6a..8f2add4386 100644
--- a/src/rpc/client.cpp
+++ b/src/rpc/client.cpp
@@ -251,6 +251,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
     { "gettxout", 1, "n" },
     { "gettxout", 2, "include_mempool" },
     { "gettxoutproof", 0, "txids" },
+    { "gettxoutproof", 2, "return_pruned" },
     { "gettxoutsetinfo", 1, "hash_or_height", ParamFormat::JSON_OR_STRING },
     { "gettxoutsetinfo", 2, "use_index"},
     { "dumptxoutset", 0, "path", ParamFormat::STRING },
diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp
index 6d5e2e75bc..d0bd77d784 100644
--- a/src/rpc/txoutproof.cpp
+++ b/src/rpc/txoutproof.cpp
@@ -47,9 +47,10 @@ static RPCMethod gettxoutproof()
         "unspent output in the utxo for this transaction. Otherwise, you need to maintain\n"
         "a transaction index, using the -txindex command line option, or specify the block\n"
         "in which the transaction is included manually (by blockhash). The block data must be available.\n\n"
-        "If pruning is enabled, this call may return error -1 indicating that a requested transaction may be found\n"
+        "If pruning is enabled and return_pruned is false, this call may return error -1 indicating that a requested transaction may be found\n"
         "in one or more pruned blocks. The block hashes are included in the error message and the\n"
-        "error.data.pruned_block_hashes array. These blocks are not guaranteed to contain all requested transactions.\n"
+        "error.data.pruned_block_hashes array. With return_pruned=true, the hashes are returned in the result instead.\n"
+        "These blocks are not guaranteed to contain all requested transactions.\n"
         "Use getblockfrompeer to fetch the blocks, then retry the request.\n",
         {
             {"txids", RPCArg::Type::ARR, RPCArg::Optional::NO, "The txids to filter",
@@ -58,13 +59,26 @@ static RPCMethod gettxoutproof()
                 },
             },
             {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "If specified, looks for txid in the block with this hash"},
+            {"return_pruned", RPCArg::Type::BOOL, RPCArg::Default{false}, "Return an object with the proof or the candidate pruned block hashes"},
         },
-        RPCResult{
-            RPCResult::Type::STR, "data", "A string that is a serialized, hex-encoded data for the proof."
+        RPCResults{
+            {"return_pruned=false", RPCResult::Type::STR_HEX, "", "The serialized, hex-encoded proof"},
+            {"return_pruned=true and the proof is available", RPCResult::Type::OBJ, "", "",
+                {
+                    {RPCResult::Type::STR_HEX, "proof", "The serialized, hex-encoded proof"},
+                }},
+            {"return_pruned=true and candidate blocks were pruned", RPCResult::Type::OBJ, "", "",
+                {
+                    {RPCResult::Type::ARR, "pruned_block_hashes", "Hashes of pruned blocks that may contain the transaction",
+                        {
+                            {RPCResult::Type::STR_HEX, "blockhash", "A candidate block hash"},
+                        }},
+                }},
         },
         RPCExamples{""},
         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
         {
+            const bool return_pruned{self.Arg<bool>("return_pruned")};
             std::set<Txid> setTxids;
             UniValue txids = request.params[0].get_array();
             if (txids.empty()) {
@@ -82,8 +96,8 @@ static RPCMethod gettxoutproof()
             NodeContext& node = EnsureAnyNodeContext(request.context);
             ChainstateManager& chainman = EnsureChainman(node);
             if (!request.params[1].isNull()) {
-                LOCK(cs_main);
                 hashBlock = ParseHashV(request.params[1], "blockhash");
+                LOCK(cs_main);
                 pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock);
                 if (!pblockindex) {
                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
@@ -111,6 +125,7 @@ static RPCMethod gettxoutproof()
             if (pblockindex == nullptr) {
                 const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, node.txindex.get(), *setTxids.begin(), chainman.m_blockman)};
                 if (const auto* miss{result.GetMiss()}) {
+                    if (return_pruned && !miss->pruned_block_hashes.empty()) return PrunedBlockHashesData(miss->pruned_block_hashes);
                     throw miss->pruned_block_hashes.empty()
                               ? JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block")
                               : JSONRPCPrunedBlocksError(miss->pruned_block_hashes);
@@ -127,6 +142,7 @@ static RPCMethod gettxoutproof()
             {
                 LOCK(cs_main);
                 if (chainman.m_blockman.IsBlockPruned(*pblockindex)) {
+                    if (return_pruned) return PrunedBlockHashesData({pblockindex->GetBlockHash()});
                     throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()});
                 }
                 CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false);
@@ -150,7 +166,10 @@ static RPCMethod gettxoutproof()
             CMerkleBlock mb(block, setTxids);
             ssMB << mb;
             std::string strHex = HexStr(ssMB);
-            return strHex;
+            if (!return_pruned) return strHex;
+            UniValue result{UniValue::VOBJ};
+            result.pushKVEnd("proof", std::move(strHex));
+            return result;
         },
     };
 }
diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp
index 746bc66d71..4a721abb7c 100644
--- a/src/rpc/util.cpp
+++ b/src/rpc/util.cpp
@@ -431,7 +431,7 @@ std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashe
     return strprintf("Transaction may be in one of the following pruned blocks: %s.", hashes);
 }

-UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes)
+UniValue PrunedBlockHashesData(const std::set<uint256>& pruned_block_hashes)
 {
     UniValue hashes{UniValue::VARR};
     for (const auto& hash : pruned_block_hashes) {
@@ -439,7 +439,12 @@ UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes)
     }
     UniValue data{UniValue::VOBJ};
     data.pushKV("pruned_block_hashes", std::move(hashes));
-    return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), data);
+    return data;
+}
+
+UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes)
+{
+    return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), PrunedBlockHashesData(pruned_block_hashes));
 }

 /**
diff --git a/src/rpc/util.h b/src/rpc/util.h
index 8cd9bbb33a..a4e8f0b3f5 100644
--- a/src/rpc/util.h
+++ b/src/rpc/util.h
@@ -149,6 +149,8 @@ UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string&

 //! Error message when a transaction lookup only matched blocks whose data was pruned.
 std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes);
+//! Object containing candidate pruned block hashes for a transaction lookup.
+UniValue PrunedBlockHashesData(const std::set<uint256>& pruned_block_hashes);
 //! JSON-RPC error for a pruned-block transaction lookup miss.
 UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes);

diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py
index 6b8937d51b..61cf801c78 100755
--- a/test/functional/feature_txindex_prune.py
+++ b/test/functional/feature_txindex_prune.py
@@ -45,6 +45,8 @@ class TxIndexPruneTest(BitcoinTestFramework):
         tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000)
         blockhash = self.generate(pruned, 1)[0]
         txid = tx["txid"]
+        parent_txid = f'{tx["tx"].vin[0].prevout.hash:064x}'
+        parent_blockhash = pruned.getrawtransaction(parent_txid, 1)["blockhash"]

         self.log.info("Mine enough blocks to prune the transaction's block")
         self.generate(full, 600)
@@ -53,6 +55,7 @@ class TxIndexPruneTest(BitcoinTestFramework):
         self.log.info("Pruned UTXO lookups work without txindex")
         self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"])
         assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [txid])
+        assert_equal(pruned.gettxoutproof([txid], return_pruned=True), {"pruned_block_hashes": [blockhash]})
         self.restart_node(0)
         self.connect_nodes(0, 1)

@@ -69,6 +72,9 @@ class TxIndexPruneTest(BitcoinTestFramework):
             except JSONRPCException as error:
                 assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {blockhash}.", "data": {"pruned_block_hashes": [blockhash]}})

+        assert_equal(pruned.gettxoutproof([parent_txid], return_pruned=True), {"pruned_block_hashes": [parent_blockhash]})
+        assert_raises_rpc_error(-5, "Transaction not yet in block", pruned.gettxoutproof, ["00" * 32], return_pruned=True)
+
         self.log.info("REST /tx returns the pruned block's hash")
         assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.")

@@ -89,7 +95,9 @@ class TxIndexPruneTest(BitcoinTestFramework):
         assert "fee" not in tx_verbose
         assert "prevout" not in tx_verbose["vin"][0]
         assert_equal(self.rest_tx(pruned, txid), tx["hex"])
-        assert_equal(pruned.verifytxoutproof(pruned.gettxoutproof([txid])), [txid])
+        proof = pruned.gettxoutproof([txid])
+        assert_equal(pruned.gettxoutproof([txid], return_pruned=True), {"proof": proof})
+        assert_equal(pruned.verifytxoutproof(proof), [txid])
         updated = pruned.utxoupdatepsbt(psbt)
         assert "non_witness_utxo" in pruned.decodepsbt(updated)["inputs"][0]

> [63ecdae](https://github.com/bitcoin/bitcoin/pull/36002/changes/63ecdaec0a3831db9b17d0d40adfc71bb18ef7c3) _rpc: report pruned blocks from GetTransaction_: A pruned block is a normal outcome for this lookup now, since the caller can fetch it and retry. I'd prefer to return it as a result rather than throw here. An opt-in mode could return an object with either `proof` or `pruned_block_hashes`, while existing callers keep getting the hex string on success. I don't like using exceptions for control flow, and it doesn't fit the existing exceptional cases here either. <details> <summary>Example opt-in result</summary> ```diff diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index 4ad85cbb6a..8f2add4386 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -251,6 +251,7 @@ static const CRPCConvertParam vRPCConvertParams[] = { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, + { "gettxoutproof", 2, "return_pruned" }, { "gettxoutsetinfo", 1, "hash_or_height", ParamFormat::JSON_OR_STRING }, { "gettxoutsetinfo", 2, "use_index"}, { "dumptxoutset", 0, "path", ParamFormat::STRING }, diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index 6d5e2e75bc..d0bd77d784 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -47,9 +47,10 @@ static RPCMethod gettxoutproof() "unspent output in the utxo for this transaction. Otherwise, you need to maintain\n" "a transaction index, using the -txindex command line option, or specify the block\n" "in which the transaction is included manually (by blockhash). The block data must be available.\n\n" - "If pruning is enabled, this call may return error -1 indicating that a requested transaction may be found\n" + "If pruning is enabled and return_pruned is false, this call may return error -1 indicating that a requested transaction may be found\n" "in one or more pruned blocks. The block hashes are included in the error message and the\n" - "error.data.pruned_block_hashes array. These blocks are not guaranteed to contain all requested transactions.\n" + "error.data.pruned_block_hashes array. With return_pruned=true, the hashes are returned in the result instead.\n" + "These blocks are not guaranteed to contain all requested transactions.\n" "Use getblockfrompeer to fetch the blocks, then retry the request.\n", { {"txids", RPCArg::Type::ARR, RPCArg::Optional::NO, "The txids to filter", @@ -58,13 +59,26 @@ static RPCMethod gettxoutproof() }, }, {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "If specified, looks for txid in the block with this hash"}, + {"return_pruned", RPCArg::Type::BOOL, RPCArg::Default{false}, "Return an object with the proof or the candidate pruned block hashes"}, }, - RPCResult{ - RPCResult::Type::STR, "data", "A string that is a serialized, hex-encoded data for the proof." + RPCResults{ + {"return_pruned=false", RPCResult::Type::STR_HEX, "", "The serialized, hex-encoded proof"}, + {"return_pruned=true and the proof is available", RPCResult::Type::OBJ, "", "", + { + {RPCResult::Type::STR_HEX, "proof", "The serialized, hex-encoded proof"}, + }}, + {"return_pruned=true and candidate blocks were pruned", RPCResult::Type::OBJ, "", "", + { + {RPCResult::Type::ARR, "pruned_block_hashes", "Hashes of pruned blocks that may contain the transaction", + { + {RPCResult::Type::STR_HEX, "blockhash", "A candidate block hash"}, + }}, + }}, }, RPCExamples{""}, [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue { + const bool return_pruned{self.Arg<bool>("return_pruned")}; std::set<Txid> setTxids; UniValue txids = request.params[0].get_array(); if (txids.empty()) { @@ -82,8 +96,8 @@ static RPCMethod gettxoutproof() NodeContext& node = EnsureAnyNodeContext(request.context); ChainstateManager& chainman = EnsureChainman(node); if (!request.params[1].isNull()) { - LOCK(cs_main); hashBlock = ParseHashV(request.params[1], "blockhash"); + LOCK(cs_main); pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); @@ -111,6 +125,7 @@ static RPCMethod gettxoutproof() if (pblockindex == nullptr) { const TxLookupResult result{GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, node.txindex.get(), *setTxids.begin(), chainman.m_blockman)}; if (const auto* miss{result.GetMiss()}) { + if (return_pruned && !miss->pruned_block_hashes.empty()) return PrunedBlockHashesData(miss->pruned_block_hashes); throw miss->pruned_block_hashes.empty() ? JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block") : JSONRPCPrunedBlocksError(miss->pruned_block_hashes); @@ -127,6 +142,7 @@ static RPCMethod gettxoutproof() { LOCK(cs_main); if (chainman.m_blockman.IsBlockPruned(*pblockindex)) { + if (return_pruned) return PrunedBlockHashesData({pblockindex->GetBlockHash()}); throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()}); } CheckBlockDataAvailability(chainman.m_blockman, *pblockindex, /*check_for_undo=*/false); @@ -150,7 +166,10 @@ static RPCMethod gettxoutproof() CMerkleBlock mb(block, setTxids); ssMB << mb; std::string strHex = HexStr(ssMB); - return strHex; + if (!return_pruned) return strHex; + UniValue result{UniValue::VOBJ}; + result.pushKVEnd("proof", std::move(strHex)); + return result; }, }; } diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp index 746bc66d71..4a721abb7c 100644 --- a/src/rpc/util.cpp +++ b/src/rpc/util.cpp @@ -431,7 +431,7 @@ std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashe return strprintf("Transaction may be in one of the following pruned blocks: %s.", hashes); } -UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes) +UniValue PrunedBlockHashesData(const std::set<uint256>& pruned_block_hashes) { UniValue hashes{UniValue::VARR}; for (const auto& hash : pruned_block_hashes) { @@ -439,7 +439,12 @@ UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes) } UniValue data{UniValue::VOBJ}; data.pushKV("pruned_block_hashes", std::move(hashes)); - return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), data); + return data; +} + +UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes) +{ + return JSONRPCError(RPC_MISC_ERROR, PrunedBlocksErrorMessage(pruned_block_hashes), PrunedBlockHashesData(pruned_block_hashes)); } /** diff --git a/src/rpc/util.h b/src/rpc/util.h index 8cd9bbb33a..a4e8f0b3f5 100644 --- a/src/rpc/util.h +++ b/src/rpc/util.h @@ -149,6 +149,8 @@ UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& //! Error message when a transaction lookup only matched blocks whose data was pruned. std::string PrunedBlocksErrorMessage(const std::set<uint256>& pruned_block_hashes); +//! Object containing candidate pruned block hashes for a transaction lookup. +UniValue PrunedBlockHashesData(const std::set<uint256>& pruned_block_hashes); //! JSON-RPC error for a pruned-block transaction lookup miss. UniValue JSONRPCPrunedBlocksError(const std::set<uint256>& pruned_block_hashes); diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py index 6b8937d51b..61cf801c78 100755 --- a/test/functional/feature_txindex_prune.py +++ b/test/functional/feature_txindex_prune.py @@ -45,6 +45,8 @@ class TxIndexPruneTest(BitcoinTestFramework): tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000) blockhash = self.generate(pruned, 1)[0] txid = tx["txid"] + parent_txid = f'{tx["tx"].vin[0].prevout.hash:064x}' + parent_blockhash = pruned.getrawtransaction(parent_txid, 1)["blockhash"] self.log.info("Mine enough blocks to prune the transaction's block") self.generate(full, 600) @@ -53,6 +55,7 @@ class TxIndexPruneTest(BitcoinTestFramework): self.log.info("Pruned UTXO lookups work without txindex") self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"]) assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [txid]) + assert_equal(pruned.gettxoutproof([txid], return_pruned=True), {"pruned_block_hashes": [blockhash]}) self.restart_node(0) self.connect_nodes(0, 1) @@ -69,6 +72,9 @@ class TxIndexPruneTest(BitcoinTestFramework): except JSONRPCException as error: assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {blockhash}.", "data": {"pruned_block_hashes": [blockhash]}}) + assert_equal(pruned.gettxoutproof([parent_txid], return_pruned=True), {"pruned_block_hashes": [parent_blockhash]}) + assert_raises_rpc_error(-5, "Transaction not yet in block", pruned.gettxoutproof, ["00" * 32], return_pruned=True) + self.log.info("REST /tx returns the pruned block's hash") assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.") @@ -89,7 +95,9 @@ class TxIndexPruneTest(BitcoinTestFramework): assert "fee" not in tx_verbose assert "prevout" not in tx_verbose["vin"][0] assert_equal(self.rest_tx(pruned, txid), tx["hex"]) - assert_equal(pruned.verifytxoutproof(pruned.gettxoutproof([txid])), [txid]) + proof = pruned.gettxoutproof([txid]) + assert_equal(pruned.gettxoutproof([txid], return_pruned=True), {"proof": proof}) + assert_equal(pruned.verifytxoutproof(proof), [txid]) updated = pruned.utxoupdatepsbt(psbt) assert "non_witness_utxo" in pruned.decodepsbt(updated)["inputs"][0] ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 15:23:24 +00:00

yeah, restart_node() already waits for both indexes to reach the tip.

Drop the redundant index wait
diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py
index 6823784855..3a5604accb 100755
--- a/test/functional/feature_pruning.py
+++ b/test/functional/feature_pruning.py
@@ -473,8 +473,6 @@ class PruneTest(BitcoinTestFramework):
 
         self.log.info("Test prune with new indexes")
         self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1", "-txindex=1"])
-        node = self.nodes[0]
-        self.wait_until(lambda: node.getindexinfo()["basic block filter index"]["best_block_height"] >= 10, timeout=300)
 
         if self.is_wallet_compiled():
             self.log.info("Test wallet re-scan")
yeah, `restart_node()` already waits for both indexes to reach the tip. <details> <summary>Drop the redundant index wait</summary> ```diff diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py index 6823784855..3a5604accb 100755 --- a/test/functional/feature_pruning.py +++ b/test/functional/feature_pruning.py @@ -473,8 +473,6 @@ class PruneTest(BitcoinTestFramework): self.log.info("Test prune with new indexes") self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1", "-txindex=1"]) - node = self.nodes[0] - self.wait_until(lambda: node.getindexinfo()["basic block filter index"]["best_block_height"] >= 10, timeout=300) if self.is_wallet_compiled(): self.log.info("Test wallet re-scan") ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 15:34:26 +00:00

5944b6d test: cover txindex lookups of pruned blocks:

This node runs only txindex, so we can check the prune height here.

Check the txindex pruning limit
diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py
index 6b8937d51b..d6cbb1a5ee 100755
--- a/test/functional/feature_txindex_prune.py
+++ b/test/functional/feature_txindex_prune.py
@@ -48,7 +48,9 @@ class TxIndexPruneTest(BitcoinTestFramework):
 
         self.log.info("Mine enough blocks to prune the transaction's block")
         self.generate(full, 600)
-        pruned.pruneblockchain(pruned.getblockcount())
+        pruned.wait_for_index_sync()
+        with pruned.assert_debug_log(["txindex limited pruning to height 691"]):
+            pruned.pruneblockchain(pruned.getblockcount())
 
         self.log.info("Pruned UTXO lookups work without txindex")
         self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"])
> [5944b6d](https://github.com/bitcoin/bitcoin/pull/36002/changes/5944b6d14a84206e5f3a5f8de039bac6a0453f7e) _test: cover txindex lookups of pruned blocks_: This node runs only txindex, so we can check the prune height here. <details> <summary>Check the txindex pruning limit</summary> ```diff diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py index 6b8937d51b..d6cbb1a5ee 100755 --- a/test/functional/feature_txindex_prune.py +++ b/test/functional/feature_txindex_prune.py @@ -48,7 +48,9 @@ class TxIndexPruneTest(BitcoinTestFramework): self.log.info("Mine enough blocks to prune the transaction's block") self.generate(full, 600) - pruned.pruneblockchain(pruned.getblockcount()) + pruned.wait_for_index_sync() + with pruned.assert_debug_log(["txindex limited pruning to height 691"]): + pruned.pruneblockchain(pruned.getblockcount()) self.log.info("Pruned UTXO lookups work without txindex") self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"]) ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 17:26:48 +00:00

5944b6d test: cover txindex lookups of pruned blocks:

The loop catches exceptions to inspect the full RPC error. batch() already gives us that reply, so we could compare the errors directly. The same pruning message can be used while waiting for the fetch, so an unrelated RPC error fails the test right away. The UTXO case with txindex disabled can check the full reply, so there’s no need to repeat that lookup with txindex enabled.

Reuse the batch helper and pruning message
--- a/test/functional/feature_txindex_prune.py
+++ b/test/functional/feature_txindex_prune.py
@@ -10,9 +10,7 @@
 from test_framework.test_framework import BitcoinTestFramework
 from test_framework.util import (
     assert_equal,
-    assert_raises_rpc_error,
     try_rpc,
-    JSONRPCException,
 )
 from test_framework.wallet import MiniWallet, getnewdestination
 
@@ -45,32 +43,32 @@
         tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000)
         blockhash = self.generate(pruned, 1)[0]
         txid = tx["txid"]
+        pruned_message = f"Transaction may be in pruned block {blockhash}."
 
         self.log.info("Mine enough blocks to prune the transaction's block")
         self.generate(full, 600)
         pruned.pruneblockchain(pruned.getblockcount())
 
+        def assert_pruned_lookup(rpc, args):
+            reply = pruned.batch([rpc.get_request(*args)])[0]
+            assert_equal(reply.get("error"), {"code": -1, "message": pruned_message, "data": {"pruned_block_hashes": [blockhash]}})
+
         self.log.info("Pruned UTXO lookups work without txindex")
         self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"])
-        assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [txid])
+        assert_pruned_lookup(pruned.gettxoutproof, [[txid]])
         self.restart_node(0)
         self.connect_nodes(0, 1)
 
-        self.log.info("RPC lookups return pruned block hashes through txindex, UTXO, and explicit-block paths")
-        for rpc, rpc_args in (
-            (pruned.getrawtransaction, [txid]),
-            (pruned.getrawtransaction, [txid, 0, blockhash]),
-            (pruned.gettxoutproof, [[txid]]),
-            (pruned.gettxoutproof, [[txid], blockhash]),
+        self.log.info("RPC lookups return pruned block hashes through txindex and explicit block hashes")
+        for rpc, rpc_args in (
+            (pruned.getrawtransaction, [txid]),
+            (pruned.getrawtransaction, [txid, 0, blockhash]),
+            (pruned.gettxoutproof, [[txid], blockhash]),
         ):
-            try:
-                rpc(*rpc_args)
-                raise AssertionError("Expected pruned transaction lookup failure")
-            except JSONRPCException as error:
-                assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {blockhash}.", "data": {"pruned_block_hashes": [blockhash]}})
+            assert_pruned_lookup(rpc, rpc_args)
 
         self.log.info("REST /tx returns the pruned block's hash")
-        assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.")
+        assert_equal(self.rest_tx(pruned, txid, status=404), pruned_message)
 
         self.log.info("utxoupdatepsbt skips previous transactions in pruned blocks")
         psbt = pruned.createpsbt([{"txid": txid, "vout": tx["sent_vout"]}, {"txid": txid, "vout": 0}], [{getnewdestination()[2]: 0.0009}])
@@ -82,7 +80,7 @@
         self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups")
         pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"])
 
-        self.wait_until(lambda: not try_rpc(None, None, pruned.getrawtransaction, txid))
+        self.wait_until(lambda: not try_rpc(-1, pruned_message, pruned.getrawtransaction, txid))
         tx_verbose = pruned.getrawtransaction(txid, 2)
         assert_equal(tx_verbose["hex"], tx["hex"])
         # verbose fields are missing because there's no undo fetched from peer
> [5944b6d](https://github.com/bitcoin/bitcoin/pull/36002/changes/5944b6d14a84206e5f3a5f8de039bac6a0453f7e) _test: cover txindex lookups of pruned blocks_: The loop catches exceptions to inspect the full RPC error. `batch()` already gives us that reply, so we could compare the errors directly. The same pruning message can be used while waiting for the fetch, so an unrelated RPC error fails the test right away. The UTXO case with txindex disabled can check the full reply, so there’s no need to repeat that lookup with txindex enabled. <details> <summary>Reuse the batch helper and pruning message</summary> ```diff --- a/test/functional/feature_txindex_prune.py +++ b/test/functional/feature_txindex_prune.py @@ -10,9 +10,7 @@ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, - assert_raises_rpc_error, try_rpc, - JSONRPCException, ) from test_framework.wallet import MiniWallet, getnewdestination @@ -45,32 +43,32 @@ tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000) blockhash = self.generate(pruned, 1)[0] txid = tx["txid"] + pruned_message = f"Transaction may be in pruned block {blockhash}." self.log.info("Mine enough blocks to prune the transaction's block") self.generate(full, 600) pruned.pruneblockchain(pruned.getblockcount()) + def assert_pruned_lookup(rpc, args): + reply = pruned.batch([rpc.get_request(*args)])[0] + assert_equal(reply.get("error"), {"code": -1, "message": pruned_message, "data": {"pruned_block_hashes": [blockhash]}}) + self.log.info("Pruned UTXO lookups work without txindex") self.restart_node(0, extra_args=["-fastprune", "-prune=1", "-txindex=0"]) - assert_raises_rpc_error(-1, f"Transaction may be in pruned block {blockhash}.", pruned.gettxoutproof, [txid]) + assert_pruned_lookup(pruned.gettxoutproof, [[txid]]) self.restart_node(0) self.connect_nodes(0, 1) - self.log.info("RPC lookups return pruned block hashes through txindex, UTXO, and explicit-block paths") - for rpc, rpc_args in ( - (pruned.getrawtransaction, [txid]), - (pruned.getrawtransaction, [txid, 0, blockhash]), - (pruned.gettxoutproof, [[txid]]), - (pruned.gettxoutproof, [[txid], blockhash]), + self.log.info("RPC lookups return pruned block hashes through txindex and explicit block hashes") + for rpc, rpc_args in ( + (pruned.getrawtransaction, [txid]), + (pruned.getrawtransaction, [txid, 0, blockhash]), + (pruned.gettxoutproof, [[txid], blockhash]), ): - try: - rpc(*rpc_args) - raise AssertionError("Expected pruned transaction lookup failure") - except JSONRPCException as error: - assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {blockhash}.", "data": {"pruned_block_hashes": [blockhash]}}) + assert_pruned_lookup(rpc, rpc_args) self.log.info("REST /tx returns the pruned block's hash") - assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.") + assert_equal(self.rest_tx(pruned, txid, status=404), pruned_message) self.log.info("utxoupdatepsbt skips previous transactions in pruned blocks") psbt = pruned.createpsbt([{"txid": txid, "vout": tx["sent_vout"]}, {"txid": txid, "vout": 0}], [{getnewdestination()[2]: 0.0009}]) @@ -82,7 +80,7 @@ self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups") pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"]) - self.wait_until(lambda: not try_rpc(None, None, pruned.getrawtransaction, txid)) + self.wait_until(lambda: not try_rpc(-1, pruned_message, pruned.getrawtransaction, txid)) tx_verbose = pruned.getrawtransaction(txid, 2) assert_equal(tx_verbose["hex"], tx["hex"]) # verbose fields are missing because there's no undo fetched from peer ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 15:35:42 +00:00

5944b6d test: cover txindex lookups of pruned blocks:

This transaction still has unspent outputs, so gettxoutproof can use the UTXO set without asking txindex.
We could add its spent parent to the same loop to cover txindex too and check that the calls log no block read errors.

Check the proof error for a spent transaction
diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py
index 6b8937d51b..f2459bbbc0 100755
--- a/test/functional/feature_txindex_prune.py
+++ b/test/functional/feature_txindex_prune.py
@@ -45,6 +45,8 @@ class TxIndexPruneTest(BitcoinTestFramework):
         tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000)
         blockhash = self.generate(pruned, 1)[0]
         txid = tx["txid"]
+        parent_txid = f'{tx["tx"].vin[0].prevout.hash:064x}'
+        parent_blockhash = pruned.getrawtransaction(parent_txid, 1)["blockhash"]

         self.log.info("Mine enough blocks to prune the transaction's block")
         self.generate(full, 600)
@@ -57,17 +59,19 @@ class TxIndexPruneTest(BitcoinTestFramework):
         self.connect_nodes(0, 1)

         self.log.info("RPC lookups return pruned block hashes through txindex, UTXO, and explicit-block paths")
-        for rpc, rpc_args in (
-            (pruned.getrawtransaction, [txid]),
-            (pruned.getrawtransaction, [txid, 0, blockhash]),
-            (pruned.gettxoutproof, [[txid]]),
-            (pruned.gettxoutproof, [[txid], blockhash]),
+        for rpc, rpc_args, expected_blockhash in (
+            (pruned.getrawtransaction, [txid], blockhash),
+            (pruned.getrawtransaction, [txid, 0, blockhash], blockhash),
+            (pruned.gettxoutproof, [[txid]], blockhash),
+            (pruned.gettxoutproof, [[txid], blockhash], blockhash),
+            (pruned.gettxoutproof, [[parent_txid]], parent_blockhash),
         ):
-            try:
-                rpc(*rpc_args)
-                raise AssertionError("Expected pruned transaction lookup failure")
-            except JSONRPCException as error:
-                assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {blockhash}.", "data": {"pruned_block_hashes": [blockhash]}})
+            with pruned.assert_debug_log([], unexpected_msgs=["while reading raw block"]):
+                try:
+                    rpc(*rpc_args)
+                    raise AssertionError("Expected pruned transaction lookup failure")
+                except JSONRPCException as error:
+                    assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {expected_blockhash}.", "data": {"pruned_block_hashes": [expected_blockhash]}})

         self.log.info("REST /tx returns the pruned block's hash")
         assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.")
> [5944b6d](https://github.com/bitcoin/bitcoin/pull/36002/changes/5944b6d14a84206e5f3a5f8de039bac6a0453f7e) _test: cover txindex lookups of pruned blocks_: This transaction still has unspent outputs, so `gettxoutproof` can use the UTXO set without asking txindex. We could add its spent parent to the same loop to cover txindex too and check that the calls log no block read errors. <details> <summary>Check the proof error for a spent transaction</summary> ```diff diff --git a/test/functional/feature_txindex_prune.py b/test/functional/feature_txindex_prune.py index 6b8937d51b..f2459bbbc0 100755 --- a/test/functional/feature_txindex_prune.py +++ b/test/functional/feature_txindex_prune.py @@ -45,6 +45,8 @@ class TxIndexPruneTest(BitcoinTestFramework): tx = wallet.send_to(from_node=pruned, scriptPubKey=getnewdestination("legacy")[1], amount=100_000) blockhash = self.generate(pruned, 1)[0] txid = tx["txid"] + parent_txid = f'{tx["tx"].vin[0].prevout.hash:064x}' + parent_blockhash = pruned.getrawtransaction(parent_txid, 1)["blockhash"] self.log.info("Mine enough blocks to prune the transaction's block") self.generate(full, 600) @@ -57,17 +59,19 @@ class TxIndexPruneTest(BitcoinTestFramework): self.connect_nodes(0, 1) self.log.info("RPC lookups return pruned block hashes through txindex, UTXO, and explicit-block paths") - for rpc, rpc_args in ( - (pruned.getrawtransaction, [txid]), - (pruned.getrawtransaction, [txid, 0, blockhash]), - (pruned.gettxoutproof, [[txid]]), - (pruned.gettxoutproof, [[txid], blockhash]), + for rpc, rpc_args, expected_blockhash in ( + (pruned.getrawtransaction, [txid], blockhash), + (pruned.getrawtransaction, [txid, 0, blockhash], blockhash), + (pruned.gettxoutproof, [[txid]], blockhash), + (pruned.gettxoutproof, [[txid], blockhash], blockhash), + (pruned.gettxoutproof, [[parent_txid]], parent_blockhash), ): - try: - rpc(*rpc_args) - raise AssertionError("Expected pruned transaction lookup failure") - except JSONRPCException as error: - assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {blockhash}.", "data": {"pruned_block_hashes": [blockhash]}}) + with pruned.assert_debug_log([], unexpected_msgs=["while reading raw block"]): + try: + rpc(*rpc_args) + raise AssertionError("Expected pruned transaction lookup failure") + except JSONRPCException as error: + assert_equal(error.error, {"code": -1, "message": f"Transaction may be in pruned block {expected_blockhash}.", "data": {"pruned_block_hashes": [expected_blockhash]}}) self.log.info("REST /tx returns the pruned block's hash") assert_equal(self.rest_tx(pruned, txid, status=404), f"Transaction may be in pruned block {blockhash}.") ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 15:36:26 +00:00

This would still pass if witness_utxo contained the wrong output.
For the legacy input, we need the full previous transaction, which is unavailable until we fetch the block.

Check the amount and script
--- a/test/functional/feature_txindex_prune.py
+++ b/test/functional/feature_txindex_prune.py
@@ -7,6 +7,7 @@
 from http.client import HTTPConnection
 from urllib.parse import urlparse
 
+from test_framework.messages import COIN
 from test_framework.test_framework import BitcoinTestFramework
 from test_framework.util import (
     assert_equal,
@@ -77,7 +78,11 @@
         updated = pruned.utxoupdatepsbt(psbt)
         legacy_input, segwit_input = pruned.decodepsbt(updated)["inputs"]
         assert "non_witness_utxo" not in legacy_input
-        assert "witness_utxo" in segwit_input
+        assert "witness_utxo" not in legacy_input
+        change = tx["tx"].vout[0]
+        witness_utxo = segwit_input["witness_utxo"]
+        assert_equal(witness_utxo["amount"] * COIN, change.nValue)
+        assert_equal(witness_utxo["scriptPubKey"]["hex"], change.scriptPubKey.hex())
 
         self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups")
         pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"])
This would still pass if `witness_utxo` contained the wrong output. For the legacy input, we need the full previous transaction, which is unavailable until we fetch the block. <details> <summary>Check the amount and script</summary> ```diff --- a/test/functional/feature_txindex_prune.py +++ b/test/functional/feature_txindex_prune.py @@ -7,6 +7,7 @@ from http.client import HTTPConnection from urllib.parse import urlparse +from test_framework.messages import COIN from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, @@ -77,7 +78,11 @@ updated = pruned.utxoupdatepsbt(psbt) legacy_input, segwit_input = pruned.decodepsbt(updated)["inputs"] assert "non_witness_utxo" not in legacy_input - assert "witness_utxo" in segwit_input + assert "witness_utxo" not in legacy_input + change = tx["tx"].vout[0] + witness_utxo = segwit_input["witness_utxo"] + assert_equal(witness_utxo["amount"] * COIN, change.nValue) + assert_equal(witness_utxo["scriptPubKey"]["hex"], change.scriptPubKey.hex()) self.log.info("Fetch the pruned block and retry RPC, REST, and PSBT lookups") pruned.getblockfrompeer(blockhash, pruned.getpeerinfo()[0]["id"]) ``` </details>
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!36002
No description provided.