mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:44:38 +00:00
txindex: allow running in pruned mode #36002
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36002
Loading…
Reference in a new issue
No description provided.
Delete branch "txindex-prune"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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
getblockfrompeerusing 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
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
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.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/32082864144/job/95549090994LLM 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.
Big concept ACK \:D/
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=1option I could set, so that myprune=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
FatalErrorfinBaseIndex::ProcessBlockand shut the node down?It's the same behavior if you try and start
coinstatsindexorblockfilterindexafter 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 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.
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 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.
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.
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?
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased due to
includeconflicts with #36116.🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/34426977165/job/102714188149LLM 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.
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.
BaseIndexnow has two prune-related flags,AllowPrune()andAllowPartialHistory(), and they aren't really independent. Partial history is only ever set up on a pruned node, so (as I understand it) an index withAllowPartialHistory()but notAllowPrune()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 anAllowPruneenum with valuesDisallowed,FullHistoryandPartialHistory.Another option would be to move
AllowPartialHistory()toTxIndexinstead. 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
getblockfrompeerand 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 ongetrawtransactionthat requests the block for us in the same rpc call?Thanks @arejula27. Those are good suggestions.
I renamed
AllowPrunetoGetPrunePolicywhich returns an enum.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
datafield 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/textstring error responses. Of course that can be done as a follow-up if there is interest.Thx! Will try the exercise!
I am finishing the (deeper) code review, hope to post it soon :D
Thanks for applying the changes I asked for in the first review. I've done a deeper pass now, built it and ran
txindex_testsandfeature_txindex_prune.py, and have a few more notes.gettxoutproofonly 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 thoughpblockindexis 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_heightdown until it reaches genesis.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
txtogether withpruned_block_hashes, or ablock_hashwithout atx. My proposal is to usestd::variant<TxFound, TxMiss>rather than one struct where the outcome is implied by which fields are set.For example,
wallet::TxStateinsrc/wallet/transaction.hmodels a transaction's state the same way, as a variant of structs.I suggest something like:
nit:
resulthas notxand noblock_hashin this branch, so this builds the same object again. Is there a reason not toreturn result;directly?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"?
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 leavestxindex_testsandfeature_txindex_prune.pypassing). 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_hashesa 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 waytxindex_collision_scan_pathdoes, 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 personally prefer use
util::expected, but i think the project approach is to use it only over real errors (likeBlockReadFailedkind of errors)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.
I am not sure if this is enough to communicate what is happening to the user. Starting with
-prune=XXX -txindex=1may 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.synced: truedoesn't really mean the same thing as before. So some clients which are not checking the newfirst_block_heightmay not get what they think they are getting.Because of what we do with
f_txindex_readyabove I am not sure all the infos inTxIndexMissErrorDetailswould ever be relevant or possible to hit, e.g. at least thesyncedcheck and added message.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
getrawtransactionandgettxoutproofrecovery 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
-prunewith-txindexstill 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 reportspermalink
Done.
Added these cases.
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.
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.
Thanks, but this is 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.
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:
Looked through (
5047435466), LGTM, left some minor comments.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"
Nit:
nullhere is actually{}oruint256::ZERO.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
TxMissis used only in case the TX was not found.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.I just wonder in what cases can a TX hash be present in the active chain more than once? Only duplicate coinbase (BIP30)?
Nit: For clarity it would be better to separate 3 cases: found, found in pruned block, and not found at all in the index.
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?
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.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.
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.
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
TxMisswith an emptypruned_block_hashesvector.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.
We intend the caller to check for
uint256::IsNull(), which is technicallyuint256::ZERO. But, I think it's clearer to specifynullhere for that reason.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:
(min. 1 TXID prefix matches)
(and it matches)
Miss is returned.
Miss is returned.
TX and its block hash is returned.
Miss is returned.
Miss with a list of potential block hashes is returned (may be empty, e.g. only false positives).
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.
Refined: "or is in a block that has been pruned (or has not been indexed yet)."
Fine as is, thanks.
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'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
electrstakes 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.
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_chaincheck filters stale blocks.Clear, thanks.
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.
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
ifwill 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.
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.
Taken, thanks.
Thanks @optout21 for your review. I took a few of your suggestions.
This string is not added to
bitcoinstrings.cpp, while the next one is. May be missing.Reviewed
be19bbac4e, left some comments.Some general comments:
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.
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.This
ifmay trigger even in cases whentxindexis 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.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.pyandfeature_pruning.py, and they pass (exceptfeature_pruning.pyin 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 withpruneheight148133, and everything behaved as expected.testnet4 commands and output
Node:
bitcoind -testnet4 -prune=550 -txindex -rest, network disabledI also noticed that
ProcessPSBTnow goes throughGetTransaction, so it looks in the mempool before the txindex (this is a behavioral change). I measuredutxoupdatepsbtanddescriptorprocesspsbtagainst 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.
With an explicit blockhash whose block is pruned,
gettxoutproofnow returnsTransaction may be in pruned block <hash>., whilegetrawtransactionstill returnsBlock not available. Is there a reason to treat these two cases differently?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. withpruneblockchain), or move the case tofeature_txindex_prune.py, which already prunes?🐙 This pull request conflicts with the target branch and needs rebase.
I removed them from bitcoinstrings.cpp. I believe that will be generated later.
Updated documentation to reflect this.
I changed the
TxMiss::pruned_block_hashesfrom astd::vectorto astd::setto reflect this.Yes, this fixes a bug without
txindexas well. Previously, callinggetrawtransactionwith verbosity 2 and no undo data would result in an RPC errorUndo data expected but can't be read. Now It will return the tx but withoutfeeandprevout(these are listed as optional in the help text).Fixed this by using
self.nodes[2]instead ofself.nodes[0]. That node does always has pruned blocks.Fixed this so both cases return the same error.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/37862719885/job/113602028381LLM reason (✨ experimental): CI failed because IWYU added a missing
#include <set>insrc/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.
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.
pruned_block_hashesfromstd::vectortostd::setto ensure returned block hashes are unique.getrawtransactionandgettxoutproofwhen a tx inside a pruned block is requested with eithertxindexor a provided block hash.getrawtransactionandgettxoutproof.I opted not to add structured errors for REST (https://github.com/bitcoin/bitcoin/pull/36002#issuecomment-5724803370):
I'm not sure this is necessary, since the error text will show the block hashes anyway. I left this alone.
Yes, I think this is ok. It aligns lookups with the other RPCs and REST endpoint.
git range-diff 619185d5ce..be19bbac4e acdb326934..23f14ab325re-concept ACK, overall LGTM, left a few remaining suggestions, it's looks pretty good already.
This should probably be v32.
Name the first release without legacy entries
Given that
GetTransactionalso uses the result for mempool lookups we could move this one tonode/.Keep the shared lookup result under node
I find
result.GetFound()andresult.GetMiss()easier to read than repeatingstd::get_ifat each call site. Deriving from the variant, likeGenTxiddoes, keeps the found/miss distinction and the existingstd::getcalls.Give the lookup result named accessors
Nit: a slightly simpler version:
Use the complement notation
This can be a bit shorter if we construct the transaction from the file and check its hash inside the
tryblock. That also keepstxlocal, and makes thecontinueunnecessary.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
This can be a bit shorter if we construct the transaction from the file and check its hash inside the
tryblock. That also keepstxlocal and makes thecontinueunnecessary.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
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
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
gettxoutprooffollows the same pruned check withCheckBlockDataAvailability, which we could reuse here. A block that was never downloaded would then reportBlock not available (not fully downloaded), asgettxoutproofandgetblockdo, 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)
nit: these three lines could be a structured binding, here and in
rest_tx:Use structured bindings for the found transaction
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:
getrawtransactionwithout 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.error.dataargument toJSONRPCErroron its own.GetTransaction, RPC and REST together.ProcessPSBTtoGetTransactionseparately, since that also changes the lookup order to mempool first.Returning the whole error here would save repeating the same code, message and data at all four call sites.
JSONRPCTransactionErroralready does something similar.Build the pruned-block error in one place
nit: given that
foundis 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
What should happen when the active-chain copy is pruned but a stale copy is still readable? We return the stale block, so
getrawtransactionshows zero confirmations andverifytxoutproofrejects the proof fromgettxoutproof.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
PruneBlockhelper from my other comment):Cover the readable stale-block fallback
nit: we already have
sync_txindexfor these three waits. This also gives us its sync logging.Reuse the index-sync helper
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_rpcfor the download wait and check the hex from the verbose response.Exercise no-txindex lookups and recovery across restart
Thanks @l0rinc for your detailed review. I took all your suggestions.
crACK
4ab48b8276Building 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.
🐙 This pull request conflicts with the target branch and needs rebase.
Thanks for the review @optout21!
Rebased due to https://github.com/bitcoin/bitcoin/pull/36618.
reACK
322cbbf4d0Reviewed rebase changes (
git range-diff 4ab48b827691ade8ceaa78b5125e9bb610d37aa6...322cbbf4d0c6c4c0abf920ac53814c1507c7e4b6).🐙 This pull request conflicts with the target branch and needs rebase.
Thanks again @optout21.
Rebased due to https://github.com/bitcoin/bitcoin/pull/35728.
git range-diff e310efb202..322cbbf4d0 fb19fed3df..8aa03c78deI 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.
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
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
I'd reuse the
getblockfrompeertest for txindex, too - to check that we can resume after fetching missing block bodies without undo data.Resume txindex after restoring missing block bodies
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
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
Seems to me we could easily extend the existing block-without-undo test to cover the no-txindex case.
Characterize missing undo without txindex
Now that #36091 was merged, let's use the failure friendly comparisons instead.
Print values for the new txindex comparisons
The test sets up a reorg and resubmits a stale block containing only the first txid
gettxoutprooflooks 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
gettxoutproofreport the pruned candidate on this mismatch?FindTxalready collects it.Cover recovery of a multi-transaction proof
Could we spend the SegWit change too? Its coin is still in the UTXO set, so
utxoupdatepsbtshould fill inwitness_utxoeven after the block is pruned.Extend the existing PSBT with its SegWit change output
Added a test covering no
fee/prevoutreturned instead of an error if we callgetrawtransactionverbosity 2 with a block hash of a block with no undo file.Updated the new-index test to also use
txindex.Done.
Done.
Done, reused node0 for this.
Done.
Done.
Fixed this in
FindTxby 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.Done.
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🐙 This pull request conflicts with the target branch and needs rebase.
Rebased due to #35474. Also rebased on top of #36890 to fix the CI failures.
git range-diff fb19fed3df..c612ccc378 08ca210a92..46bfd40244Code review ACK
c3de4d7dc7I 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.
nit: Could mention why this is the case, may not be obvious to newer devs
nit: Using an optional here would have been more explicit but feel free to ignore
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: 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 ;)
No need to change
::cs_main, we prefer that versionnit: 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:
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: 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.
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.
Could unset both data and undo (
~BLOCK_HAVE_MASK) here? Just seems more correct behavior.nit: Also why use
Assertinstead ofBOOST_REQUIREhere?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.
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 ofutil::Expectedonly for errors, not for normal results (1). #35646 was built on that idea (2, 3). Following that, I would say that aTxMissis 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.Done. We now fail if we're already pruned, and show a message to the user to run with
-reindex.I kept the shared error message with the hashes in the wording. For
bitcoin-cliand REST the structured data is not displayed, so we need the hashes in the message for these cases.It does not fail anymore because of the missing undo data. This is handled in the first commit :).
Taken, thanks.
Done.
Done.
Kept the existing null convention here. That's used generally throughout the codebase for
uint256types.I kept this as a variant. I agree with @arejula27 that
TxMissis a normal result and not an error, so this is the more appropriate type here.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..a215a43f03ACK
a215a43f03reACK
a215a43f03Reviewed 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)Nit: A default-constructed
TxLookupResultstruct will beTxFound, which is not explicit and not entirely intuitive. A constructor would make this more explicit.Nit:
node0will start a resource-intensive full txindex build here, in an already very heavy test. Is this really needed? Is its result checked?Will do if I push again.
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.
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.datain 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.
With both indexes on node 0, txindex can mask a missing filter-index prune lock. Running
blockfilterindexon 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
I had to read both commits to tell which
GetTransactionchanges affect lookup behavior.I’d switch
FindTx,FindLegacyTx, andGetTransactiontoTxLookupResulttogether, 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
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.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
I was a bit confused here at first, I expected
Expected<T, E>(pun intended), but the positions don’t mean value and error - andstd::variantactually default-constructs its first alternative, so puttingTxMissfirst gives us an empty miss instead of aTxFoundwith a null transaction. Reordering also changes the numeric indices, but existing callers select by type, so they don’t need adjusting.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
This introduces dead code now. By moving
JSONRPCPrunedBlocksErrorand thegettxoutproofcheck 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
pushKVEndfor all three keys here and useJointo transform it directly.Use the new argument in gettxoutproof
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
prooforpruned_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
yeah,
restart_node()already waits for both indexes to reach the tip.Drop the redundant index wait
This node runs only txindex, so we can check the prune height here.
Check the txindex pruning limit
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
This transaction still has unspent outputs, so
gettxoutproofcan 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
This would still pass if
witness_utxocontained 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