Skip to content

rpc: Manual prune lock management (Take 2) - #34534

Open
fjahr wants to merge 6 commits into
bitcoin:masterfrom
fjahr:2026-02-prunelocks-rpc-v2
Open

fjahr wants to merge 6 commits into
bitcoin:masterfrom
fjahr:2026-02-prunelocks-rpc-v2

Conversation

@fjahr

@fjahr fjahr commented Feb 8, 2026 •

Copy link
Copy Markdown
Contributor

This is a refreshed version of #19463, which was closed due to inactivity.

Motivation: On pruned nodes, if a wallet is not loaded while the node is running, blocks necessary for rescanning when the wallet is loaded may be pruned. This PR allows users and external wallet software to manually manage prune locks via RPC, so they can protect blocks needed for future rescans and also clean up locks that are no longer relevant (e.g. after permanently unloading a wallet from a node). This is useful both for Bitcoin Core's own wallet and for external wallets that use Bitcoin Core as a backend. Usage of temporary prune locking may also be helpful in other functional test scenarios but I didn't spend time to check where might apply.

This PR leverages the existing prune locks system we already have. The interface of the RPCs of the old PR has been slightly updated, it now matches the pattern used by setban/listbanned exactly. The locks are prefixed to distinguish them from the systems locks and prevent naming colissions. They are not persisted across restarts.

@DrahtBot

DrahtBot commented Feb 8, 2026 •

Copy link
Copy Markdown
Contributor

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 optout21, andrewtoth
Concept ACK stickies-v
Stale ACK sedited, GEREMIAA

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:

  • #36904 (log: Remove trailing and embedded newlines from log messages by maflcko)
  • #36858 (refactor: break the blockstorage/validation circular dependency by pzafonte)
  • #36856 (kernel: add manual pruning by pzafonte)
  • #36778 (AssumeUTXO: replace loadtxoutset RPC with a startup arg by l0rinc)
  • #36738 (refactor: move block writes and pruning into BlockManager by pzafonte)
  • #36266 (rpc: Let dumptxoutset fail early on stale targets and concurrent runs by fjahr)

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.

@fjahr fjahr mentioned this pull request Feb 8, 2026
@sedited

sedited commented Feb 8, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@DrahtBot

DrahtBot commented Feb 8, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task Windows native, fuzz, VS 2022: https://github.com/bitcoin/bitcoin/actions/runs/21799390662/job/62892243983
LLM reason (✨ experimental): Fuzz test failed because the RPC command "listprunelocks" is not registered as safe or unsafe for fuzzing in rpc.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.

@fjahr
fjahr force-pushed the 2026-02-prunelocks-rpc-v2 branch from df7a8c4 to f192b06 Compare February 8, 2026 15:28
@fjahr

fjahr commented Feb 8, 2026

Copy link
Copy Markdown
Contributor Author

Fixing CI failure: Forgot to set RPC_COMMANDS_[NOT_]SAFE_FOR_FUZZING for the new RPCs.

@luke-jr luke-jr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incomplete review. Basically, the original PR interface was way better.

Comment thread src/rpc/blockchain.cpp Outdated
"These locks are used internally by indexes and can also be set manually via the setprunelock RPC.\n",
{},
RPCResult{
RPCResult::Type::ARR, "", "",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was an Object for future extensibility. No reason to lose that.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The RPC is called listprunelocks, I don't see how it could be extended to return anything else aside from a list of locks without that other thing feeling out of place. Can you give some specific ideas that you have? At least I would want to give the RPC a different name then (getpruneinfo or so) but potentially these ideas should rather be in a separate RPC. I prefer consistency and so I really like that we could be consistenty with the banning RPC.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

listprunelocks could return a "blockman epoch" in the future, if there was need to further distinguish rpc results. (Yes, this is made up, but with an array, this is impossible, with an object, this is trivial and harmless)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is a "blockman epoch"? I don't think I have heard of that before.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess TIL per this comment that the JSON object thing is in the dev notes, fair enough, I have changed it to return an object.

Comment thread src/rpc/blockchain.cpp Resolved
Comment thread src/rpc/blockchain.cpp Resolved
@fjahr
fjahr force-pushed the 2026-02-prunelocks-rpc-v2 branch from f192b06 to 0032cee Compare February 18, 2026 13:54
@fjahr

fjahr commented Feb 18, 2026

Copy link
Copy Markdown
Contributor Author

@luke-jr

Basically, the original PR interface was way better.

Is this just about #34534 (comment) or did you mean something else?

@fjahr

fjahr commented Feb 18, 2026

Copy link
Copy Markdown
Contributor Author

Addressed feedback from @luke-jr and @bvbfan , thanks for the review!

@sedited

sedited commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

I can not recall who was mentioned as a potential user but I would appreciate if someone could ping them to take a look if this is still relevant to them.

Do you remember at least who mentioned these users/use cases?

@sedited
sedited requested a review from stickies-v March 19, 2026 17:13
@stickies-v

Copy link
Copy Markdown
Contributor

Unfortunately, I can not recall who was mentioned as a potential user but I would appreciate if someone could ping them to take a look if this is still relevant to them.

This looks potentially interesting, but I don't think we should be implementing RPCs when we don't know anyone that would actually be using them? Since the previous PR has been open since 2020 already without users chiming in, it seems like there's no real demand for this?

@achow101

Copy link
Copy Markdown
Member

This is generally useful in the wallet and for any wallets that leverage Bitcoin Core. The fundamental issue is that if the wallet is not loaded while the node is running, blocks necessary for rescanning when the wallet is loaded may be pruned away. The wallet definitely should be using prune locks, but it's also necessary to have a way to for users to remove prune locks that are no longer relevant, e.g. if they unload a wallet that they don't plan to load on that node again. External wallets that use Bitcoin Core should also find this useful as they can then set prune locks that match the scan state of the external wallet.

@stickies-v

Copy link
Copy Markdown
Contributor

Thanks for the explanation @achow101 . Concept ACK. Enabling wallets to build on top of a pruned node via RPC seems enough of a use case to move this forward. @fjahr I think this might be useful to include in PR description to give it more motivation?

@fjahr

fjahr commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the explanation @achow101 . Concept ACK. Enabling wallets to build on top of a pruned node via RPC seems enough of a use case to move this forward. @fjahr I think this might be useful to include in PR description to give it more motivation?

Done, replace that vague part of the description with a better motivation paragraph.

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing that is still not clear to me is how this is actually useful to external applications if the locks are not persisted. I could see how this might be interesting for our own wallets, by setting prune locks for wallets even though they are not loaded yet. But for outside users this seems like a limitation that is difficult to deal with. If you want to add a wallet on startup, wouldn't that require racing to set a lock again if you restart? What is the exact scenario here?

Comment thread src/rpc/blockchain.cpp Outdated
ChainstateManager& chainman = EnsureAnyChainman(request.context);
UniValue locks_arr(UniValue::VARR);
{
const auto prune_locks = WITH_LOCK(::cs_main, return chainman.m_blockman.GetPruneLocks());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we either have to hold this lock while iterating through the prune locks, or copy them? I think my preference would be to just take a copy here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, it certainly seems like I addressed this comment without thinking about it enough because the surrounding parentesis were unnecessary as well. I am now using a explicit unordered_map constructor now to ensure the copy happens before the lock scope ends and I have added a comment and removed the parenthesis.

Comment thread src/node/blockstorage.h Outdated
bool DeletePruneLock(const std::string& name) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);

//! Return the current set of prune locks.
const std::unordered_map<std::string, PruneLockInfo>& GetPruneLocks() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return m_prune_locks; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason for introducing this helper? Existing validation code that iterates through the locks directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m_prune_locks is private and the direct access to it in validation.cpp is only possible because ChainState is a friend class of BlockManager. Of course we could also just make it public but a getter method seemed nicer to me.

@fjahr
fjahr force-pushed the 2026-02-prunelocks-rpc-v2 branch from b7fc779 to c7ac2d8 Compare March 22, 2026 13:40
@fjahr

fjahr commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed latest @sedited feedback, thank you!

One thing that is still not clear to me is how this is actually useful to external applications if the locks are not persisted. I could see how this might be interesting for our own wallets, by setting prune locks for wallets even though they are not loaded yet. But for outside users this seems like a limitation that is difficult to deal with. If you want to add a wallet on startup, wouldn't that require racing to set a lock again if you restart? What is the exact scenario here?

First, I think we can agree that it's useful for long-running nodes and the internal wallet, right? So for the following I am still unsure if it should be included here or part of follow-up PR.

For a node that is relaunched only every few weeks for usage of (cold-ish) wallet the persisted lock sounds useful. But I am not sure if just making the locks persistent is actually the best UI for this use-case. The pattern would probably be that the user, before shutdown, sets a prune lock to the last scan height (potentially the tip) and then shuts down. Then on restart the prune lock is respected. But then maybe it would actually be more convenient if there was a startup option -prunelocked or so where the node can be started with the current tip locked. It could get a height parameter too if an earlier height should be locked. I haven't spent much time thinking if this covers all the use-cases but so far I tend to think the startup option covers what I have in mind and comes with a few upsides: If the node crashes and the user couldn't set the lock before, with persistence they might be still screwed but with the startup option they are safe. And since we could avoid persistence this should be much easier to implement and have less code to maintain.

EDIT: Also, for certain wallets that really need a lot of control, there is always the option to manually prune as well.

@sedited

sedited commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

First, I think we can agree that it's useful for long-running nodes and the internal wallet, right? So for the following I am still unsure if it should be included here or part of follow-up PR.

The case is still not quite clear to me to be honest. Would the wallet start tracking prune locks for unloaded wallets? Afaict it doesn't currently hold a lock during rescan - that does indeed seem like something useful. I can also see how deleting / cleaning up existing locks could be useful, though it also feels like bit of a footgun. I'm having a hard time thinking of a scenario where you can robustly race a node pruning and important an existing wallet / descriptor. The startup option does seem better to me too.

@fjahr

fjahr commented Mar 25, 2026

Copy link
Copy Markdown
Contributor Author

The startup option does seem better to me too.

Thanks, I have added a minimal implementation of the startup option because so far seems like a clearly useful feature to me if outside wallets want to use prune locks in any capacity. But conceptual feedback still very welcome!

Would the wallet start tracking prune locks for unloaded wallets?

I think so? I could see something like this become more common in the future when more users switch on pruning to avoid having to get a larger disk. I would expect there are wallet options that market themselves being compatible with (possibly aggressive) pruning on the node and that this option will become more common in the future. But of course it would be a stronger statement to hear from an implementer directly that they would use such a feature. I just looked at the sparrow docs as a start and they are rather "hands-off" so far and just warn about potential issues: https://sparrowwallet.com/docs/connect-node.html#pruned-nodes

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/45074726945/job/137369313684
LLM reason (✨ experimental): CI failed during linking because libbitcoinkernel.so has an undefined SanitizeString(std::string_view, int) symbol.

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.

@GEREMIAA

Copy link
Copy Markdown

tACK d025cf1

Tested on Ubuntu 22.04.5 (x86_64, GCC 11.4), signet node with pruning, wallet loaded.

  • rpc_prunelock.py passes, and the unit tests pass (378/378).
  • With a lock at 330000, pruneblockchain 331500 did not advance pruneheight (329114) and block 330000 stayed available. After setprunelock <id> remove, the same call pruned to 330933 and getblock 330000 returned "Block not available (pruned data)". Note that the lock applies per blk file, so blocks a bit below the lock height can also be kept. That looks expected.
  • listprunelocks shows the user: prefix. Manual locks are gone after a restart, as documented.
  • -prunelock=a:331500 -prunelock=a:331200 -prunelock=b gives a at 331200 (the lowest height) and b at 0.
  • Error cases give clear messages: invalid id, unknown id on remove, unknown command, negative height, -prunelock without -prune, and an invalid -prunelock value.

Two small points on the setprunelock help:

  1. The height argument says default=0 and also "(only required for "add")". add without a height is accepted and sets the lock at 0, so the height is not really required. Maybe "(only used for "add")"?
  2. setprunelock <id> remove 123 is accepted and the height is silently ignored. That's not a problem, but it could be rejected, or the help could mention it.

@optout21 optout21 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed (d025cf1). Comments:

  • A side effect worth exploring: during any reorg, all prune locks above tip-1 are set to tip-1. Maybe this should not apply on manual blocks. The lowering is done in Chainstate::DisconnectTip().

  • No unit tests for the parsing helpers IsValidPruneLockId and ParsePruneLockArg.

  • listprunelocks returns user:testlock, but setprunelock only accepts testlock. Passing user:testlock fails because : isn't allowed. Should be more consistent.

Comment thread src/rpc/blockchain.cpp Resolved
Comment thread src/rpc/blockchain.cpp Resolved
@DrahtBot
DrahtBot requested a review from optout21 November 24, 2026 22:13
@fjahr
fjahr force-pushed the 2026-02-prunelocks-rpc-v2 branch 2 times, most recently from 70c2230 to 20cb220 Compare November 25, 2026 15:46
@fjahr

fjahr commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review @optout21!

A side effect worth exploring: during any reorg, all prune locks above tip-1 are set to tip-1. Maybe this should not apply on manual blocks.

I think this should still apply to manual locks too. An external indexer could run behind the chain just like the internal indexes and needs the blocks from the fork point on to handle the reorg. But you are right that this could be surprising behavior, so I add some mention of this in the setprunelock help.

No unit tests for the parsing helpers IsValidPruneLockId and ParsePruneLockArg.

The functional test covers a lot of invalid ids and values through both setprunelock and -prunelock which should provide good coverage of these helpers, so I left this as is.

listprunelocks returns user:testlock, but setprunelock only accepts testlock.

Right, the inconsistency could be confusing to some users. I opted for changing listprunelocks so it returns the id without the prefix and has a new type field (user or internal), so a listed id could be passed to setprunelock.

@GEREMIAA

Copy link
Copy Markdown

re-ACK 20cb220

Re-tested on Ubuntu 22.04.5, on a pruned signet node:

  • rpc_prunelock.py and the unit tests pass (378/378).
  • On a non-pruned node (regtest), setprunelock now fails with "Cannot set a prune lock because node is not in prune mode."
  • listprunelocks returns ids without the user: prefix, with the new type field, sorted by id. An id from the list can be passed directly to setprunelock <id> remove.
  • Locks still prevent pruning: with a lock at 331900, pruneblockchain 332150 kept block 331900.
  • The help now says "only used for "add"" and documents the reorg behavior. Thanks for taking that into account.

@andrewtoth

Copy link
Copy Markdown
Contributor

ACK 20cb220

@optout21

Copy link
Copy Markdown
Contributor

@fjahr , thanks for considering my points.
On the reorg issue: I agree. If there is a reorg, the external indexer will likely reindex the reorged height again as well.

@optout21

Copy link
Copy Markdown
Contributor

ACK 20cb220

Concluding my previous reviews with an ack, looks good!

A new comment/suggestion: Internally, the "user:" prefix is used to mark external locks. This is internal now -- added automatically by add, removed automatically when listed. The magic string prefix could be replaced by a bool flag or enum (but has to be part of the key, a composite key). This scheme would be less error prone, but also less flexible. Or, if the "user:" prefix is indeed internal, at least replace it with the more visible "USER:" or "EXT:" form.

fjahr and others added 6 commits November 29, 2026 15:27
This is needed in RPCs that manage prune locks manually.
These allow for manual management of prune locks by users and follow the UX pattern of setban/listbanned.

Co-authored-by: Luke Dashjr <[email protected]>
This allows to start a node with a prune lock already set in order to avoid racing with any unwanted pruning.
@fjahr
fjahr force-pushed the 2026-02-prunelocks-rpc-v2 branch from 20cb220 to dd6c67b Compare November 29, 2026 23:29
@fjahr

fjahr commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Internally, the "user:" prefix is used to mark external locks. This is internal now -- added automatically by add, removed automatically when listed. The magic string prefix could be replaced by a bool flag or enum (but has to be part of the key, a composite key). This scheme would be less error prone, but also less flexible. Or, if the "user:" prefix is indeed internal, at least replace it with the more visible "USER:" or "EXT:" form.

I agree that this would be cleaner and clearer and decided to implement this in another push. Sorry for invalidating the ACKs one more time but I hope the rest of the reviewers agree that this is better. I went with an enum to allow for new types like the wallet to be added later. Or if indexes are moved outside of the node at some point they may get a different category.

The change is roughly neutral in terms of LOC added/removed so I think the change overall get easier to review but those that need to re-review see a bit of churn, again sorry about that: https://github.com/bitcoin/bitcoin/compare/20cb220b55f746a8b4538f640aee374604863c85..dd6c67b0e5f6ffe184d101281eb107fcf32a26f6

@optout21

Copy link
Copy Markdown
Contributor

reACK dd6c67b

Sorry for triggering another ack-cycle, I'm keen on this PR to land :)
The enum is more pleasing than the string prefix operations (comparison, removal, etc.). Thanks for taking it!

git range-diff 20cb220...dd6c67b
git range-diff 1b2c63d..20cb220 9601d8c..dd6c67b

@andrewtoth andrewtoth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reACK dd6c67b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.