wallet: make migration more robust against failures #34193

pull furszy wants to merge 9 commits into bitcoin:master from furszy:2026_wallet_safer_MigrateToSQLite changing 7 files +330 −111
  1. furszy commented at 8:59 PM on January 2, 2026: member

    This is just me finding a few more edge cases after #34156 and #34176

    The goal of the PR is to handle failures in a controlled way. Just so the process can automatically restore the original wallet without requiring user manual intervention.

    The covered cases are:

    1. During DoMigration(): There are methods that can throw exceptions and abruptly abort the process.
 Instead of crashing (GUI) or returning a generic exception, we now will catch and return the error gracefully. This lets the process restore the original wallet automatically.

    2. Trying to migrate a wallet in a read-only directory throws a filesystem exception and skips cleanup. Now the process will fail gracefully with a clear error msg, and automatically restore the original wallet.

    3. Any failure during MigrateToSQLite requires user manual intervention.
 Now the original wallet db will remain untouched, and only be updated once the sqlite db creation fully succeeds.

  2. DrahtBot added the label Wallet on Jan 2, 2026
  3. DrahtBot commented at 8:59 PM on January 2, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

    The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

    See the guideline and AI policy for information on the review process.

    Type Reviewers
    ACK ryanofsky, w0xlt

    If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore.

    <!--174a7506f384e20aa4161008e828411d-->

    Conflicts

    Reviewers, this pull request conflicts with the following ones:

    • #36897 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36897.svg"></sub> (wallet, migration: Contain all legacy wallet and migration related things in its own subdirectory, namespace, and classes by achow101)
    • #36823 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36823.svg"></sub> (wallet, migration: Skip legacy wallet records rather than erasing them, and drop unused record erase functions by achow101)
    • #36743 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36743.svg"></sub> ([RFC] build: build with -Wmissing-declarations/prototypes by fanquake)
    • #36444 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36444.svg"></sub> (wallet: Store information about created and imported multipath descriptors by achow101)
    • #36443 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36443.svg"></sub> (descriptor: Reconstruct a multipath descriptor from its expansion by achow101)
    • #36442 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36442.svg"></sub> (descriptor: Represent multipath descriptors in a single Descriptor object by achow101)
    • #36087 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36087.svg"></sub> (util: Add and use AssertUnreachable by maflcko)
    • #35911 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35911.svg"></sub> (Warn on and add missing [[noreturn]] by fanquake)
    • #34909 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34909.svg"></sub> (wallet, refactor: modularise wallet by extracting out legacy wallet migration by rkrux)
    • #34603 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34603.svg"></sub> (wallet: Fix detection of symlinks on Windows by achow101)
    • #31260 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/31260.svg"></sub> (scripted-diff: Type-safe settings retrieval by ryanofsky)
    • #30343 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/30343.svg"></sub> (wallet, logging: Replace WalletLogPrintf() with LogInfo() by ryanofsky)

    If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

    LLM Linter (✨ experimental)

    Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

    • src/wallet/wallet.cpp: WalletDescriptor(std::move(descs.at(0)), creation_time, 0, 0, 0)
    • src/wallet/wallet.cpp: out_wallet->AddWalletDescriptor(w_desc, keys, "", false)

    <sup>2026-11-13 20:31:05</sup>

  4. furszy closed this on Jan 2, 2026

  5. furszy renamed this:
    wallet: make migration more robust
    wallet: make migration more robust against failures
    on Jan 2, 2026
  6. furszy reopened this on Jan 2, 2026

  7. furszy force-pushed on Jan 2, 2026
  8. DrahtBot added the label CI failed on Jan 2, 2026
  9. furszy force-pushed on Jan 4, 2026
  10. furszy force-pushed on Jan 4, 2026
  11. furszy force-pushed on Jan 5, 2026
  12. hebasto commented at 12:08 PM on January 5, 2026: member

    Looks like the CI fails for msvcrt, but not for ucrt:

    Run ./bin/bench_bitcoin.exe -sanity-check
    Running with -sanity-check option, output is being suppressed as benchmark results will be useless.
    Error: filesystem error: cannot copy: File exists [C:\Users\RUNNER~1\AppData\Local\Temp\test_common bitcoin\WalletMigration\bb3603a0a694b3c4c79a\regtest\tmp_sqlite_13776532190043757581] [C:\Users\RUNNER~1\AppData\Local\Temp\test_common bitcoin\WalletMigration\bb3603a0a694b3c4c79a\regtest]
    

    https://github.com/bitcoin/bitcoin/actions/runs/20702313540/job/59427203126?pr=34193#step:9:200

    Specifically, the WalletMigration benchmark fails.

  13. DrahtBot added the label Needs rebase on Jan 7, 2026
  14. in src/util/fs_helpers.cpp:308 in eb5e076b18
     304 | @@ -304,6 +305,28 @@ std::optional<fs::perms> InterpretPermString(const std::string& s)
     305 |      }
     306 |  }
     307 |  
     308 | +bool IsFileWritable(const fs::path& file)
    


    ryanofsky commented at 3:18 PM on January 7, 2026:

    In commit "wallet: fail migration gracefully on non-writable wallets" (eb5e076b189aa5dadb9572f3ce7b33eb609d7b69)

    Was skimming this PR and the first few commits seem reasonable, but I’d advise against the approach in the last two commits of checking whether paths are writable before writing, rather than handling write failures directly. A few concerns:

    1. It masks other problems. Write failures should surface through the normal error-reporting paths with clear messages, regardless of where they originate. Pre-checks bypass those paths and can obscure or regress error reporting, especially if lower-level errors improve over time.

    2. It adds unnecessary complexity. The write still has to be attempted, so the pre-check duplicates logic without simplifying the code.

    3. It introduces TOCTOU risks. A path that is writable at check time may not be writable at write time.

    In general, attempting the write and handling failures directly is simpler, more robust, and leads to better error reporting.


    furszy commented at 8:42 PM on January 7, 2026:

    The issue here is that we are doing low-level operations. Basically, we are:

    1. Loading all BDB records into memory.
    2. Deleting the BDB file.
    3. Creating a new sqlite db.
    4. Writing all records to the new db.

    The added checks are meant to avoid failing with a generic filesystem exception at step (2), during the BDB deletion, which can be located in a different directory than the sqlite one we are about to create

    But.. thinking further, we could handle this differently by catching the exception directly from the fs::remove call instead. Let me see why I didn't do it in that way before, there must be a reason.

    Also, the last commit is about not removing the original wallet until we are sure the sqlite one has at least been created successfully. If we are not able to write to disk at that point, the migration will fail anyway. This function is just the early "move everything from BDB to sqlite" step; we still need to create and store the descriptors, remove the old records, and so on.

  15. furszy force-pushed on Jan 7, 2026
  16. DrahtBot removed the label Needs rebase on Jan 7, 2026
  17. furszy force-pushed on Jan 8, 2026
  18. furszy force-pushed on Jan 19, 2026
  19. furszy commented at 2:45 PM on January 19, 2026: member

    Maybe turn into draft while the CI is red?

    thanks for the ping, wasn't aware of the failure.

  20. furszy force-pushed on Jan 19, 2026
  21. DrahtBot removed the label CI failed on Jan 19, 2026
  22. DrahtBot added the label Needs rebase on Jan 26, 2026
  23. furszy force-pushed on Jan 26, 2026
  24. DrahtBot removed the label Needs rebase on Jan 26, 2026
  25. DrahtBot added the label CI failed on Jan 26, 2026
  26. in src/wallet/wallet.cpp:3866 in e1886ab9b1
    3874 |      // Generate the path for the location of the migrated wallet
    3875 |      // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
    3876 | -    const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
    3877 | +    const fs::path dst_wallet_path = fs::weakly_canonical(fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name)));
    3878 | +    // After importing all records, the new DB at tmp_wallet_path will replace the original wallet at dst_wallet_path.
    3879 | +    std::string new_db_name = strprintf("tmp_sqlite_%d", FastRandomContext().rand64());
    


    achow101 commented at 9:21 PM on January 26, 2026:

    In e1886ab9b1abfa485bfce25b51f2dd9b566cb26a "wallet: migration, make sqlite creation robust against failures"

    Could use a name that is a more informative if there's an issue with moving the wallet back, maybe tmp_sqlite_<wallet name>_<timestamp>


    furszy commented at 10:44 PM on January 26, 2026:

    Sure. Done as suggested.

  27. in src/wallet/wallet.cpp:3813 in e1886ab9b1
    3808 | +    for (const auto& entry : fs::directory_iterator(src)) {
    3809 | +        fs::path filename = entry.path().filename();
    3810 | +        fs::path target = dst / filename;
    3811 | +
    3812 | +        if (fs::exists(target)) {
    3813 | +            throw fs::filesystem_error("destination already exists", entry.path(), target, std::make_error_code(std::errc::file_exists));
    


    achow101 commented at 9:24 PM on January 26, 2026:

    In e1886ab9b1abfa485bfce25b51f2dd9b566cb26a "wallet: migration, make sqlite creation robust against failures"

    Why throw instead of returning an error? MigrateToSQLite already bypasses failed migration cleanup.


    furszy commented at 10:46 PM on January 26, 2026:

    I coded it with half of my brain. Done. Changed it to return an error instead.

  28. DrahtBot removed the label CI failed on Jan 26, 2026
  29. furszy force-pushed on Jan 26, 2026
  30. furszy force-pushed on Jan 26, 2026
  31. DrahtBot added the label CI failed on Jan 26, 2026
  32. DrahtBot commented at 11:05 PM on January 26, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task Windows-cross to x86_64, ucrt: https://github.com/bitcoin/bitcoin/actions/runs/21376876348/job/61534946085</sub> <sub>LLM reason (✨ experimental): Compilation failed: invalid initialization of a const std::string& from a std::filesystem::path in wallet.cpp (PathFromString argument type mismatch).</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  33. furszy force-pushed on Jan 27, 2026
  34. furszy force-pushed on Jan 27, 2026
  35. DrahtBot removed the label CI failed on Jan 27, 2026
  36. DrahtBot added the label Needs rebase on Feb 4, 2026
  37. furszy force-pushed on Feb 4, 2026
  38. DrahtBot removed the label Needs rebase on Feb 4, 2026
  39. sedited requested review from ryanofsky on May 23, 2026
  40. DrahtBot added the label Needs rebase on May 28, 2026
  41. in src/wallet/wallet.cpp:3884 in 09a09e48b5
    3880 | +    fs::remove(db_path, err_db);
    3881 | +    if (err_db) {
    3882 | +        std::string err_help;
    3883 | +        const bool perm_issue = err_db.value() == EACCES || err_db.value() == EPERM  || err_db.value() == EROFS;
    3884 | +        if (perm_issue) err_help = "Adjust directory or file permissions to proceed with migration.";
    3885 | +        error = strprintf(_("Error: Wallet db cannot be updated. %s"), err_help);
    


    ryanofsky commented at 12:12 AM on June 25, 2026:

    In commit "wallet: fail migration gracefully on non-writable wallets" (09a09e48b53dcf7c10f9f4b89a7d3697589751e1)

    Would be good to include more details in the message like strprintf(_("Error: Wallet db cannot be updated. Path: %s, Error: %s.%s"), db_path, err_db.message(), err_help);. Error messages saying something failed without saying why it failed can be frustrating to deal with.


    furszy commented at 9:13 PM on September 2, 2026:

    done as suggested. Thanks!


    ryanofsky commented at 5:14 PM on November 5, 2026:

    re: #34193 (review)

    In commit "wallet: fail migration gracefully on non-writable wallets" (75d796ce3aa4d73364a451bff0db9f72ce24fd04)

    done as suggested

    Thanks! It looks like the path and error text were added in the later commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0) instead of this one, so in this commit the message still doesn't say which error happened. Could they go in this commit, where the message is added?

    It would also be nice to fold the next commit "test: add coverage for migrating a non-writable wallet" (0f5fbb14a8ffe42dcf323ad32a7cff9f6da29245) into this one, since the test checks exactly this error path, and then it can check the full message from the start. If you'd rather keep them separate, it would help to mention the test in this commit message and this commit in the test's commit message, so it's clear they go together. This PR isn't easy to review, and seeing the test change next to the code change makes both easier to follow: the code change is easier to understand because the test shows exactly how the behavior changes, and the test change is easier to understand because the code it tests is right there and doesn't have to be looked up.

  42. in src/wallet/wallet.cpp:3838 in 406c14db5b
    3832 | @@ -3833,6 +3833,36 @@ util::Result<std::reference_wrapper<DescriptorScriptPubKeyMan>> CWallet::AddWall
    3833 |      return std::reference_wrapper(*spk_man);
    3834 |  }
    3835 |  
    3836 | +// Move files from `src` into `dst`.
    3837 | +// Note: This function doesn't recurse: `src` must not contain subdirectories.
    3838 | +util::Result<void> MoveDirContent(const fs::path& src, const fs::path& dst)
    


    ryanofsky commented at 12:55 AM on June 25, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (406c14db5b16c2e1befdef76d6debd0b0ca4f6c2)

    This function returns util::Result but contains a lot of filesystem calls that can throw exceptions (directory_iterator constructor, fs::exists, fs::rename). It could be good to call non throwing version of these function and return error messages if these calls fail, or wrap the function body in a try/catch. Or keep current code but document that this can throw in addition to return a Result error so callers know to handle this.


    furszy commented at 9:16 PM on September 2, 2026:

    Ended up dropping the function entirely. We don't need such machinery. The db is just a single .dat sqlite file and can be moved in isolation. I probably was way too worried about the wallets/ deletion bug back then and overthought this.

  43. in src/wallet/wallet.cpp:3847 in 406c14db5b
    3842 | +
    3843 | +    // Validate all dst paths up front to avoid partial moves
    3844 | +    std::vector<std::pair<fs::path, fs::path>> files_to_move;
    3845 | +    for (const auto& entry : fs::directory_iterator(src)) {
    3846 | +        const fs::path target = dst / fs::path(entry.path().filename());
    3847 | +        if (fs::exists(target)) {
    


    ryanofsky commented at 12:58 AM on June 25, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (406c14db5b16c2e1befdef76d6debd0b0ca4f6c2)

    fs::exists will follow symlinks which is probably not what we want here. Also this can return false if target is a broken symlink. Could use if (fs::is_symlink(target) || fs::exists(target)) or similar to prevent these things

  44. in src/wallet/wallet.cpp:3943 in 406c14db5b
    3957 | -            assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    3958 | +            assert(false); // This is a critical error, the new db could not be written to. The original db is untouched, so we can abort safely.
    3959 |          }
    3960 |      }
    3961 |      bool committed = batch->TxnCommit();
    3962 |      assert(committed); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    


    ryanofsky commented at 12:59 AM on June 25, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (406c14db5b16c2e1befdef76d6debd0b0ca4f6c2)

    s/exists as a backup/is untouched/ here as well

  45. in src/wallet/wallet.cpp:3933 in 406c14db5b
    3946 | +
    3947 |      // Write existing records into the new DB
    3948 |      batch = m_database->MakeBatch();
    3949 |      bool began = batch->TxnBegin();
    3950 | -    assert(began); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    3951 | +    assert(began); // This is a critical error, the new db could not be written to. The original db is untouched, so we can abort safely.
    


    ryanofsky commented at 1:05 AM on June 25, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (406c14db5b16c2e1befdef76d6debd0b0ca4f6c2)

    Now that original database is kept in place at this point, instead of being deleted, it would seem nice to replace these asserts with simple failures. Previously it (sort of) made sense to crash the process at this point since the database was in half-written incomplete state. But now the original database is unchanged, and there isn't actually a critical error anymore.


    furszy commented at 9:17 PM on September 2, 2026:

    Sure, done as suggested. Thanks!

  46. in src/wallet/wallet.cpp:3957 in 406c14db5b
    3971 | +    if (err_db) {
    3972 | +        std::string err_help;
    3973 | +        const bool perm_issue = err_db.value() == EACCES || err_db.value() == EPERM  || err_db.value() == EROFS;
    3974 | +        if (perm_issue) err_help = "Adjust directory or file permissions to proceed with migration.";
    3975 | +        error = strprintf(_("Error: Wallet db cannot be updated. %s"), err_help);
    3976 | +        return false;
    


    ryanofsky commented at 1:09 AM on June 25, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (406c14db5b16c2e1befdef76d6debd0b0ca4f6c2)

    Could delete tmp_wallet_path here

  47. in src/wallet/wallet.cpp:3923 in 406c14db5b
    3935 |      opts.require_format = DatabaseFormat::SQLITE;
    3936 |      DatabaseStatus db_status;
    3937 | -    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);
    3938 | -    assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.
    3939 | +    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(tmp_wallet_path, opts, db_status, error);
    3940 | +    if (!new_db) return false; // error msg appended internally
    


    ryanofsky commented at 1:12 AM on June 25, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (406c14db5b16c2e1befdef76d6debd0b0ca4f6c2)

    Could delete tmp_wallet_path here. Also not sure if of the code populating this database will throw, but it would also seem good to delete it in that case too.


    furszy commented at 9:17 PM on September 2, 2026:

    Sure, done as suggested. Thanks!

  48. in src/wallet/wallet.cpp:3951 in 406c14db5b outdated
    3965 | +    // ######################################################################
    3966 | +    // At this point, the new database has all records.                     #
    3967 | +    // We can remove the old db file and move the new db inside the wallet  #
    3968 | +    // ######################################################################
    3969 | +    std::error_code err_db;
    3970 | +    fs::remove(origin_db_path, err_db);
    


    ryanofsky commented at 1:53 AM on June 25, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (406c14db5b16c2e1befdef76d6debd0b0ca4f6c2)

    If after anything after this fs::remove fails (like the renames below or the removes or the MakeDatabase call) or throws, then the wallet directory will be an a bad state and the user will have to manually restore from a backup. This was also the case with the previous fs::remove call, but that code has had more testing while this code is new. So it might be more likely to have problems. Might be possible to address this by having MigrateLegacyToDescriptor call RestoreWallet in this case.


    furszy commented at 9:18 PM on September 2, 2026:

    All cases should be covered now, thanks!


    ryanofsky commented at 1:59 PM on November 5, 2026:

    re: #34193 (review)

    In commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0)

    All cases should be covered now

    Thanks, this is much better now that all records are written before the original file is removed, and the catch added in the last commit covers TryCreateDirectories throwing. But from reading the code I think two failures after this fs::remove still need manual recovery:

    • If copy_file fails, fail() deletes the temporary sqlite db and MigrateToSQLite returns false. MigrateLegacyToDescriptor then returns the error right away without reaching the restore code, so the wallet directory is left with no wallet.dat (or possibly a partial one), and the only copy of the wallet is the .legacy.bak file, which the error message doesn't mention.
    • If reopening the database fails, the Assert on MakeDatabase crashes the node.

    One way to cover both would be to throw instead of returning false once the original file is removed, and the same instead of the Assert, so the new catch block sends them through the restore path. Returning false is still right before that point, since the original file is untouched then. The separate comment about renaming instead of copying would also remove the partial copy case.

  49. ryanofsky approved
  50. ryanofsky commented at 1:59 AM on June 25, 2026: contributor

    Code review ACK 406c14db5b16c2e1befdef76d6debd0b0ca4f6c2. I think this looks good, and all the changes here seem safe, but given complexity of the code would want to have another pass of review to have more confidence there are no bugs.

    On the approach: first 4 commits look great and straightforwardly improve error handling. Initial concern i had earlier about trying to predict whether paths were writable is resolved and well handled.

    The last commit should also be a net improvement, but is more of a mixed bag. The last commit provides a potentially significant benefit because it delays deleting the original wallet database until the new sqlite database is fully created, so if there are errors creating it, the old wallet will be left in place, and it it can be migrated again later (or dumped or opened in an old version of bitcoin core) without the user manually needing to restore from the backup file.

    The downside of the last commit is it adds more complexity to code that is already pretty complex, and leaves filesystem in a slightly messier state because if creating and populating the sqlite database fails there will now be two copies of the original bdb database instead of one.

    More ideally the code would get rid of all these deletes and renames and backups and restores and just leave the original data exactly where it is during the migration, writing the new data to temporary directory. Then do simple renames if the migration succeeds, renaming the old wallet to have a migrated_<timestamp> suffix and renaming the new wallet directories in its place.

  51. sedited commented at 11:03 AM on August 27, 2026: contributor

    @furszy can you rebase and address @ryanofsky's comments?

  52. furszy force-pushed on Sep 2, 2026
  53. DrahtBot removed the label Needs rebase on Sep 2, 2026
  54. furszy force-pushed on Sep 2, 2026
  55. DrahtBot added the label CI failed on Sep 2, 2026
  56. DrahtBot commented at 9:01 PM on September 2, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task lint: https://github.com/bitcoin/bitcoin/actions/runs/33681544029/job/100419038857</sub> <sub>LLM reason (✨ experimental): CI failed due to a lint violation: shutil.rmtree() usage flagged as dangerous in test/functional/wallet_migration.py (lint check rmtree).</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  57. furszy force-pushed on Sep 2, 2026
  58. furszy commented at 9:13 PM on September 2, 2026: member

    Updated per feedback. Thanks @ryanofsky! sorry for the delay.

    More ideally the code would get rid of all these deletes and renames and backups and restores and just leave the original data exactly where it is during the migration, writing the new data to temporary directory. Then do simple renames if the migration succeeds, renaming the old wallet to have a migrated_ suffix and renaming the new wallet directories in its place.

    I had a branch for this ~2.5 years ago (it should still be in my repo fork), creating a new wallet and importing descriptors, txs, metadata there, etc. which was letting us remove MigrateToSQLite entirely, but I wasn't convinced it was ever going to be merged due to all the bugs we were continually finding within the process back then, and some other refactoring that was needed. We are much better now to retry to implement it but I hardly see such a big change landing at this point in time.

  59. DrahtBot removed the label CI failed on Sep 2, 2026
  60. DrahtBot added the label Needs rebase on Sep 14, 2026
  61. sedited commented at 6:10 AM on October 19, 2026: contributor

    @furszy ping for rebase?

  62. furszy force-pushed on Oct 19, 2026
  63. DrahtBot removed the label Needs rebase on Oct 19, 2026
  64. DrahtBot added the label Needs rebase on Oct 20, 2026
  65. furszy force-pushed on Nov 4, 2026
  66. DrahtBot removed the label Needs rebase on Nov 4, 2026
  67. in src/wallet/wallet.cpp:3815 in b9486540d7
    3816 | +    const std::string name_prefix = m_name.empty() ? MigrationPrefixName(*this) : [&] {
    3817 | +        const auto legacy_wallet_path = fs::weakly_canonical(GetWalletDir() / fs::PathFromString(m_name));
    3818 | +        return fs::PathToString(legacy_wallet_path.filename());
    3819 | +    }();
    3820 | +    const std::string new_db_name = strprintf("%s_sqlite_%d.tmp", name_prefix, GetTime());
    3821 | +    const fs::path tmp_wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(new_db_name));
    


    ryanofsky commented at 1:59 PM on November 5, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0)

    Would it work to create the temporary database next to the original file, in origin_db_path.parent_path(), instead of in the wallets directory? Then it is always on the same filesystem as the destination, and the copy_file call below could be a fs::rename:

    • The move becomes atomic, so a failure can't leave a partially copied wallet.dat behind.
    • There is no need to copy a possibly large file, or for the new copy_file overload in fs.h.
    • As far as I can tell copy_file doesn't sync the new file to disk before remove_tmp() deletes the source, so a crash shortly after migration could leave a truncated wallet.dat. A rename keeps the data sqlite already synced.

    For directory wallets that location is the wallet's own directory, and for plain-file wallets it's the directory containing the file, where the new wallet directory is created. The read-only directory test would then fail earlier, when creating the temporary database, with a different message, which seems fine since nothing has been changed at that point either. The other-filesystem test would still be worth keeping.


    furszy commented at 8:54 PM on November 10, 2026:

    Sure, done as suggested. I think I wasn't so happy creating a file in a directory the wallet doesn't "own" when I did this, but.. the truth is that we always migrate in-place anyway.

  68. in src/wallet/wallet.cpp:3847 in b9486540d7
    3865 | +            if (!in_batch.Write(std::span{key}, std::span{value})) return false;
    3866 | +        }
    3867 | +        return true;
    3868 | +    });
    3869 | +    if (!written) {
    3870 | +        return fail(strprintf(_("Error: Unable to write records into the new database for wallet '%s'"), GetName()));
    


    ryanofsky commented at 1:59 PM on November 5, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0)

    Here and in the fs::remove(origin_db_path) error case below, fail() removes the temporary files while new_db still has the database open. I believe on Windows the removes fail (and the errors are ignored), leaving the _sqlite_*.tmp directory behind, and on other platforms sqlite keeps writing to an unlinked file until new_db is destroyed. Could call new_db.reset(); before both return fail(...) calls, or declare new_db before the fail lambda and reset it there.

    Also, remove_tmp only deletes the data file, so a wallet.dat-journal left by a failed commit or rollback would keep the directory from being removed. It could delete everything in new_db->Files(), saved before the reset.


    furszy commented at 8:57 PM on November 10, 2026:

    Good catch, fixed. Thanks! Added an extra check too. The tests should catch this now.

  69. in src/wallet/wallet.cpp:3813 in b9486540d7
    3814 | +    // Create a temporary database in the wallets directory. The process will replace the
    3815 | +    // real one upon completion.
    3816 | +    const std::string name_prefix = m_name.empty() ? MigrationPrefixName(*this) : [&] {
    3817 | +        const auto legacy_wallet_path = fs::weakly_canonical(GetWalletDir() / fs::PathFromString(m_name));
    3818 | +        return fs::PathToString(legacy_wallet_path.filename());
    3819 | +    }();
    


    ryanofsky commented at 1:59 PM on November 5, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0)

    This duplicates the backup_prefix code in MigrateLegacyToDescriptor, which is nontrivial and IMO fragile. It would make more sense to move into a helper both places call so the logic is not duplicated and both call sites can be simpler. Here is a refactoring that can be applied with git apply on top of this commit, with no change in behavior:

    <details><summary>diff</summary> <p>

    diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
    index a40794237f5..8e21044bfb9 100644
    --- a/src/wallet/wallet.cpp
    +++ b/src/wallet/wallet.cpp
    @@ -3755,7 +3755,7 @@ util::Expected<CExtPubKey, WalletError> CWallet::AddHDKey(const std::optional<CE
     }
    
     // Returns wallet prefix for migration.
    -// Used to name the backup file and newly created wallets.
    +// Used to name the newly created wallets.
     // E.g. a watch-only wallet is named "<prefix>_watchonly".
     static std::string MigrationPrefixName(CWallet& wallet)
     {
    @@ -3763,6 +3763,18 @@ static std::string MigrationPrefixName(CWallet& wallet)
         return name.empty() ? "default_wallet" : name;
     }
    
    +// Returns prefix for files created in the wallets directory during migration:
    +// the backup file and the temporary database. Unlike MigrationPrefixName(),
    +// this is a single path component, because the wallet name can be a path.
    +static std::string MigrationFilePrefix(CWallet& wallet)
    +{
    +    const std::string& name{wallet.GetName()};
    +    if (name.empty()) return MigrationPrefixName(wallet);
    +    // fs::weakly_canonical resolves relative specifiers and removes trailing slashes.
    +    const fs::path legacy_wallet_path{fs::weakly_canonical(GetWalletDir() / fs::PathFromString(name))};
    +    return fs::PathToString(legacy_wallet_path.filename());
    +}
    +
     bool CWallet::MigrateToSQLite(bilingual_str& error)
     {
         AssertLockHeld(cs_wallet);
    @@ -3807,11 +3819,7 @@ bool CWallet::MigrateToSQLite(bilingual_str& error)
    
         // Create a temporary database in the wallets directory. The process will replace the
         // real one upon completion.
    -    const std::string name_prefix = m_name.empty() ? MigrationPrefixName(*this) : [&] {
    -        const auto legacy_wallet_path = fs::weakly_canonical(GetWalletDir() / fs::PathFromString(m_name));
    -        return fs::PathToString(legacy_wallet_path.filename());
    -    }();
    -    const std::string new_db_name = strprintf("%s_sqlite_%d.tmp", name_prefix, GetTime());
    +    const std::string new_db_name = strprintf("%s_sqlite_%d.tmp", MigrationFilePrefix(*this), GetTime());
         const fs::path tmp_wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(new_db_name));
         if (fs::exists(fs::symlink_status(tmp_wallet_path))) {
             error = strprintf(_("Error: Unable to create new database for wallet '%s': temporary path '%s' already exists"), GetName(), fs::PathToString(tmp_wallet_path));
    @@ -4290,11 +4298,7 @@ util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet>
         // cases, but in the case where the wallet name is a path to a data file,
         // the name of the data file is used, and in the case where the wallet name
         // is blank, "default_wallet" is used.
    -    const std::string backup_prefix = wallet_name.empty() ? MigrationPrefixName(*local_wallet) : [&] {
    -        // fs::weakly_canonical resolves relative specifiers and remove trailing slashes.
    -        const auto legacy_wallet_path = fs::weakly_canonical(GetWalletDir() / fs::PathFromString(wallet_name));
    -        return fs::PathToString(legacy_wallet_path.filename());
    -    }();
    +    const std::string backup_prefix = MigrationFilePrefix(*local_wallet);
    
         fs::path backup_filename = fs::PathFromString(strprintf("%s_%d.legacy.bak", backup_prefix, GetTime()));
         fs::path backup_path = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
    

    </p> </details>


    furszy commented at 8:58 PM on November 10, 2026:

    Cool, taken. Added it before the "make sqlite creation robust against failures" commit to shorten the review burden a bit there.

  70. in src/wallet/wallet.cpp:4113 in 4931d63c07 outdated
    4126 | -                error = _("Error: Failed to create new watchonly wallet");
    4127 | -                return false;
    4128 | -            }
    4129 | -            res.watchonly_wallet = data->watchonly_wallet;
    4130 | -            LOCK(data->watchonly_wallet->cs_wallet);
    4131 | +        const auto fn_create_wallet = [&context, &options, &empty_context, load_on_startup](const std::string& wallet_name,
    


    ryanofsky commented at 2:22 PM on November 5, 2026:

    In commit "wallet: migration, unify watchonly and solvables wallets creation" (4931d63c074b7d982656f5fb48b8ec0dfcefac3c)

    Great change! Thanks for deduplicating this code. Having one fn_create_wallet lambda also makes the later error handling changes easier to review, since the try/catch only has to be added once. Since the error message after CreateNew is now shared, it could include the wallet name, like _("Error: Failed to create new wallet '%s'"). It currently says "watchonly" for the solvables wallet too, though that was already the case before this change.


    furszy commented at 8:59 PM on November 10, 2026:

    Sure, done as suggested.

  71. in src/wallet/wallet.cpp:4338 in 3ca388f099 outdated
    4332 | @@ -4313,6 +4333,8 @@ util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet>
    4333 |              local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
    4334 |              success = true;
    4335 |          }
    4336 | +    } catch (const std::exception& e) {
    4337 | +        error = Untranslated(strprintf("Unexpected exception during migration: %s", e.what()));
    4338 |      }
    


    ryanofsky commented at 5:14 PM on November 5, 2026:

    In commit "wallet: safety-belt, catch exceptions during migration" (3ca388f099c6a161faa40bf8b91c5aa89cb5b11d)

    Could the commit message say what changes for users? As I understand it, the cleanup and restore code at the end of MigrateLegacyToDescriptor already ran when DoMigration returned an error or the migrated wallets failed to load, but an exception thrown from MigrateToSQLite or DoMigration skipped it. The RPC returned the exception text, and the user was left with a partially migrated wallet and had to restore the backup and delete the new wallet files manually. Now the exception becomes an error and the same cleanup runs. Maybe something like:

    wallet: migration, restore backup if an exception is thrown
    
    If MigrateToSQLite or DoMigration throws, the exception previously skipped the failure handling at the end of MigrateLegacyToDescriptor. The RPC returned the exception message, and the user was left with a partially migrated wallet and had to restore the .legacy.bak backup and delete the new wallet files manually.
    
    Catch these exceptions so the failed migration is cleaned up and the original wallet is restored from the backup automatically, the same way as when DoMigration returns an error.
    

    It could also mention which exceptions are expected here. For example, TryCreateDirectories in MigrateToSQLite can throw after the original database has been deleted, which is the case where this matters most.


    furszy commented at 9:00 PM on November 10, 2026:

    Sure, done as suggested.

  72. in src/wallet/wallet.cpp:4155 in f8602f4b5e outdated
    4148 | @@ -4148,6 +4149,10 @@ bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error,
    4149 |                  // Add the wallet to settings
    4150 |                  UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);
    4151 |                  return true;
    4152 | +            } catch (std::exception& e) {
    4153 | +                error = strprintf(_("Failed to create new wallet '%s'. Error: %s"), wallet_name, e.what());
    4154 | +                return false;
    4155 | +            }
    


    ryanofsky commented at 5:40 PM on November 5, 2026:

    In commit "wallet: migration, handle exceptions during wallet creation" (f8602f4b5ee01953404cac21119187da9ca1d588)

    Could the commit message describe the actual change in behavior? Through RPC the exception is already returned as an error, so the difference is what's left on disk. Maybe something like:

    If creating the watch-only or solvables wallet throws, the migration is now rolled back like other migration failures: the partially created wallets are deleted and the original wallet is restored from the backup. Previously the exception skipped this cleanup, so the user had to restore the backup and delete the partially created wallets manually.
    

    Also, just to confirm: as far as I know nobody has reported hitting this, and it can only happen in rare cases like a database write failure while importing descriptors into the new wallet. Is that right?


    furszy commented at 9:01 PM on November 10, 2026:

    Sure, commit message squashed there. Thanks!. And yeah, no one reported this that I know.

  73. in src/wallet/wallet.cpp:3874 in b9486540d7
    3873 | +    TryCreateDirectories(dst_wallet_dir);
    3874 | +    fs::copy_file(tmp_db, dst_wallet_dir / "wallet.dat", fs::copy_options::none, err_db);
    3875 | +    if (err_db) {
    3876 | +        return fail(strprintf(_("Error: Wallet db cannot be updated. Path: %s, Error: %s."), fs::PathToString(dst_wallet_dir), err_db.message()));
    3877 | +    }
    3878 | +    remove_tmp();
    


    ryanofsky commented at 5:41 PM on November 5, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0)

    Similar to the comment about the non-writable wallet test, it would be nice to fold the commit "test: migrate wallet located on a different filesystem" (0da9ec4f6b3073bbb62442863e5ba2de75762771) into this one, since it tests the cross-filesystem case of this move. If you'd rather keep them separate, it would help to mention each commit in the other's commit message.


    ryanofsky commented at 5:32 PM on November 16, 2026:

    re: #34193 (review)

    Resolving this: with the rename there is no longer a cross-filesystem copy, and https://github.com/bitcoin/bitcoin/pull/34193/commits/4b5bd462fad9d246c79e9dae7255d12fd6baa1ea now checks that the temporary database created next to a wallet on another filesystem is cleaned up, so keeping it as a separate commit makes sense.

  74. in src/wallet/wallet.cpp:3830 in 038d663391
    3840 | +        }
    3841 | +        return true;
    3842 | +    });
    3843 | +    if (!written) {
    3844 | +        fs::remove(new_db->Filename());
    3845 | +        assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    


    ryanofsky commented at 5:41 PM on November 5, 2026:

    In commit "wallet: use RunWithinTxn within MigrateToSQlite" (038d663391621f14e2dcb08ce1a6d9296646689e)

    Using RunWithinTxn here is nice: it makes the write loop much easier to follow and puts the begin, write and commit failures in one place. But this commit is hard to review because it isn't a refactoring, it changes how failures are handled, and the next commit replaces that failure handling again. I think the simplest fix is to restructure the commits; otherwise there are a few problems to fix here.

    Suggested restructuring: keep only the walletdb.cpp/walletdb.h part in this commit, which is a real refactoring, and move the MigrateToSQLite change into the next commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0). That commit rewrites this block anyway, so its diff would then go directly from the old asserts to the new error returns, and the cleanup problems below would be covered by the comment on fail(). Commit message for this commit could be:

    wallet: add RunWithinTxn overload taking a DatabaseBatch
    
    Refactoring, no behavior change. Make the static RunWithinTxn helper a template so it works with both WalletBatch and DatabaseBatch, and add a WalletDatabase overload whose callback takes a DatabaseBatch. The next commit uses it in MigrateToSQLite to write the migrated records in one transaction and return an error if that fails.
    

    If you keep this commit as it is, these should be fixed:

    1. The database is no longer closed before its file is deleted, and only wallet.dat is deleted. Deleting the data file of an open database can leave wallet.dat-journal behind as a hot journal, and since the new database is created at the wallet's own path, SQLite could roll it back into a new wallet.dat created there later, for example when the migration is retried after restoring the backup.

    2. fs::remove is the throwing overload. If it throws (likely on Windows, which can't delete an open file), the exception skips the assert(false) that is meant to stop the node, and at this commit nothing in the migration catches it, so the RPC returns an error and the node keeps running.

    3. assert(false) normally means a programming bug, but here runtime errors (full disk, I/O error, corrupt database) reach it, which isn't obvious to readers.

    Something like this would fix all three:

    if (!written) {
        // Can be reached by runtime errors such as a full disk, an I/O error or a corrupt database.
        const std::vector<fs::path> files{new_db->Files()};
        new_db->Close();
        for (const fs::path& file : files) {
            std::error_code ec;
            fs::remove(file, ec);
        }
        assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    }
    
    1. The commit message should say this isn't a pure refactoring, and that the next commit replaces these asserts. For example:
    wallet: use RunWithinTxn within MigrateToSQLite
    
    Write the migrated records with RunWithinTxn so failures to begin, write or commit the transaction are handled in one place. The next commit uses this to return an error instead of asserting.
    
    This is a refactoring except on failure paths that still end in assert(false): the new database is now closed and deleted when the transaction can't be started or committed, not only when a write fails, and the failure is logged.
    

    furszy commented at 9:05 PM on November 10, 2026:

    Reworked it a bit, tried to get the best of both worlds and reduce the size of the largest commit instead of expanding it further. It should be hopefully better now.


    ryanofsky commented at 2:48 PM on November 12, 2026:

    re: #34193 (review)

    Reworked it a bit, tried to get the best of both worlds and reduce the size of the largest commit

    Thanks, this is much easier to follow now. The commit message says exactly what changes, and having Erase() close the database and remove all its files fixes the cleanup problems in one place.

  75. in src/wallet/wallet.cpp:3855 in b9486540d7 outdated
    3854 | +    // ######################################################################
    3855 | +    // At this point, the new database has all records.                     #
    3856 | +    // We can remove the old db file and move the new db inside the wallet  #
    3857 | +    // ######################################################################
    3858 | +    std::error_code err_db;
    3859 | +    fs::remove(origin_db_path, err_db);
    


    ryanofsky commented at 6:00 PM on November 5, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (b9486540d774f2e07ecce93af0637d6e685a93e0)

    This can corrupt the migrated wallet if a stale sqlite journal is in the wallet directory. The copy_file below puts a complete database at wallet.dat, and if a wallet.dat-journal from an earlier crashed sqlite write is already there (for example from a migration that crashed in an older version, after the user restored the backup manually), SQLite treats it as a hot journal for the new file and rolls it back into it when MakeDatabase reopens it. This happens after the original file is deleted. Master doesn't have this problem because it creates the database in place as an empty file, and SQLite ignores the journal for an empty file.

    I checked this with a Python sqlite3 script using the same locking mode as the wallet: 3 of 3 runs corrupted the copied database, twice as "database disk image is malformed" and once silently, passing integrity_check with different contents.

    It should be easy to fix by failing before the original is removed if the journal exists:

    // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
    
    // A journal left at the destination by an earlier crashed sqlite write would be
    // rolled back into the new database when it is opened, corrupting it.
    const fs::path dst_journal{fs::PathFromString(fs::PathToString(SQLiteDataFile(dst_wallet_dir)) + "-journal")};
    if (std::error_code ec; fs::exists(fs::symlink_status(dst_journal, ec))) {
        return fail(strprintf(_("Error: Unable to migrate wallet '%s' because a leftover database journal file exists at '%s'. Move it out of the wallet directory and try again."), GetName(), fs::PathToString(dst_journal)));
    }
    

    with the later dst_wallet_dir declaration removed. A test could be similar to test_unwritable_dir_failure: write a dummy wallet.dat-journal into the wallet directory, check that migratewallet fails with this error, and check the wallet is still BDB.


    furszy commented at 3:54 PM on November 11, 2026:

    Nice find! fixed + added coverage for it.


    ryanofsky commented at 2:48 PM on November 12, 2026:

    re: #34193 (review)

    Nice find! fixed + added coverage for it.

    Thanks, the fix and both tests look good. Deleting the leftover journal instead of returning an error as I suggested seems safe: the file at the destination is the BDB database being migrated, so the journal can't belong to it, and the database check covers the case where deleting it would be wrong. I left a separate comment about documenting this, and a possible simpler alternative.

  76. ryanofsky commented at 6:10 PM on November 5, 2026: contributor

    Code review 3ca388f099c6a161faa40bf8b91c5aa89cb5b11d. Thanks for the updates! This is very close and a clear improvement over master in most failure cases: writing all records before removing the original file, and rolling back on exceptions, both look good.

    I'd like to see the stale journal issue fixed before ACKing, since it is the one case where copying the new database into place can corrupt a wallet that master would migrate correctly. The fix should be small. The copy_file failure case and the commit message suggestions would also be good to address, but I wouldn't block on them.

  77. achow101 commented at 7:10 PM on November 5, 2026: member

    This is possibly orthogonal, but I just had the thought that maybe we can achieve some additional robustness in migration by first migrating to an in-memory sqlite database, and then only writing that out to disk when migration is successful. Then we may be able to sidestep the whole issue of needing to automatically restore the original legacy wallet file by not removing it until we are sure the new database is good.

  78. furszy commented at 8:00 PM on November 5, 2026: member

    This is possibly orthogonal, but I just had the thought that maybe we can achieve some additional robustness in migration by first migrating to an in-memory sqlite database, and then only writing that out to disk when migration is successful. Then we may be able to sidestep the whole issue of needing to automatically restore the original legacy wallet file by not removing it until we are sure the new database is good.

    See #34193 (comment) . I had a branch that was doing essentially that, never touching the real wallet up to the final rename at the very last moment. But finding it on my fork was hard.. probably should make an LLM search for it.

    Still, I think this PR contains some good changes that worth to get merged even if we move towards that direction.

  79. wallet: migration, unify watchonly and solvables wallets creation
    No need to repeat the exact same code twice.
    This will let us introduce new safety checks and improve error
    handling for both wallets without the risk of forgetting to
    update one of them.
    c178347171
  80. wallet: migration, handle exceptions during wallet creation
    If creating the watch-only or solvables wallet throws, the migration is
    now rolled back like other migration failures: the partially created
    wallets are deleted and the original wallet is restored from the backup.
    
    Previously the exception skipped this cleanup, so the user had to restore
    the backup and delete the partially created wallets manually.
    249639cce7
  81. furszy force-pushed on Nov 10, 2026
  82. DrahtBot added the label CI failed on Nov 10, 2026
  83. wallet: migration, restore backup if an exception is thrown
    If MigrateToSQLite or DoMigration throws, the exception previously skipped the
    failure handling at the end of MigrateLegacyToDescriptor. The RPC returned the
    exception message, and the user was left with a partially migrated wallet and
    had to restore the .legacy.bak backup and delete the new wallet files manually.
    
    Catch these exceptions so the failed migration is cleaned up and the original
    wallet is restored from the backup automatically, the same way as when
    DoMigration returns an error.
    10852e1318
  84. furszy force-pushed on Nov 11, 2026
  85. DrahtBot removed the label CI failed on Nov 11, 2026
  86. in src/wallet/wallet.cpp:3872 in da055ca4bc
    3890 | +    // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be
    3891 | +    // atomically replaced by a directory, the original db is erased first in that case.
    3892 | +    if (db_file == dst_wallet_dir) {
    3893 | +        if (auto res{m_database->Erase()}; !res) return fail(util::ErrorString(res));
    3894 | +    }
    3895 | +    if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) return fail(util::ErrorString(res));
    


    ryanofsky commented at 2:48 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    Following up on #34193 (review): with the rename, a failure here now leaves directory wallets untouched, which covers the common case. From reading the code, two narrower cases still need a manual restore from the .legacy.bak file:

    • For a plain-file wallet, the original is erased first, so if MoveDatabase then fails, fail() also deletes the new database and MigrateLegacyToDescriptor returns the error without restoring the backup.
    • If the rename succeeds but reopening fails, the Assert in MoveDatabase crashes the node. The close and reopen also open a new window: migration doesn't reserve the wallet name the way loading does, so a concurrent loadwallet for the same wallet could take the database's exclusive lock in between. The Ralph review reports this case too and pointed out the loadwallet race.

    Neither is a regression, so I don't think they need to block this, but it would be nice if failures after the original is erased or replaced went through the restore path added in "wallet: migration, restore backup if an exception is thrown", for example by returning an error from MoveDatabase instead of asserting and throwing from MigrateToSQLite in these cases.

    More generally, MigrateLegacyToDescriptor treats a false return from MigrateToSQLite as "the original is untouched" and skips the restore, while an exception gets the full rollback. That makes it easy for a future change to add a return false after the point of no return without noticing (the comment on the final cleanup is one place where this matters). It would be less fragile if the caller decided based on whether the original was replaced, for example with an output parameter set right after the move, instead of on how the failure was reported, or at least if MigrateToSQLite documented that it may only return false while the original is untouched.


    ryanofsky commented at 5:24 PM on November 16, 2026:

    re: #34193 (review)

    it would be nice if failures after the original is erased or replaced went through the restore path

    Thanks, this looks good. Failures after the original may be gone now throw and restore the backup, reopening returns an error instead of asserting, and the MigrateToSQLite documentation states the contract, so a future change is much less likely to get it wrong.

    The loadwallet window between the rename and the reopen is still there, but it needs someone to load the wallet while it is being migrated, so I don't think it needs more code here.

  87. in src/wallet/db.cpp:94 in 8a9c3af0eb
      87 | @@ -86,6 +88,26 @@ fs::path BDBDataFile(const fs::path& wallet_path)
      88 |      }
      89 |  }
      90 |  
      91 | +static bilingual_str FileError(const fs::path& path, const std::error_code& ec)
      92 | +{
      93 | +    bilingual_str error{strprintf(_("Error: Wallet db file cannot be modified. Path: %s, Error: %s."), fs::PathToString(path), ec.message())};
      94 | +    if (ec.value() == EACCES || ec.value() == EPERM || ec.value() == EROFS) {
    


    ryanofsky commented at 3:14 PM on November 12, 2026:

    In commit "wallet: fail migration gracefully on non-writable wallets" (93e0cd6051ae391f6dcaeb71a2e36f3660225739)

    This compares the raw error value with errno constants, but MSVC's std::filesystem reports Win32 error codes (access denied is 5, not EACCES), so the permission hint would be left out there, and a Win32 code could match an unrelated errno value. Comparing with std::errc works for both:

        if (ec == std::errc::permission_denied || ec == std::errc::operation_not_permitted || ec == std::errc::read_only_file_system) {
    

    The Ralph review flagged this too.


    ryanofsky commented at 5:31 PM on November 16, 2026:
  88. in src/wallet/db.h:206 in 8a9c3af0eb
     202 | @@ -199,6 +203,9 @@ std::vector<std::pair<fs::path, std::string>> ListDatabases(const fs::path& path
     203 |  void ReadDatabaseArgs(const ArgsManager& args, DatabaseOptions& options);
     204 |  std::unique_ptr<WalletDatabase> MakeDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
     205 |  
     206 | +/** Moves 'db' to the 'dst_path' folder and reloads it from the new location */
    


    ryanofsky commented at 4:20 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    It would help if this comment mentioned that the move is a rename, so dst_path has to be on the same filesystem as the database. That requirement is why MigrateToSQLite builds the temporary database next to the original, but nothing here says so. Maybe something like:

    /**
     * Move 'db' into the 'dst_path' directory by renaming its data file, and reopen it from there.
     * 'dst_path' must be on the same filesystem as the database. An existing data file at the
     * destination is replaced, and a leftover journal there is removed first. On failure, 'db'
     * is left closed.
     */
    

    ryanofsky commented at 5:31 PM on November 16, 2026:

    re: #34193 (review)

    Thanks, the doc comment is updated in https://github.com/bitcoin/bitcoin/pull/34193/commits/77e82fcc3d5baaadd5512ba58b3f677e5498ed17, including the case where the moved file can't be reopened.

  89. in src/wallet/wallet.cpp:3826 in 8a9c3af0eb outdated
    3827 | +    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
    3828 | +
    3829 | +    // Create a temporary database next to the original db file
    3830 | +    const std::string new_db_name = strprintf("%s_sqlite_%d.tmp", MigrationFilePrefix(*this), GetTime());
    3831 | +    const fs::path tmp_wallet_path = fs::path{db_file.parent_path()} / fs::PathFromString(new_db_name);
    3832 | +    if (std::error_code ec; fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {
    


    ryanofsky commented at 4:20 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    Note: I first thought this check was redundant with opts.require_create, but MakeDatabase only rejects a path that already contains a database, and would create the new one inside an existing directory or symlink. This check is what lets the cleanup below assume the directory only holds the new database files. If you want, a short comment could save the next reader the same question:

        // Refuse any existing path, not just an existing database (all that require_create checks), so cleanup only deletes files this function created.
        if (std::error_code ec; fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {
    

    ryanofsky commented at 5:31 PM on November 16, 2026:
  90. in src/wallet/wallet.cpp:3875 in 8a9c3af0eb
    3893 | +        if (auto res{m_database->Erase()}; !res) return fail(util::ErrorString(res));
    3894 | +    }
    3895 | +    if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) return fail(util::ErrorString(res));
    3896 | +    m_database = std::move(new_db);
    3897 | +    std::error_code ec;
    3898 | +    fs::remove(tmp_wallet_path, ec); // Empty after the move
    


    ryanofsky commented at 4:20 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    I don't think this error should be ignored. The temporary directory only held the new database files, and the data file was just moved out, so if it can't be removed, something unexpected happened, like the database not being closed cleanly and leaving a journal behind. Migration has had enough subtle bugs that it seems better to stop and report anything unexpected than to continue silently. Since the original has already been replaced at this point, this needs to throw rather than return false: an exception goes through the restore path, while a false return is treated as "nothing changed" (see the earlier comment). The rollback deletes m_database's files, so the order matters too, and a comment on the assignment would keep it from being moved later:

        // Point m_database at the new database as soon as it replaces the original. If anything fails after
        // this, the caller's rollback deletes m_database's files before restoring the backup, so it must
        // name the files that are now at the wallet location.
        m_database = std::move(new_db);
        // The temporary directory only held the new database files, which were just moved out, so it should be empty.
        // If it can't be removed, something unexpected happened, so stop and let the caller restore the backup.
        std::error_code ec;
        if (!fs::remove(tmp_wallet_path, ec)) {
            throw std::runtime_error(strprintf("Unable to remove temporary directory %s after moving the new database: %s", fs::PathToString(tmp_wallet_path), ec ? ec.message() : "it no longer exists"));
        }
    

    ryanofsky commented at 5:32 PM on November 16, 2026:

    re: #34193 (review)

    Thanks, in https://github.com/bitcoin/bitcoin/pull/34193/commits/77e82fcc3d5baaadd5512ba58b3f677e5498ed17 this now throws so the backup is restored, and the comment on the m_database assignment explains the order.

  91. in src/wallet/wallet.cpp:3799 in 93e0cd6051
    3798 | -    fs::remove(db_path);
    3799 | +    // Close this database and erase its files
    3800 | +    if (auto res{m_database->Erase()}; !res) {
    3801 | +        error = util::ErrorString(res);
    3802 | +        return false;
    3803 | +    }
    


    ryanofsky commented at 4:21 PM on November 12, 2026:

    In commit "wallet: fail migration gracefully on non-writable wallets" (93e0cd6051ae391f6dcaeb71a2e36f3660225739)

    Nit: now that this commit comes after "restore backup if an exception is thrown", the commit message describes the old behavior. At that point the exception from fs::remove is caught, but the restore code then fails to delete the same file, so the RPC still returns a raw filesystem error. Maybe something like:

    If the wallet db file can't be deleted, for example because the wallet directory is read-only, migration fails with a raw filesystem error, because the restore code also fails to delete the file.
    
    Erase the db files using error codes instead, so migration stops before changing anything and returns an error naming the file and the reason, with a hint to fix the permissions when that is the cause.
    

    ryanofsky commented at 5:24 PM on November 16, 2026:

    re: #34193 (review)

    In commit "wallet: fail migration gracefully on non-writable wallets" (a625d2361bdf9f02b2335b8787234d4544054131)

    This still applies to the latest push, in case it was missed. Just a nit though.

  92. in src/wallet/wallet.cpp:3845 in da055ca4bc
    3851 | +        if (new_db) (void)new_db->Erase();
    3852 |          std::error_code ec;
    3853 | -        fs::remove(wallet_path, ec);
    3854 | +        fs::remove(tmp_wallet_path, ec);
    3855 |          return false;
    3856 |      };
    


    ryanofsky commented at 4:22 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    A few things about this lambda:

    • If MakeDatabase fails after SQLite has already created the file (when Open() throws after sqlite3_open_v2, or verification fails), it returns null and leaves wallet.dat in the temporary directory. Then fail() skips Erase(), and removing the directory fails because it isn't empty, so the temporary directory stays next to the wallet. The Ralph review points this out too.
    • It ignores cleanup errors, so if the temporary database can't be removed, the user isn't told and the files are left behind.
    • The name fail doesn't say what it does: it sets the error, then deletes the temporary database and directory.

    Something like this would cover all three. Since the directory didn't exist before, the files can be removed by name when there is no database object, and checking whether the directory is still there at the end catches every way the cleanup can fail:

    // Set the error, then delete the temporary database and its directory. The directory did not
    // exist before, so it only holds the new db files.
    const auto remove_tmp_and_fail = [&](bilingual_str err) {
        error = std::move(err);
        // Errors from the individual removals are ignored here, because the check below reports
        // any failure to clean up by looking for the temporary directory.
        std::error_code ec;
        if (new_db) {
            (void)new_db->Erase();
        } else {
            const fs::path data_file{SQLiteDataFile(tmp_wallet_path)};
            fs::remove(data_file, ec);
            fs::remove(fs::PathFromString(fs::PathToString(data_file) + "-journal"), ec);
        }
        fs::remove(tmp_wallet_path, ec);
        if (fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {
            error += Untranslated(" ") + strprintf(_("The temporary database at %s could not be removed."), fs::PathToString(tmp_wallet_path));
        }
        return false;
    };
    

    ryanofsky commented at 5:31 PM on November 16, 2026:

    re: #34193 (review)

    In commit "wallet: migration, make sqlite creation robust against failures" (77e82fcc3d5baaadd5512ba58b3f677e5498ed17)

    Thanks, latest update covers all three concerns, even though it uses directory iteration instead of CWallet:::Erase, so carries some of the risk of the banned fs::remove_all. But deleting whatever is in the temporary directory is simpler than removing the files by name, and the check that the directory didn't exist before makes it safer.

    One thing I got wrong in my suggestion above is the final check. Checking whether the directory still exists after removing it is unnecessary and slightly worse than checking the error from fs::remove. If any file is left inside, removing the directory fails with "Directory not empty", so its error already reports every way the cleanup can fail. If the directory was never created, fs::remove returns false with no error. Meanwhile fs::exists(fs::symlink_status(...)) returns false when lstat fails for another reason (like permission denied), so it can report a successful cleanup when it couldn't tell. This would be simpler:

    fs::remove(tmp_wallet_path, ec);
    if (ec) {
        error += Untranslated(" ") + strprintf(_("The temporary database at %s could not be removed."), fs::PathToString(tmp_wallet_path));
    }
    
  93. in src/wallet/db.cpp:204 in da055ca4bc
     199 | +        if (ec) return util::Error{FileError(leftover, ec)};
     200 | +    }
     201 | +
     202 | +    fs::create_directories(dst_path, ec);
     203 | +    if (!ec) fs::rename(wallet_file, dst_file, ec);
     204 | +    if (ec) return util::Error{FileError(dst_file, ec)};
    


    ryanofsky commented at 4:23 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    These two operations share one error message that only names the destination file, so the error doesn't say whether creating the directory or the rename failed. For a rename failure it can also point at the wrong place: the cause may be on the source side (the temporary directory) rather than the destination, but the message says the destination file "cannot be modified", and the permission hint suggests fixing that path. It would be clearer to report each operation separately, with both paths for the rename:

    fs::create_directories(dst_path, ec);
    if (ec) return util::Error{strprintf(_("Error: Unable to create wallet directory %s: %s."), fs::PathToString(dst_path), ec.message())};
    fs::rename(wallet_file, dst_file, ec);
    if (ec) return util::Error{strprintf(_("Error: Unable to move the new wallet db from %s to %s: %s."), fs::PathToString(wallet_file), fs::PathToString(dst_file), ec.message())};
    

    If the permission hint is wanted here too, FileError could take the message describing the failed operation instead of a single path.


    ryanofsky commented at 5:31 PM on November 16, 2026:

    re: #34193 (review)

    Thanks, the two failures have separate errors now, with both paths for the rename, in https://github.com/bitcoin/bitcoin/pull/34193/commits/77e82fcc3d5baaadd5512ba58b3f677e5498ed17.

  94. in src/wallet/wallet.cpp:3872 in da055ca4bc
    3870 | +    // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be
    3871 | +    // atomically replaced by a directory, the original db is erased first in that case.
    3872 | +    if (db_file == dst_wallet_dir) {
    3873 | +        if (auto res{m_database->Erase()}; !res) return fail(util::ErrorString(res));
    3874 | +    }
    3875 | +    if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) return fail(util::ErrorString(res));
    


    ryanofsky commented at 4:23 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    The commit message still describes an earlier version of this change: it doesn't say the temporary directory is now next to the original database (which is what makes the rename possible), it says the original files are removed before the new database is moved in, when for directory wallets the rename now replaces the original directly, and it doesn't mention the leftover journal cleanup. Maybe something like:

    Currently, MigrateToSQLite loads all BDB records into memory, deletes the original database, creates the sqlite database in its place and writes the records to it. If anything fails after the delete, the wallet is left partly in sqlite format with legacy records, and the user has to restore the backup manually.
    
    Instead, build the sqlite database in a temporary directory next to the original database file, and once all records are written, rename it into place. For wallet directories the rename replaces the original wallet.dat atomically, so a failure at any earlier point leaves the original untouched. A wallet that is a plain file becomes a wallet directory, which cannot replace the file atomically, so the original file is erased just before the move.
    
    Before the move, remove any leftover journal at the destination, since SQLite would roll it back into the new database when it is opened and corrupt it.
    

    ryanofsky commented at 5:24 PM on November 16, 2026:

    re: #34193 (review)

    In commit "wallet: migration, make sqlite creation robust against failures" (77e82fcc3d5baaadd5512ba58b3f677e5498ed17)

    The commit message still describes an earlier version of this change

    This still applies to the latest push. Here is the suggestion updated with the new behavior when the move fails:

    Currently, MigrateToSQLite loads all BDB records into memory, deletes the original database, creates the sqlite database in its place and writes the records to it. If anything fails after the delete, the wallet is left partly in sqlite format with legacy records, and the user has to restore the backup manually.
    
    Instead, build the sqlite database in a temporary directory next to the original database file, and once all records are written, rename it into place. For wallet directories the rename replaces the original wallet.dat atomically, so a failure at any earlier point leaves the original untouched. A wallet that is a plain file becomes a wallet directory, which cannot replace the file atomically, so the original file is erased just before the move. Failures from that point on throw, so the caller restores the backup.
    
    Before the move, remove any leftover journal at the destination, since SQLite would roll it back into the new database when it is opened and corrupt it.
    
  95. in src/wallet/wallet.cpp:3821 in da055ca4bc
    3819 | +    // Close this database. It is replaced once the new one is fully built
    3820 | +    const fs::path db_file = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_database->Filename()));
    3821 | +    m_database->Close();
    3822 | +
    3823 | +    // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories
    3824 | +    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
    


    ryanofsky commented at 4:23 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    Nit: renaming wallet_path to dst_wallet_dir is a nice improvement, but moving the declaration up here makes the diff harder to read, since it isn't used until the move at the end. It could stay where wallet_path was, just before // Make new DB, with its original comment, so the diff only shows the rename:

    // Generate the path for the location of the migrated wallet
    // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
    
    // Make new DB
    

  96. in src/wallet/wallet.cpp:3830 in 2f7e525ac7
    3840 | +        }
    3841 | +        return true;
    3842 | +    });
    3843 | +    if (!written) {
    3844 | +        fail(strprintf(_("Error: Unable to write records into the new database for wallet '%s'"), GetName()));
    3845 | +        assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    


    ryanofsky commented at 4:24 PM on November 12, 2026:

    In commit "wallet: use RunWithinTxn within MigrateToSQLite" (2f7e525ac75c0417a5d83f1ebeba21f85bdc478a)

    In this commit fail() is only called once, right before assert(false), so the error message it sets is never shown, and the lambda hides what that call actually does: delete the new database and try to remove the wallet directory, ignoring errors. It would be clearer to do the cleanup inline here and add the lambda in "wallet: migration, make sqlite creation robust against failures", where it has several callers and the error is returned to the user:

    if (!written) {
        // Best-effort cleanup before stopping. Errors are ignored because the assert below ends the process anyway.
        (void)new_db->Erase();
        std::error_code ec;
        fs::remove(wallet_path, ec);
        assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    }
    

  97. in src/wallet/db.cpp:190 in 8a9c3af0eb
     185 | +    db->Close();
     186 | +
     187 | +    const fs::path dst_file{dst_path / fs::path{wallet_file.filename()}};
     188 | +
     189 | +    // Any other file of this db at the destination (e.g. a hot journal) is a leftover of an interrupted write to an
     190 | +    // earlier db there. Erase it, as the moved db would apply it when opened, corrupting it. Never erase a database.
    


    ryanofsky commented at 5:01 PM on November 12, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (da055ca4bc59df70d034e7f528165f4d13ed06bf)

    When I first read this I thought the loop only removed files this code had created, but it deletes files it finds at the destination that shouldn't normally be there. Maybe the comment could say so more directly:

        // Check for destination files that should never be present normally, but could exist if an outside process created them
        // or an earlier migration was interrupted. Return an error if they look like wallet databases, otherwise delete them. In
        // particular, delete a leftover journal, which SQLite would roll back into the moved database when opening it, corrupting it.
    

    Alternately, I think i would be safer and simpler to return an error for any file found here, dropping the database checks. As far as I can tell, failures that are reported (like running out of disk space) already clean up their journal, so a leftover one can only come from the process dying during an earlier migration followed by a manual restore, or from something outside Bitcoin Core. That's rare, and a user who hits it has already been recovering by hand, so an error naming the file would be easy to act on. Current approach seems ok though.


    ryanofsky commented at 5:32 PM on November 16, 2026:

    re: #34193 (review)

    In commit "wallet: migration, make sqlite creation robust against failures" (77e82fcc3d5baaadd5512ba58b3f677e5498ed17)

    Thanks, the reworded comment makes it clear these files weren't created by this code.

    I'd still lean toward the simpler alternative from my comment above, though: return an error for any file found here instead of checking whether it looks like a database and deleting it otherwise. It's less code, it never deletes a file this code didn't create, and since failures here now restore the backup, a user who hits it gets an error naming the file and can move it out of the way and try again. Something like:

    // Other files of this db should never be present at the destination, but an interrupted earlier migration or an
    // outside process may leave them there. A leftover journal, for example, would be rolled back into the moved db
    // by SQLite, corrupting it. Return an error rather than guessing whether a file is safe to delete.
    std::error_code ec;
    for (const fs::path& file : files) {
        const fs::path leftover{dst_path / fs::path{file.filename()}};
        if (leftover == dst_file) continue; // Replaced atomically by the rename below
        if (fs::symlink_status(leftover, ec).type() != fs::file_type::not_found) {
            return util::Error{strprintf(_("Error: Unable to move the wallet db, unexpected file %s found at the destination. Move it elsewhere and try again."), fs::PathToString(leftover))};
        }
    }
    

    Current approach is fine too if you prefer it.

  98. ryanofsky approved
  99. ryanofsky commented at 5:08 PM on November 12, 2026: contributor

    Code review ACK 8a9c3af0eb7df50f38ca511491d3d0d1e47f7fb7. This is a clear improvement over master, which deletes the original database before writing the new one. Now a directory wallet stays untouched until a single rename replaces it, exceptions roll back to the backup, and the stale journal case is handled.

    Thanks for the quick and thorough update! None of the inline comments need to block this, but the ones I think matter most are:

    The Ralph review was also helpful here and caught a few of the smaller issues noted inline.

  100. wallet: fail migration gracefully on non-writable wallets
    Currently, attempting a wallet migration when the database
    directory or file is not writable results in a filesystem
    exception that abruptly aborts the process, skipping the
    post-failure cleanup logic and returning a not particularly
    helpful error message.
    a625d2361b
  101. wallet: use RunWithinTxn within MigrateToSQLite
    Write the migrated records with RunWithinTxn so failures to begin,
    write or commit the transaction are handled in one place. A later
    commit uses this to return an error instead of asserting.
    
    This is a refactoring except on failure paths that still end in
    assert(false): the new database is now closed and deleted when the
    transaction can't be started or committed, not only when a write
    fails, and the failure is properly logged.
    72161d494e
  102. wallet: migration, add MigrationFilePrefix() helper
    Move the code that derives the backup file name prefix into a
    helper, so the next commit can reuse it to name the temporary
    database migration will build, leaving the original database
    untouched until the new one has all the records.
    
    The helpers are moved above MigrateToSQLite(), which will call it.
    
    No behavior change.
    6ae15e236e
  103. wallet: migration, make sqlite creation robust against failures
    Currently, MigrateToSQLite loads all BDB records into memory,
    then deletes the original database just to create the sqlite
    db in the same place, and finally writes all cached records
    to it.
    
    This is not really the best because it removes the original db
    before making sure the sqlite one is fully built. If creation
    fails, the wallet ends up partly in sqlite format with legacy
    records, and the user has to restore from a backup manually.
    
    This fixes all that by creating the sqlite db in a temporary
    directory first. Then, the original BDB files are removed only
    once the sqlite db is fully constructed, and the new db is
    moved into the original location.
    
    The result is that no user manual intervention is needed if
    MigrateToSQLite fails as the original db stays untouched.
    77e82fcc3d
  104. test: migrate wallet located on a different filesystem 4b5bd462fa
  105. test: migrate a wallet with a leftover journal at its location
    Covers the leftover file removal added in "wallet: migration, make
    sqlite creation robust against failures". Without it, SQLite rolls
    the stale journal back into the migrated db once it is moved into
    place, writing pages of an unrelated database into it.
    e2e397edae
  106. furszy force-pushed on Nov 13, 2026
  107. in src/wallet/wallet.cpp:3883 in e2e397edae
    3899 | +    // atomically replaced by a directory, the original db is erased first in that case.
    3900 | +    if (db_file == dst_wallet_dir) {
    3901 | +        if (auto res{m_database->Erase()}; !res) return remove_tmp_and_fail(util::ErrorString(res));
    3902 | +    }
    3903 | +
    3904 | +    // From here on, the original db may be gone. Failures throw, so the caller restores the backup.
    


    ryanofsky commented at 6:17 PM on November 16, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (77e82fcc3d5baaadd5512ba58b3f677e5498ed17)

    Since MigrateLegacyToDescriptor restores the backup only when MigrateToSQLite throws, it would be good if the comment here warned more directly that nothing after this point may return false. Something like:

    // From here on, the original db may have been erased or replaced. Never return false after this point: the caller
    // treats false as "the original db is unchanged" and skips restoring the backup. Throw instead, so the caller
    // deletes the wallet files and restores the backup.
    

    Might also suggest a comment and assert clarifying why the Erase() call is safe:

    // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be
    // atomically replaced by a directory, the original db is erased first in that case. The original db is a single
    // file, so if Erase() fails nothing was removed, and returning false is still correct.
    if (db_file == dst_wallet_dir) {
        Assert(m_database->Files().size() == 1);
        if (auto res{m_database->Erase()}; !res) return remove_tmp_and_fail(util::ErrorString(res));
    }
    

    Returning false after the Erase() fails is only right because the legacy database is a single file. If Erase() could remove some files and then fail, the backup wouldn't be restored. Throwing wouldn't help in that case either: the rollback removes the same files with the throwing fs::remove, which would probably fail again, outside the try block. So it seems best to document the assumption, and the assert would catch it if Files() ever returned more than one file here.

  108. in src/wallet/wallet.h:1053 in e2e397edae
    1050 |       * A backup is not created.
    1051 | -     * May crash if something unexpected happens in the filesystem.
    1052 | +     * Returns false, with the original database untouched, if the new one can't be built. Once the original
    1053 | +     * database may have been erased or replaced, failures throw instead, so the caller restores the backup.
    1054 |       */
    1055 |      bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
    


    ryanofsky commented at 6:17 PM on November 16, 2026:

    In commit "wallet: migration, make sqlite creation robust against failures" (77e82fcc3d5baaadd5512ba58b3f677e5498ed17)

    Thanks for documenting this. Besides a clearer warning in MigrateToSQLite, since a stray return false after the original is replaced would silently skip the restore, it might be worth making the contract part of the return type, for example:

    enum class MigrateDbResult {
        SUCCESS,          //!< The wallet now uses the new SQLite database
        FAILED_UNCHANGED, //!< The new database couldn't be built and the original is untouched, so no restore is needed
    };
    

    Then return false doesn't compile, and each early return has to say that the original is unchanged, which makes a mistake after the point of no return easier to spot in review. Not needed for this PR though.

  109. ryanofsky approved
  110. ryanofsky commented at 6:40 PM on November 16, 2026: contributor

    Code review ACK e2e397edaee1e722e670488b6f324fb3698770c4. This is a clear improvement over master, which deletes the original database before writing the new one and asserts if anything fails after that. Now the new database is fully built before it replaces the original, and failures after that point restore the backup instead of leaving the wallet for the user to restore by hand.

    Thanks for taking the suggestions! The return false vs. throw contract is now documented and followed, which was my main concern. None of the remaining comments need to block this, but the ones I think matter most are:

  111. w0xlt commented at 8:30 AM on November 17, 2026: contributor

    ACK e2e397edaee1e722e670488b6f324fb3698770c4

    For directory wallets, if MoveDatabase fails before the rename, the original is still intact, but the PR code throws and the caller deletes it and restores it from the backup. The file was never touched, so the delete-and-restore is unnecessary, and if the restore fails the user has to restore the backup by hand.

    The error could say whether the rename happened (e.g. util::Expected with a bool dst_replaced), so MigrateToSQLite could return false in that case.

    But it is fine as a follow-up.

  112. DrahtBot added the label Needs rebase on Nov 20, 2026
  113. DrahtBot commented at 10:59 PM on November 20, 2026: contributor

    <!--cf906140f33d8803c4a75a2196329ecb-->

    🐙 This pull request conflicts with the target branch and needs rebase.


github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-11-23 12:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me