Merge bitcoin/bitcoin#34193: wallet: make migration more robust against failures
What changed, and why it matters
This Bitcoin Core update hardens the wallet migration tool so that if something goes wrong while converting an old wallet to the new SQLite format, the original wallet is preserved or restored automatically instead of being left in a broken state. It also prevents migration from accidentally corrupting the new wallet when leftover database files are present. There is no evidence this is an actively exploitable attack; it is a defensive robustness fix.
Apply the patch. It is a defensive hardening improvement for the wallet migration path. Users planning to migrate legacy wallets should run a version that includes this fix to reduce the risk of wallet corruption or loss if migration fails.
Security signals we found
Original migration code deleted the legacy BDB file before the new SQLite database was fully created, risking data loss on failure
New migration builds SQLite database in a temporary path and atomically moves it only after successful record write
Leftover SQLite journal at destination is now rejected to prevent rollback corruption of the migrated database
Read-only wallet directory now fails gracefully with a clear error instead of throwing an unhandled filesystem exception
Failures after the original database may have been erased now throw so the caller restores the backup
Common wallet creation helper catches exceptions and returns false so backup restoration can proceed
Evidence from the diff
The commit refactors MigrateToSQLite and related migration code so that the new SQLite database is built in a temporary directory and only moved into place after all records are written successfully. It adds WalletDatabase::Erase() and MoveDatabase() helpers, detects leftover journals or other unexpected files at the destination, handles read-only directories and other filesystem errors gracefully, and wraps watchonly/solvables wallet creation in a common try/catch so failures restore the backup. The functional tests add coverage for non-writable directories, stale journals, journal-named files, and cross-filesystem wallets.
Changed components
src/wallet/db.cppsrc/wallet/db.hsrc/wallet/migration.cppsrc/wallet/wallet.hsrc/wallet/walletdb.cppsrc/wallet/walletdb.htest/functional/wallet_migration.pyInspect captured patch +335 / −111
### src/wallet/db.cpp
@@ -7,6 +7,7 @@
#include <common/args.h>
#include <util/fs.h>
#include <util/log.h>
+#include <util/translation.h>
#include <wallet/db.h>
#include <algorithm>
@@ -86,6 +87,26 @@ fs::path BDBDataFile(const fs::path& wallet_path)
}
}
+static bilingual_str FileError(const fs::path& path, const std::error_code& ec)
+{
+ bilingual_str error{strprintf(_("Error: Wallet db file cannot be modified. Path: %s, Error: %s."), fs::PathToString(path), ec.message())};
+ if (ec == std::errc::permission_denied || ec == std::errc::operation_not_permitted || ec == std::errc::read_only_file_system) {
+ error += Untranslated(" ") + _("Adjust directory or file permissions and try again.");
+ }
+ return error;
+}
+
+util::Result<void> WalletDatabase::Erase()
+{
+ Close();
+ for (const fs::path& file : Files()) {
+ std::error_code ec;
+ fs::remove(file, ec);
+ if (ec) return util::Error{FileError(file, ec)};
+ }
+ return {};
+}
+
fs::path SQLiteDataFile(const fs::path& path)
{
return path / "wallet.dat";
@@ -156,4 +177,43 @@ void ReadDatabaseArgs(const ArgsManager& args, DatabaseOptions& options)
options.use_unsafe_sync = args.GetBoolArg("-unsafesqlitesync", options.use_unsafe_sync);
}
+util::Result<void> MoveDatabase(std::unique_ptr<WalletDatabase>& db, const fs::path& dst_path, DatabaseOptions& opts)
+{
+ const fs::path wallet_file{fs::PathFromString(db->Filename())};
+ const std::vector<fs::path> files{db->Files()};
+ db->Close();
+
+ const fs::path dst_file{dst_path / fs::path{wallet_file.filename()}};
+
+ // 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))};
+ }
+ }
+
+ 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())};
+
+ // Reload db connection
+ DatabaseStatus db_status;
+ opts.require_create = false;
+ opts.require_existing = true;
+ bilingual_str error;
+ std::unique_ptr<WalletDatabase> moved_db{MakeDatabase(dst_path, opts, db_status, error)};
+ if (!moved_db) {
+ fs::remove(dst_file, ec); // Don't leave a db that can't be opened at the destination
+ return util::Error{error};
+ }
+ db = std::move(moved_db);
+ return {};
+}
+
} // namespace wallet
### src/wallet/db.h
@@ -10,6 +10,7 @@
#include <streams.h>
#include <support/allocators/secure.h>
#include <util/fs.h>
+#include <util/result.h>
#include <memory>
#include <optional>
@@ -158,6 +159,9 @@ class WalletDatabase
/** Make a DatabaseBatch connected to this database */
virtual std::unique_ptr<DatabaseBatch> MakeBatch() = 0;
+
+ /** Close the database and erase all its files */
+ util::Result<void> Erase();
};
enum class DatabaseFormat {
@@ -199,6 +203,15 @@ std::vector<std::pair<fs::path, std::string>> ListDatabases(const fs::path& path
void ReadDatabaseArgs(const ArgsManager& args, DatabaseOptions& options);
std::unique_ptr<WalletDatabase> MakeDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
+/**
+ * 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. If another file of the db, such as a leftover journal, is already
+ * at the destination, nothing is moved and an error is returned.
+ * On failure, 'db' is left closed, and a moved data file that can't be reopened is erased.
+ */
+util::Result<void> MoveDatabase(std::unique_ptr<WalletDatabase>& db, const fs::path& dst_path, DatabaseOptions& opts);
+
fs::path BDBDataFile(const fs::path& path);
fs::path SQLiteDataFile(const fs::path& path);
bool IsBDBFile(const fs::path& path);
### src/wallet/migration.cpp
@@ -40,6 +40,27 @@ void CWallet::SetupLegacyDataSPKM()
AddScriptPubKeyMan(id, std::move(spk_manager));
}
+// Returns wallet prefix for migration.
+// Used to name the backup file and newly created wallets.
+// E.g. a watch-only wallet is named "<prefix>_watchonly".
+static std::string MigrationPrefixName(CWallet& wallet)
+{
+ const std::string& name{wallet.GetName()};
+ 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);
@@ -78,39 +99,88 @@ bool CWallet::MigrateToSQLite(bilingual_str& error)
return false;
}
- // Close this database and delete the file
- fs::path db_path = fs::PathFromString(m_database->Filename());
+ // Close this database. It stays untouched until the new one is fully built
+ const fs::path db_file = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_database->Filename()));
m_database->Close();
- fs::remove(db_path);
+
+ // Create a temporary database next to the original db file
+ const std::string new_db_name = strprintf("%s_sqlite_%d.tmp", MigrationFilePrefix(*this), GetTime());
+ const fs::path tmp_wallet_path = fs::path{db_file.parent_path()} / fs::PathFromString(new_db_name);
+ // 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))) {
+ error = strprintf(_("Error: Unable to create the new database for wallet '%s'. Temporary path '%s' already exists."), GetName(), fs::PathToString(tmp_wallet_path));
+ return false;
+ }
// 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 wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
+ const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
// Make new DB
DatabaseOptions opts;
opts.require_create = true;
opts.require_format = DatabaseFormat::SQLITE;
DatabaseStatus db_status;
- std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);
- assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.
- m_database.reset();
- m_database = std::move(new_db);
+ std::unique_ptr<WalletDatabase> new_db = MakeDatabase(tmp_wallet_path, opts, db_status, error);
+
+ // Set the error, then delete the temporary database and its directory. The directory did not exist before, so it
+ // only holds files of the new db, including any left by a failed creation.
+ const auto remove_tmp_and_fail = [&](bilingual_str err) {
+ error = std::move(err);
+ new_db.reset(); // Close the db before deleting its files
+ std::error_code ec;
+ for (auto it{fs::directory_iterator(tmp_wallet_path, ec)}; !ec && it != fs::directory_iterator(); it.increment(ec)) {
+ fs::remove(it->path(), ec);
+ }
+ 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));
+ }
+ return false;
+ };
+
+ if (!new_db) {
+ return remove_tmp_and_fail(strprintf(_("Error: Unable to create the new database for wallet '%s'."), GetName()) + Untranslated(" ") + error);
+ }
// Write existing records into the new DB
- batch = m_database->MakeBatch();
- bool began = batch->TxnBegin();
- 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.
- for (const auto& [key, value] : records) {
- if (!batch->Write(std::span{key}, std::span{value})) {
- batch->TxnAbort();
- m_database->Close();
- fs::remove(m_database->Filename());
- AssertUnreachable(); // 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.
- }
- }
- bool committed = batch->TxnCommit();
- 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.
+ const bool written = RunWithinTxn(*new_db, "migration: write records to new db", [&records](DatabaseBatch& in_batch) {
+ for (const auto& [key, value] : records) {
+ if (!in_batch.Write(std::span{key}, std::span{value})) return false;
+ }
+ return true;
+ });
+ if (!written) {
+ return remove_tmp_and_fail(strprintf(_("Error: Unable to write records into the new database for wallet '%s'"), GetName()));
+ }
+
+ // ######################################################################
+ // At this point, the new database has all records. #
+ // Move it into the wallet location, replacing the original db file. #
+ // ######################################################################
+
+ // 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) {
+ Assume(m_database->Files().size() == 1);
+ if (auto res{m_database->Erase()}; !res) return remove_tmp_and_fail(util::ErrorString(res));
+ }
+
+ // From here on, the original db may have been erased or replaced. Never return false after this point, as the
+ // caller would skip the restore. Throw instead, so it deletes the wallet files and restores the backup.
+ if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) {
+ remove_tmp_and_fail(util::ErrorString(res));
+ throw std::runtime_error(error.original);
+ }
+ // The caller's rollback deletes m_database's files, so point it at the new db as soon as it replaces the original
+ m_database = std::move(new_db);
+ // The temporary dir only held the new db files, which were just moved out. If it can't be removed, something
+ // unexpected happened, so stop and let the caller restore the backup.
+ if (std::error_code ec; !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"));
+ }
return true;
}
@@ -355,15 +425,6 @@ util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch,
return {}; // all good
}
-// Returns wallet prefix for migration.
-// Used to name the backup file and newly created wallets.
-// E.g. a watch-only wallet is named "<prefix>_watchonly".
-static std::string MigrationPrefixName(CWallet& wallet)
-{
- const std::string& name{wallet.GetName()};
- return name.empty() ? "default_wallet" : name;
-}
-
bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error, MigrationResult& res, const bool load_on_startup = true) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
{
AssertLockHeld(wallet.cs_wallet);
@@ -390,85 +451,63 @@ bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error,
if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
options.create_flags |= WALLET_FLAG_KEY_ORIGIN_METADATA;
}
- if (data->watch_descs.size() > 0) {
- wallet.WalletLogPrintf("Making a new watchonly wallet containing the watched scripts");
- DatabaseStatus status;
- std::vector<bilingual_str> warnings;
- std::string wallet_name = MigrationPrefixName(wallet) + "_watchonly";
- std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
- if (!database) {
- error = strprintf(_("Wallet file creation failed: %s"), error);
- return false;
- }
+ const auto fn_create_wallet = [&context, &options, &empty_context, load_on_startup](const std::string& wallet_name,
+ const std::vector<std::pair<std::string, int64_t>>& descs_to_import,
+ std::shared_ptr<CWallet>& out_wallet, bilingual_str& error) {
+ try {
+ DatabaseStatus status;
+ std::vector<bilingual_str> warnings;
+ std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
+ if (!database) {
+ error = strprintf(_("Wallet file creation failed: %s"), error);
+ return false;
+ }
- data->watchonly_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);
- if (!data->watchonly_wallet) {
- error = _("Error: Failed to create new watchonly wallet");
- return false;
- }
- res.watchonly_wallet = data->watchonly_wallet;
- LOCK(data->watchonly_wallet->cs_wallet);
-
- // Parse the descriptors and add them to the new wallet
- for (const auto& [desc_str, creation_time] : data->watch_descs) {
- // Parse the descriptor
- FlatSigningProvider keys;
- std::string parse_err;
- std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
- // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.
- assert(descs.size() == 1);
- assert(!descs.at(0)->IsRange());
-
- // Add to the wallet
- WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
- if (auto spkm_res = data->watchonly_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
- throw std::runtime_error(util::ErrorString(spkm_res).original);
+ out_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);
+ if (!out_wallet) {
+ error = strprintf(_("Error: Failed to create new wallet '%s'"), wallet_name);
+ return false;
+ }
+ LOCK(out_wallet->cs_wallet);
+
+ // Parse the descriptors and add them to the new wallet
+ for (const auto& [desc_str, creation_time] : descs_to_import) {
+ // Parse the descriptor
+ FlatSigningProvider keys;
+ std::string parse_err;
+ std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
+ // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.
+ assert(descs.size() == 1);
+ assert(!descs.at(0)->IsRange());
+
+ // Add to the wallet
+ WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
+ if (auto spkm_res = out_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
+ throw std::runtime_error(util::ErrorString(spkm_res).original);
+ }
}
+
+ // Add the wallet to settings
+ UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);
+ return true;
+ } catch (std::exception& e) {
+ error = strprintf(_("Failed to create new wallet '%s'. Error: %s"), wallet_name, e.what());
+ return false;
}
+ };
- // Add the wallet to settings
- UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);
+ if (data->watch_descs.size() > 0) {
+ wallet.WalletLogPrintf("Making a new watchonly wallet containing the watched scripts");
+ bool ret = fn_create_wallet(/*wallet_name=*/MigrationPrefixName(wallet) + "_watchonly", data->watch_descs, /*out_wallet=*/data->watchonly_wallet, error);
+ res.watchonly_wallet = data->watchonly_wallet; // always set just so it can be cleaned up later
+ if (!ret) return false;
}
if (data->solvable_descs.size() > 0) {
wallet.WalletLogPrintf("Making a new watchonly wallet containing the unwatched solvable scripts");
-
- DatabaseStatus status;
- std::vector<bilingual_str> warnings;
- std::string wallet_name = MigrationPrefixName(wallet) + "_solvables";
- std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
- if (!database) {
- error = strprintf(_("Wallet file creation failed: %s"), error);
- return false;
- }
-
- data->solvable_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);
- if (!data->solvable_wallet) {
- error = _("Error: Failed to create new watchonly wallet");
- return false;
- }
- res.solvables_wallet = data->solvable_wallet;
- LOCK(data->solvable_wallet->cs_wallet);
-
- // Parse the descriptors and add them to the new wallet
- for (const auto& [desc_str, creation_time] : data->solvable_descs) {
- // Parse the descriptor
- FlatSigningProvider keys;
- std::string parse_err;
- std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
- // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.
- assert(descs.size() == 1);
- assert(!descs.at(0)->IsRange());
-
- // Add to the wallet
- WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
- if (auto spkm_res = data->solvable_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
- throw std::runtime_error(util::ErrorString(spkm_res).original);
- }
- }
-
- // Add the wallet to settings
- UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);
+ bool ret = fn_create_wallet(/*wallet_name=*/MigrationPrefixName(wallet) + "_solvables", data->solvable_descs, /*out_wallet=*/data->solvable_wallet, error);
+ res.solvables_wallet = data->solvable_wallet; // always set just so it can be cleaned up later
+ if (!ret) return false;
}
}
@@ -551,11 +590,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);
@@ -579,7 +614,7 @@ util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet>
// migrating only watch-only scripts.
bool empty_local_wallet = false;
- {
+ try {
LOCK(local_wallet->cs_wallet);
// First change to using SQLite
if (!local_wallet->MigrateToSQLite(error)) return util::Error{error};
@@ -594,6 +629,8 @@ util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet>
local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
success = true;
}
+ } catch (const std::exception& e) {
+ error = Untranslated(strprintf("Migration failed: %s", e.what()));
}
// In case of loading failure, we need to remember the wallet files we have created to remove.
### src/wallet/wallet.h
@@ -1053,9 +1053,10 @@ class CWallet final : public WalletStorage, public interfaces::Chain::Notificati
util::Expected<CExtPubKey, WalletError> AddHDKey(const std::optional<CExtKey>& key);
/** Move all records from the BDB database to a new SQLite database for storage.
- * The original BDB file will be deleted and replaced with a new SQLite file.
+ * The new database is built in a temporary directory and then moved into place, replacing the original one.
* A backup is not created.
- * May crash if something unexpected happens in the filesystem.
+ * Returns false, with the original database untouched, if the new one can't be built. Once the original
+ * database may have been erased or replaced, failures throw instead, so the caller restores the backup.
*/
bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
### src/wallet/walletdb.cpp
@@ -1276,7 +1276,8 @@ DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
return result;
}
-static bool RunWithinTxn(WalletBatch& batch, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
+template <typename T>
+static bool RunWithinTxn(T& batch, std::string_view process_desc, const std::function<bool(T&)>& func)
{
if (!batch.TxnBegin()) {
LogDebug(BCLog::WALLETDB, "Error: cannot create db txn for %s\n", process_desc);
@@ -1305,6 +1306,12 @@ bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const
return RunWithinTxn(batch, process_desc, func);
}
+bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(DatabaseBatch&)>& func)
+{
+ const auto batch = database.MakeBatch();
+ return RunWithinTxn(*batch, process_desc, func);
+}
+
bool WalletBatch::WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent)
{
auto key{std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), std::string("used")))};
### src/wallet/walletdb.h
@@ -319,6 +319,7 @@ class WalletBatch
* @return true if the db txn executed successfully, false otherwise.
*/
bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func);
+bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(DatabaseBatch&)>& func);
bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
### test/functional/wallet_migration.py
@@ -6,10 +6,12 @@
from contextlib import suppress
from pathlib import Path
import json
-import os.path
+import os
import random
import shutil
+import stat
import struct
+import tempfile
import time
from decimal import Decimal
@@ -30,6 +32,7 @@
assert_greater_than,
assert_raises_rpc_error,
find_vout_for_address,
+ is_dir_writable,
sha256sum_file,
)
from test_framework.wallet_util import (
@@ -113,6 +116,11 @@ def check_address(self, wallet, addr, is_mine, is_change, label):
else:
assert_equal(addr_info['labels'], []),
+ def assert_no_tmp_db(self, path):
+ """Assert that no temporary migration database was left behind under 'path'"""
+ for _, dirs, files in os.walk(path):
+ assert not [f for f in dirs + files if "_sqlite_" in f and f.endswith(".tmp")]
+
def migrate_and_get_rpc(self, wallet_name, **kwargs):
# Since we may rescan on loading of a wallet, make sure that the best block
# is written before beginning migration
@@ -161,6 +169,7 @@ def migrate_and_get_rpc(self, wallet_name, **kwargs):
expected_backup_path = self.master_node.wallets_path / backup_filename
assert_equal(str(expected_backup_path), migrate_info['backup_path'])
assert {"name": backup_filename} not in self.master_node.listwalletdir()["wallets"]
+ self.assert_no_tmp_db(self.master_node.wallets_path)
# Open the wallet with sqlite and verify that the wallet has the last hardened cache flag
# set and the last hardened cache entries
@@ -183,6 +192,98 @@ def check_last_hardened(conn):
return migrate_info, wallet
+ def test_unwritable_dir_failure(self):
+ self.log.info("Test migration failure due to non-writable directory")
+ wallet_name = "bad_permissions"
+ wallet = self.create_legacy_wallet(wallet_name)
+ wallet.unloadwallet()
+ shutil.copytree(self.old_node.wallets_path / wallet_name, self.master_node.wallets_path / wallet_name, dirs_exist_ok=True)
+
+ # Change dir perms and migrate
+ wallet_path = self.master_node.wallets_path / wallet_name
+ original_dir_perms = wallet_path.stat().st_mode
+ wallet_path.chmod(original_dir_perms & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH))
+ if is_dir_writable(wallet_path):
+ self.log.warning("Skipping migration non-writable directory test: unable to enforce read-only permissions")
+ else:
+ assert_raises_rpc_error(-4, "Error: Unable to create the new database for wallet 'bad_permissions'.", self.master_node.migratewallet, wallet_name)
+ # Reset directory permissions
+ wallet_path.chmod(original_dir_perms)
+ self.assert_no_tmp_db(self.master_node.wallets_path)
+
+ # Check the wallet we tried to migrate is still BDB
+ self.assert_is_bdb(wallet_name)
+
+ def test_stale_journal(self):
+ self.log.info("Test migration fails if a leftover database journal is found at the wallet location")
+ try:
+ import sqlite3 # type: ignore[import]
+ except ImportError:
+ self.log.warning("Skipping stale journal test: sqlite3 module not available")
+ return
+ wallet_name = "stale_journal"
+ wallet = self.create_legacy_wallet(wallet_name)
+ wallet.unloadwallet()
+ wallet_path = self.master_node.wallets_path / wallet_name
+ shutil.copytree(self.old_node.wallets_path / wallet_name, wallet_path, dirs_exist_ok=True)
+ journal_path = wallet_path / "wallet.dat-journal"
+
+ # Leave the journal of an unrelated db at the wallet location, as a write interrupted by a crash would.
+ # Copying it in the middle of a transaction makes it "hot": SQLite rolls it back on the next open.
+ src_db = os.path.join(self.options.tmpdir, "unrelated.dat")
+ conn = sqlite3.connect(src_db, isolation_level=None)
+ conn.execute("CREATE TABLE t(v BLOB)")
+ conn.execute("BEGIN")
+ for _ in range(400):
+ conn.execute("INSERT INTO t VALUES (randomblob(200))")
+ conn.execute("COMMIT")
+ conn.execute("PRAGMA cache_size=2") # Make the next transaction write its changes to disk
+ conn.execute("BEGIN")
+ conn.execute("UPDATE t SET v = randomblob(200)")
+ shutil.copyfile(f"{src_db}-journal", journal_path)
+ conn.close()
+
+ # Migration must fail and keep the journal. Otherwise, SQLite rolls it back into the migrated wallet when opening
+ # it, and corrupts it.
+ assert_raises_rpc_error(-4, f"Migration failed: Error: Unable to move the wallet db, unexpected file {journal_path} found at the destination. Move it elsewhere and try again.", self.master_node.migratewallet, wallet_name)
+ assert journal_path.exists()
+ self.assert_no_tmp_db(self.master_node.wallets_path)
+ self.assert_is_bdb(wallet_name)
+
+ def test_db_named_as_journal(self):
+ self.log.info("Test migration does not remove a wallet database named like a journal of the migrated wallet")
+ wallet_name = "db_named_as_journal"
+ wallet = self.create_legacy_wallet(wallet_name)
+ wallet.unloadwallet()
+ wallet_path = self.master_node.wallets_path / wallet_name
+ shutil.copytree(self.old_node.wallets_path / wallet_name, wallet_path, dirs_exist_ok=True)
+ journal_path = wallet_path / "wallet.dat-journal"
+ shutil.copyfile(wallet_path / "wallet.dat", journal_path)
+
+ assert_raises_rpc_error(-4, f"Migration failed: Error: Unable to move the wallet db, unexpected file {journal_path} found at the destination. Move it elsewhere and try again.", self.master_node.migratewallet, wallet_name)
+ assert journal_path.exists()
+ self.assert_no_tmp_db(self.master_node.wallets_path)
+ self.assert_is_bdb(wallet_name)
+
+ def test_other_filesystem(self):
+ self.log.info("Test migration of a wallet located on a different filesystem than the wallets directory")
+ wallets_dev = os.stat(self.master_node.wallets_path).st_dev
+ other_fs = next((p for p in [Path("/dev/shm"), Path(tempfile.gettempdir())] if p.is_dir() and os.stat(p).st_dev != wallets_dev), None)
+ if other_fs is None:
+ self.log.warning("Skipping migration on other filesystem test: no other filesystem available")
+ return
+
+ with tempfile.TemporaryDirectory(prefix="wallet_migration_", dir=other_fs) as parent_dir:
+ wallet_name = str(Path(parent_dir) / "wallet")
+ wallet = self.create_legacy_wallet(wallet_name)
+ addr = wallet.getnewaddress()
+
+ migrate_res, wallet = self.migrate_and_get_rpc(wallet_name)
+ assert_equal(wallet.getaddressinfo(addr)["ismine"], True)
+ self.assert_no_tmp_db(parent_dir) # tmp db is created next to the wallet, check it was cleaned up
+ wallet.unloadwallet()
+ os.remove(migrate_res["backup_path"])
+
def test_basic(self):
# Update listtransctions' output from old nodes to be compatible
def listtransactions_compatibility(list):
@@ -1758,6 +1859,10 @@ def run_test(self):
self.generate(self.master_node, 101)
# TODO: Test the actual records in the wallet for these tests too. The behavior may be correct, but the data written may not be what we actually want
+ self.test_unwritable_dir_failure()
+ self.test_stale_journal()
+ self.test_db_named_as_journal()
+ self.test_other_filesystem()
self.test_basic()
self.test_multisig()
self.test_other_watchonly()Why this scored 53/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.