mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
wallet, sqlite: Enable secure_delete by default #36796
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!36796
Loading…
Reference in a new issue
No description provided.
Delete branch "raii-sqlite-secure-delete"
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?
Currently, when we make deletions or updates to the database that require records to be fully deleted and to not persist in free pages afterwards, we need to explicitly call
WalletDatabase::Rewrite. This behavior was introduced in #635 to ensure that unencrypted private keys are erased from the database after encrypting a wallet, and initial encryption is the only consumer of this function.However, initial encryption is not the only functionality that requires secure deletion. l0rinc's LLMs recently found changing the passphrase can leave the original that encryption key record in free pages. We should want to ensure that those records are also deleted, although I do not consider that the presence of such records in free space to actually be a problem. Note that this behavior appears to be present since wallet encryption was initially introduced in #352.
Fortunately, SQLite offers a secure_delete flag that can be enabled on each connection to a database. If set, all deletes or updates will ensure that any data that was deleted or overwritten actually are overwritten with 0's. It is one of the 2 methods in SQLite's documentation for ensuring that records do not persist in free pages, the other method being to call
VACUUMafter deletions or updates, which is whatRewritedoes.The downside is that secure_delete will increase CPU and disk I/O, which is why this was not set previously. However, it seems like several distros ship with secure_delete enabled by default: Debian, Ubuntu, Fedora, Arch, and NixOS all set SQLite's compile time option to default secure_delete to enabled, and these are just the ones I've looked at. This suggests to me that the performance penalty is not actually that bad. As I run Arch and often do not use depends builds, I had not noticed that secure_delete was always on and did not experience any particularly poor wallet performance that could be attributed to that behavior. In the grand scheme of things, erases and updates are fairly infrequent in the wallet.
This PR enables secure_delete when the database is opened, and also enables it by default in the sqlite depends package. There are also a couple tests to check that all records we want deleted actually are being deleted from the database.
WalletDatabase::Rewriteis removed as it it is no longer used.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.
LLM Linter (✨ experimental)
Possible typos and grammar issues:
src/wallet/sqlite.cpp:Enbling→Enabling[misspelling]2026-12-01 03:31:20
🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/42328113449/job/128268068670LLM reason (✨ experimental): CI failed because Python lint found six unnecessary semicolons in
test/functional/wallet_encryption.py.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.
Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments.
🟠 Minor · A close-time
incremental_vacuumfailure terminates the nodeIf reclaiming free pages fails during wallet unload or shutdown, the new close-time
incremental_vacuumthrows throughCleanup() noexceptand terminates the node.Location:
src/wallet/sqlite.cpp:403(head).🟠 Minor · Migration
VACUUMruns before wallet verificationExisting wallets with
auto_vacuum != 2are rewritten before schema and integrity verification, and a migration failure now prevents loading.Location:
src/wallet/sqlite.cpp:326(head).🔵 Suggestion ·
wallet_encryption.pynow skips all checks without Pythonsqlite3The unconditional
skip_if_no_py_sqlite3()removes existing encryption RPC coverage in environments without the optional module, although only the oldmkeycomparison needs database access.Location:
test/functional/wallet_encryption.py:35(head).🔵 Suggestion ·
Rewrite()disappears before replacement migration cleanup landsRemoving
Rewrite()one commit before adding migrationVACUUMmakes the cleanup transition harder to validate for wallets containing stale records from older releases.Location: src/wallet/wallet.cpp:851 (commit).
Review coverage was incomplete.
Reviewed:
d0868f381ae4· Review report · Previous reportspermalink
Concept ACK
For a wallet created at this head, no copy of the plaintext key stays in
wallet.dat-journalafterencryptwallet, while the wallet is loaded or after akill -9.I ran
encryptwalleton a fresh descriptor wallet at96352f5200and counted copies of its 32-byte xprv private key in its files. I linked bitcoind against Homebrew SQLite and against depends, both leavingsecure_deleteoff by default, so only the pragma this PR adds can zero the pages.wallet.datand the journal held 0 copies while loaded, after akill -9, and after a restart and reload. The same run on the head of #36793, which still relies on VACUUM, left 6 copies in the journal, 1 after the restart.The script, builds and output are in https://gist.github.com/fametrano/245e7d7aa2a4762d2ce7c102e097b92f/7cf068b0300062264dce40a1838c98d4958504b0.
Looks like there's a typo here.
Oops fixed
ACK
38c28393cbtACK
38c28393cbWith the
secure_deletepragma removed fromSQLiteDatabase::Open, the depends default alone now keeps the key out ofwallet.datand its journal. Linked against the depends SQLite built at38c28393cb,wallet.datand its journal held no copy of the plaintext key afterencryptwallet, after akill -9, or after the restart. Linked against the one built at96352f5200,wallet.datheld 6 copies, and the journal 14 after encryption, 14 after the kill and 5 after the restart.The PR as pushed left no copy with Homebrew SQLite or with either depends build.
wallet_encryption.pyand the wallet unit tests pass at this head. As before, this covers a freshly created wallet.The builds, script and output are in https://gist.github.com/fametrano/ef1fb32f05c8163272c8be27aeb32cf2/c4fe15cebece1cc35956f636de8648a74ce8940c.
Concept ACK
Tested
38c28393cbagainst mastera527a0077aon macOS 27.2.1 arm64.With macOS system SQLite (
secure_delete=2, FAST), master and the PR produced the same results, and the PR'swallet_encryption.pypassed on both. With Homebrew SQLite 3.54.1 (secure_delete=0by default), the test failed on master at line 118 because the oldmkeywas still present, and passed with the PR.The Homebrew build confirmed both that the PR prevents new residues and that pre-upgrade residues can persist, as noted in the Ralph review:
mkeyafterwalletpassphrasechangewallet.dat; an equivalent wallet encrypted on master has 0mkeyresidue left by a passphrase change on masterEnabling
secure_deleteprevents new residues in these tests, but does not remove existing ones. Removing the encryption-timeVACUUMtherefore leaves plaintext private-key copies in an existing wallet that master would have removed when encrypting it.As encryption only happens on specific paths, what about enabling secure deletion only for the DB connection that will erase the keys? Otherwise all wallet workflows pay the option overhead for no reason. As we never delete other records during any common path.
We currently keep a single DB connection per wallet for its entire lifetime, but as we lock
cs_walletduring the entire operation, we can create a new connection only for this use case, with the secure deletion option enabled, then close it and resume/recreate the lifetime one.My original plan was to do something like that, to enable and disable secure delete as needed. But as I was testing that, I realized that multiple distros ship with sqlite compiled with secure delete enabled by default, so I figured the performance cost of enabling secure delete always probably isn't actually that bad. Enabling it always makes this much easier to reason about as well.
🐙 This pull request conflicts with the target branch and needs rebase.
🐙 This pull request conflicts with the target branch and needs rebase.
Concept ACK
While this solves the encryption key leak during passphrase change for new wallets, it introduces something worse, as the removal of
Rewriteleaves private keys dangling in existing wallets after encryption.Can cherry-pick the following test to reproduce the behavior here (see
test_encrypt_wallet): https://github.com/furszy/bitcoin-core/blob/2026_wallet_where_is_my_key/test/functional/wallet_encryption_compatibility.pyEssentially, previous releases don't have
secure_deleteenabled, so when a page fills up, SQLite moves its records to a new page without erasing them from the old one. Creating a wallet always fills its first page, so that page keeps old copies of the first records. These leftovers are no longer part of any record, so SQLite doesn't track them, andsecure_deletenever sees them (it only zeroes data being touched at the moment it's deleted). So when such a prev-release wallet is encrypted with this PR, the key records get replaced and zeroed, but the old raw copies stay.So, while I also agree on having
secure_deleteenabled by default, it doesn't let us drop theVACUUMcleanup. Just pushed a branch with everything, including a few more tests too: 2026_wallet_where_is_my_key. All yours if you like it.Cherry picked the test.
As long as we vacuum old databases prior to encrypting them, we can still drop
Rewrite. I was looking at enablingauto_vacuumfor disk space saving, and if we were to enable it, we would need to perform aVACUUM, so I've added a commit that does that. This both enables additional disk space saving, and automatic vacuum for old databases (without running vacuum every time) which allows us to drop the vacuum after encrypting.