Repository navigation
txindex: allow running in pruned mode - #36002
andrewtoth wants to merge 7 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
10fd02e to
6abdd0c
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
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 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 |
It's the same behavior if you try and start
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
left a comment
There was a problem hiding this 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 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. |
6abdd0c to
1f1dcd6
Compare
|
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 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 Wdyt? |
1f1dcd6 to
ee176d3
Compare
|
Rebased due to |
ee176d3 to
c92f0aa
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
There was a problem hiding this 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?
322cbbf to
8aa03c7
Compare
l0rinc
left a comment
There was a problem hiding this 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.
8aa03c7 to
c612ccc
Compare
|
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.
|
c612ccc to
c3de4d7
Compare
| self.stop_node(2) | ||
| self.nodes[2].assert_start_raises_init_error( | ||
| expected_msg='Error: txindex best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)' | ||
| f'{os.linesep}Error: A fatal internal error occurred, see debug.log for details: Failed to start indexes, shutting down…', |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Done. We now fail if we're already pruned, and show a message to the user to run with -reindex.
| { | ||
| const std::string hashes{Join(pruned_block_hashes, ", ", [](const uint256& hash) { return hash.GetHex(); })}; | ||
| if (pruned_block_hashes.size() == 1) { | ||
| return strprintf("Transaction may be in pruned block %s.", hashes); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| "If pruning is enabled, this call may return error -1 indicating that the 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 the transaction.\n" | ||
| "Use getblockfrompeer to fetch the blocks, then retry the lookup.\n\n" |
There was a problem hiding this comment.
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 ;)
There was a problem hiding this comment.
It does not fail anymore because of the missing undo data. This is handled in the first commit :).
| CBlock block; | ||
|
|
||
| if (tx->IsCoinBase() || !blockindex || WITH_LOCK(::cs_main, return !(blockindex->nStatus & BLOCK_HAVE_MASK))) { | ||
| if (tx->IsCoinBase() || !blockindex || WITH_LOCK(::cs_main, return !(blockindex->nStatus & BLOCK_HAVE_UNDO))) { |
There was a problem hiding this comment.
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 !(blockindex->nStatus & BLOCK_HAVE_UNDO))) { | |
| 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.
| // Destructor is declared because this class contains a unique_ptr to an incomplete type. | ||
| virtual ~TxIndex() override; | ||
|
|
||
| /// Pruning is allowed unless the database still contains legacy entries. |
There was a problem hiding this comment.
nit: Could mention why this is the case, may not be obvious to newer devs
| { | ||
| LOCK(cs_main); | ||
| chainman.m_blockman.m_have_pruned = true; | ||
| Assert(chainman.m_blockman.LookupBlockIndex(block_hash))->nStatus &= ~BLOCK_HAVE_DATA; |
There was a problem hiding this comment.
Could unset both data and undo (~BLOCK_HAVE_MASK) here? Just seems more correct behavior.
There was a problem hiding this comment.
nit: Also why use Assert instead of BOOST_REQUIRE here?
| CTransactionRef tx; | ||
| /// Hash of the block containing the transaction. null if the transaction | ||
| /// was found in the mempool. | ||
| uint256 block_hash; |
There was a problem hiding this comment.
nit: Using an optional here would have been more explicit but feel free to ignore
There was a problem hiding this comment.
Kept the existing null convention here. That's used generally throughout the codebase for uint256 types.
| }; | ||
|
|
||
| /// Result of a transaction lookup that may be answered by the txindex. | ||
| struct TxLookupResult : public std::variant<TxFound, TxMiss> |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Check for BLOCK_HAVE_UNDO before reading undo data for verbosity 2. Return the transaction without fee and prevout when undo data is unavailable, matching the documented behavior.
Accept an optional data value and include it in the error object when non-null. Preserve the existing response shape when no data is supplied.
FindTx now returns a TxLookupResult so callers can distinguish a missing transaction from one that may only be in pruned blocks.
Propagate lookup results through GetTransaction to RPC and REST callers. Include candidate pruned block hashes in error messages and JSON-RPC error.data, including the known block when gettxoutproof uses the UTXO set. Callers can fetch missing blocks with getblockfrompeer and retry. Adapt PSBT lookups to the new transaction lookup result type.
Extend the prune+txindex functional test to check that getrawtransaction, gettxoutproof, and REST /tx return the pruned block hash, and that utxoupdatepsbt skips those previous transactions until the block is fetched.
c3de4d7 to
a215a43
Compare
|
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
|
|
ACK a215a43 |
| }; | ||
|
|
||
| /// Result of a transaction lookup that may be answered by the txindex. | ||
| struct TxLookupResult : public std::variant<TxFound, TxMiss> |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Will do if I push again.
There was a problem hiding this comment.
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.
| self.log.info("Test prune with a new index") | ||
| self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1"]) | ||
| self.log.info("Test prune with new indexes") | ||
| self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1", "-txindex=1"]) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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")
l0rinc
left a comment
There was a problem hiding this 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.
| }; | ||
|
|
||
| /// Result of a transaction lookup that may be answered by the txindex. | ||
| struct TxLookupResult : public std::variant<TxFound, TxMiss> |
There was a problem hiding this comment.
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.
| } | ||
|
|
||
| std::optional<TxIndexResult> TxIndex::FindTx(const Txid& tx_hash) const | ||
| TxLookupResult TxIndex::FindTx(const Txid& tx_hash) const |
There was a problem hiding this comment.
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);
}
| self.log.info("Test prune with a new index") | ||
| self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1"]) | ||
| self.log.info("Test prune with new indexes") | ||
| self.restart_node(0, extra_args=["-prune=550", "-blockfilterindex=1", "-txindex=1"]) |
There was a problem hiding this comment.
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")| { | ||
| LOCK(cs_main); | ||
| if (chainman.m_blockman.IsBlockPruned(*pblockindex)) { | ||
| throw JSONRPCPrunedBlocksError({pblockindex->GetBlockHash()}); |
There was a problem hiding this comment.
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]
|
|
||
| if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { | ||
| node.txindex = MakeIndex<TxIndex>(interfaces::MakeChain(node), index_cache_sizes.tx_index, /*f_memory=*/false, do_reindex); | ||
| if (chainman.m_blockman.IsPruneMode() && !node.txindex->AllowPrune()) { |
There was a problem hiding this comment.
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.
| // 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; |
There was a problem hiding this comment.
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
}| 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 ( |
There was a problem hiding this comment.
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
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 #10609, #12651, #16182, #35240