Skip to content

Commit

Permalink
Bugfix: Wallet: Wrap RestoreWallet content in a try block to ensure e…
Browse files Browse the repository at this point in the history
…xceptions become returned errors and incomplete wallet directory is removed
  • Loading branch information
luke-jr committed Sep 16, 2022
1 parent 07df6cd commit 335ff98
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/wallet/wallet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -379,25 +379,31 @@ std::shared_ptr<CWallet> RestoreWallet(WalletContext& context, const fs::path& b
ReadDatabaseArgs(*context.args, options);
options.require_existing = true;

if (!fs::exists(backup_file)) {
error = Untranslated("Backup file does not exist");
status = DatabaseStatus::FAILED_INVALID_BACKUP_FILE;
return nullptr;
}

const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::u8path(wallet_name));
auto wallet_file = wallet_path / "wallet.dat";
std::shared_ptr<CWallet> wallet;

if (fs::exists(wallet_path) || !TryCreateDirectories(wallet_path)) {
error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", fs::PathToString(wallet_path)));
status = DatabaseStatus::FAILED_ALREADY_EXISTS;
return nullptr;
}
try {
if (!fs::exists(backup_file)) {
error = Untranslated("Backup file does not exist");
status = DatabaseStatus::FAILED_INVALID_BACKUP_FILE;
return nullptr;
}

auto wallet_file = wallet_path / "wallet.dat";
fs::copy_file(backup_file, wallet_file, fs::copy_options::none);
if (fs::exists(wallet_path) || !TryCreateDirectories(wallet_path)) {
error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", fs::PathToString(wallet_path)));
status = DatabaseStatus::FAILED_ALREADY_EXISTS;
return nullptr;
}

auto wallet = LoadWallet(context, wallet_name, load_on_start, options, status, error, warnings);
fs::copy_file(backup_file, wallet_file, fs::copy_options::none);

wallet = LoadWallet(context, wallet_name, load_on_start, options, status, error, warnings);
} catch (const std::exception& e) {
assert(!wallet);
if (!error.empty()) error += Untranslated("\n");
error += strprintf(Untranslated("Unexpected exception: %s"), e.what());
}
if (!wallet) {
fs::remove(wallet_file);
fs::remove(wallet_path);
Expand Down

0 comments on commit 335ff98

Please sign in to comment.