Skip to content

Commit 9105887

Browse files
committed
Merge bitcoin/bitcoin#32273: wallet: Fix relative path backup during migration.
76fe0e5 test: Migration of a wallet ending in `../` (David Gumberg) f0bb3d5 test: Migration of a wallet ending in `/` (David Gumberg) 41faef5 test: Migration fail recovery w/ `../` in path (David Gumberg) 63c6d36 test: Migration of a wallet with `../` in path. (David Gumberg) 70f1c99 wallet: Fix migration of wallets with pathnames. (David Gumberg) f6ee59b wallet: migration: Make backup in walletdir (David Gumberg) e22c359 test: wallet: Check direct file backup name. (David Gumberg) Pull request description: Support for wallets outside of the default wallet directory was added in #11687, and these external wallets can be specified with paths relative to the wallet directory, e.g. `bitcoin-cli loadwallet ../../mywallet`. In the RPC commands, there is no distinction between a wallet's 'name' and a wallet's 'path'. This PR fixes an issue with wallet backup during migration where the wallet's 'name-path' is used in the backup filename. This goes south when that filename is appended to the directory where we want to put the file and the wallet's 'name' actually gets treated as a path: ```cpp fs::path backup_filename = fs::PathFromString(strprintf("%s_%d.legacy.bak", (wallet_name.empty() ? "default_wallet" : wallet_name), GetTime())); fs::path backup_path = this_wallet_dir / backup_filename; ``` Attempting to migrate a wallet with the 'name' `../../../mywallet` results in a backup being placed in `datadir/wallets/../../../mywallet/../../../mywallet_1744683963.legacy.bak`. If permissions don't exist to write to that folder, migration can fail. The solution implemented here is to put backup files in the top-level of the node's `walletdir` directory, using the folder name (and in some rare cases the file name) of the wallet to name the backup file: https://github.com/bitcoin/bitcoin/blob/9fa5480fc4c46fa11345c45fbe4dd21c127e3e05/src/wallet/wallet.cpp#L4254-L4268 ##### Steps to reproduce on master Build and run `bitcoind` with legacy wallet creation enabled: ```bash $ cmake -B build -DWITH_BDB=ON && cmake --build build -j $(nproc) $ ./build/bin/bitcoind -regtest -deprecatedrpc=create_bdb ``` Create a wallet with some relative path specifiers (exercise caution with where this file may be written) ```bash $ ./build/bin/bitcoin-cli -regtest -named createwallet wallet_name="../../../myrelativewallet" descriptors=false ``` Try to migrate the wallet: ```bash $ ./build/bin/bitcoin-cli -regtest -named migratewallet wallet_name="../../../myrelativewallet" ``` You will see a message in `debug.log` about trying to backup a file somewhere like: `/home/user/.bitcoin/regtest/wallets/../../../myrelativewallet/../../../myrelativewallet_1744686627.legacy.bak` and migration might fail because `bitcoind` doesn't have permissions to write the backup file. ACKs for top commit: pablomartin4btc: tACK 76fe0e5 achow101: ACK 76fe0e5 ryanofsky: Code review ACK 76fe0e5. Nice changes that (1) fix potential errors when names of wallets being migrated contain slashes, and (2) store migration backups in the top-level `-walletdir` instead of in individual wallet subdirectories. Tree-SHA512: 5cf6ed9f44ac7d204e4e9854edd3fb9b43812e930f76343b142b3c19df3de2ae5ca1548d4a8d26226d537bca231e3a50b3ff0d963c200303fb761f2b4eb3f0d9
2 parents 6b99670 + 76fe0e5 commit 9105887

File tree

2 files changed

+182
-19
lines changed

2 files changed

+182
-19
lines changed

src/wallet/wallet.cpp

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4201,10 +4201,20 @@ util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet>
42014201
return util::Error{_("Error: This wallet is already a descriptor wallet")};
42024202
}
42034203

4204-
// Make a backup of the DB
4205-
fs::path this_wallet_dir = fs::absolute(fs::PathFromString(local_wallet->GetDatabase().Filename())).parent_path();
4206-
fs::path backup_filename = fs::PathFromString(strprintf("%s_%d.legacy.bak", (wallet_name.empty() ? "default_wallet" : wallet_name), GetTime()));
4207-
fs::path backup_path = this_wallet_dir / backup_filename;
4204+
// Make a backup of the DB in the wallet's directory with a unique filename
4205+
// using the wallet name and current timestamp. The backup filename is based
4206+
// on the name of the parent directory containing the wallet data in most
4207+
// cases, but in the case where the wallet name is a path to a data file,
4208+
// the name of the data file is used, and in the case where the wallet name
4209+
// is blank, "default_wallet" is used.
4210+
const std::string backup_prefix = wallet_name.empty() ? "default_wallet" : [&] {
4211+
// fs::weakly_canonical resolves relative specifiers and remove trailing slashes.
4212+
const auto legacy_wallet_path = fs::weakly_canonical(GetWalletDir() / fs::PathFromString(wallet_name));
4213+
return fs::PathToString(legacy_wallet_path.filename());
4214+
}();
4215+
4216+
fs::path backup_filename = fs::PathFromString(strprintf("%s_%d.legacy.bak", backup_prefix, GetTime()));
4217+
fs::path backup_path = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
42084218
if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {
42094219
return util::Error{_("Error: Unable to make a backup of your wallet")};
42104220
}
@@ -4286,11 +4296,6 @@ util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet>
42864296
}
42874297
}
42884298
if (!success) {
4289-
// Migration failed, cleanup
4290-
// Before deleting the wallet's directory, copy the backup file to the top-level wallets dir
4291-
fs::path temp_backup_location = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
4292-
fs::copy_file(backup_path, temp_backup_location, fs::copy_options::none);
4293-
42944299
// Make list of wallets to cleanup
42954300
std::vector<std::shared_ptr<CWallet>> created_wallets;
42964301
if (local_wallet) created_wallets.push_back(std::move(local_wallet));
@@ -4326,18 +4331,14 @@ util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet>
43264331
// Restore the backup
43274332
// Convert the backup file to the wallet db file by renaming it and moving it into the wallet's directory.
43284333
bilingual_str restore_error;
4329-
const auto& ptr_wallet = RestoreWallet(context, temp_backup_location, wallet_name, /*load_on_start=*/std::nullopt, status, restore_error, warnings, /*load_after_restore=*/false);
4334+
const auto& ptr_wallet = RestoreWallet(context, backup_path, wallet_name, /*load_on_start=*/std::nullopt, status, restore_error, warnings, /*load_after_restore=*/false);
43304335
if (!restore_error.empty()) {
43314336
error += restore_error + _("\nUnable to restore backup of wallet.");
43324337
return util::Error{error};
43334338
}
43344339
// Verify that the legacy wallet is not loaded after restoring from the backup.
43354340
assert(!ptr_wallet);
43364341

4337-
// The wallet directory has been restored, but just in case, copy the previously created backup to the wallet dir
4338-
fs::copy_file(temp_backup_location, backup_path, fs::copy_options::none);
4339-
fs::remove(temp_backup_location);
4340-
43414342
return util::Error{error};
43424343
}
43434344
return res;

test/functional/wallet_migration.py

Lines changed: 167 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,23 +118,39 @@ def migrate_and_get_rpc(self, wallet_name, **kwargs):
118118
if wallet_name == "":
119119
shutil.copyfile(self.old_node.wallets_path / "wallet.dat", self.master_node.wallets_path / "wallet.dat")
120120
else:
121-
shutil.copytree(self.old_node.wallets_path / wallet_name, self.master_node.wallets_path / wallet_name)
121+
src = os.path.abspath(self.old_node.wallets_path / wallet_name)
122+
dst = os.path.abspath(self.master_node.wallets_path / wallet_name)
123+
if src != dst :
124+
shutil.copytree(self.old_node.wallets_path / wallet_name, self.master_node.wallets_path / wallet_name, dirs_exist_ok=True)
122125
# Check that the wallet shows up in listwalletdir with a warning about migration
123126
wallets = self.master_node.listwalletdir()
124127
for w in wallets["wallets"]:
125128
if w["name"] == wallet_name:
126129
assert_equal(w["warnings"], ["This wallet is a legacy wallet and will need to be migrated with migratewallet before it can be loaded"])
130+
131+
# Mock time so that we can check the backup filename.
132+
mocked_time = int(time.time())
133+
self.master_node.setmocktime(mocked_time)
127134
# Migrate, checking that rescan does not occur
128135
with self.master_node.assert_debug_log(expected_msgs=[], unexpected_msgs=["Rescanning"]):
129136
migrate_info = self.master_node.migratewallet(wallet_name=wallet_name, **kwargs)
137+
self.master_node.setmocktime(0)
130138
# Update wallet name in case the initial wallet was completely migrated to a watch-only wallet
131139
# (in which case the wallet name would be suffixed by the 'watchonly' term)
132-
wallet_name = migrate_info['wallet_name']
133-
wallet = self.master_node.get_wallet_rpc(wallet_name)
140+
migrated_wallet_name = migrate_info['wallet_name']
141+
wallet = self.master_node.get_wallet_rpc(migrated_wallet_name)
134142
assert_equal(wallet.getwalletinfo()["descriptors"], True)
135-
self.assert_is_sqlite(wallet_name)
143+
self.assert_is_sqlite(migrated_wallet_name)
136144
# Always verify the backup path exist after migration
137145
assert os.path.exists(migrate_info['backup_path'])
146+
if wallet_name == "":
147+
backup_prefix = "default_wallet"
148+
else:
149+
backup_prefix = os.path.basename(os.path.realpath(self.old_node.wallets_path / wallet_name))
150+
151+
expected_backup_path = self.master_node.wallets_path / f"{backup_prefix}_{mocked_time}.legacy.bak"
152+
assert_equal(str(expected_backup_path), migrate_info['backup_path'])
153+
138154
return migrate_info, wallet
139155

140156
def test_basic(self):
@@ -553,6 +569,98 @@ def test_unloaded_by_path(self):
553569

554570
assert_equal(bals, wallet.getbalances())
555571

572+
def test_wallet_with_relative_path(self):
573+
self.log.info("Test migration of a wallet that isn't loaded, specified by a relative path")
574+
575+
# Get the nearest common path of both nodes' wallet paths.
576+
common_parent = os.path.commonpath([self.master_node.wallets_path, self.old_node.wallets_path])
577+
578+
# This test assumes that the relative path from each wallet directory to the common path is identical.
579+
assert_equal(os.path.relpath(common_parent, start=self.master_node.wallets_path), os.path.relpath(common_parent, start=self.old_node.wallets_path))
580+
581+
wallet_name = "relative"
582+
absolute_path = os.path.abspath(os.path.join(common_parent, wallet_name))
583+
relative_name = os.path.relpath(absolute_path, start=self.master_node.wallets_path)
584+
585+
wallet = self.create_legacy_wallet(relative_name)
586+
# listwalletdirs only returns wallets in the wallet directory
587+
assert {"name": relative_name} not in wallet.listwalletdir()["wallets"]
588+
assert relative_name in wallet.listwallets()
589+
590+
default = self.master_node.get_wallet_rpc(self.default_wallet_name)
591+
addr = wallet.getnewaddress()
592+
txid = default.sendtoaddress(addr, 1)
593+
self.generate(self.master_node, 1)
594+
bals = wallet.getbalances()
595+
596+
# migratewallet uses current time in naming the backup file, set a mock time
597+
# to check that this works correctly.
598+
curr_time = int(time.time())
599+
self.master_node.setmocktime(curr_time)
600+
migrate_res, wallet = self.migrate_and_get_rpc(relative_name)
601+
self.master_node.setmocktime(0)
602+
603+
# Check that the wallet was migrated, knows the right txid, and has the right balance.
604+
assert wallet.gettransaction(txid)
605+
assert_equal(bals, wallet.getbalances())
606+
607+
# The migrated wallet should not be in the wallet dir, but should be in the list of wallets.
608+
info = wallet.getwalletinfo()
609+
610+
walletdirlist = wallet.listwalletdir()
611+
assert {"name": info["walletname"]} not in walletdirlist["wallets"]
612+
613+
walletlist = wallet.listwallets()
614+
assert info["walletname"] in walletlist
615+
616+
# Check that old node can restore from the backup.
617+
self.old_node.restorewallet("relative_restored", migrate_res['backup_path'])
618+
wallet = self.old_node.get_wallet_rpc("relative_restored")
619+
assert wallet.gettransaction(txid)
620+
assert_equal(bals, wallet.getbalances())
621+
622+
info = wallet.getwalletinfo()
623+
assert_equal(info["descriptors"], False)
624+
assert_equal(info["format"], "bdb")
625+
626+
def test_wallet_with_path_ending_in_slash(self):
627+
self.log.info("Test migrating a wallet with a name/path ending in '/'")
628+
629+
# The last directory in the wallet's path
630+
final_dir = "mywallet"
631+
wallet_name = f"path/to/{final_dir}/"
632+
wallet = self.create_legacy_wallet(wallet_name)
633+
default = self.master_node.get_wallet_rpc(self.default_wallet_name)
634+
635+
addr = wallet.getnewaddress()
636+
txid = default.sendtoaddress(addr, 1)
637+
self.generate(self.master_node, 1)
638+
bals = wallet.getbalances()
639+
640+
_, wallet = self.migrate_and_get_rpc(wallet_name)
641+
642+
assert wallet.gettransaction(txid)
643+
644+
assert_equal(bals, wallet.getbalances())
645+
646+
def test_wallet_with_path_ending_in_relative_specifier(self):
647+
self.log.info("Test migrating a wallet with a name/path ending in a relative specifier, '..'")
648+
wallet_ending_in_relative = "path/that/ends/in/.."
649+
# the wallet data is actually inside of path/that/ends/
650+
wallet = self.create_legacy_wallet(wallet_ending_in_relative)
651+
default = self.master_node.get_wallet_rpc(self.default_wallet_name)
652+
653+
addr = wallet.getnewaddress()
654+
txid = default.sendtoaddress(addr, 1)
655+
self.generate(self.master_node, 1)
656+
bals = wallet.getbalances()
657+
658+
_, wallet = self.migrate_and_get_rpc(wallet_ending_in_relative)
659+
660+
assert wallet.gettransaction(txid)
661+
662+
assert_equal(bals, wallet.getbalances())
663+
556664
def test_default_wallet(self):
557665
self.log.info("Test migration of the wallet named as the empty string")
558666
wallet = self.create_legacy_wallet("")
@@ -590,7 +698,10 @@ def test_direct_file(self):
590698
)
591699
assert (self.master_node.wallets_path / "plainfile").is_file()
592700

593-
self.master_node.migratewallet("plainfile")
701+
mocked_time = int(time.time())
702+
self.master_node.setmocktime(mocked_time)
703+
migrate_res = self.master_node.migratewallet("plainfile")
704+
assert_equal(f"plainfile_{mocked_time}.legacy.bak", os.path.basename(migrate_res["backup_path"]))
594705
wallet = self.master_node.get_wallet_rpc("plainfile")
595706
info = wallet.getwalletinfo()
596707
assert_equal(info["descriptors"], True)
@@ -924,6 +1035,53 @@ def test_failed_migration_cleanup(self):
9241035
# Check the wallet we tried to migrate is still BDB
9251036
self.assert_is_bdb("failed")
9261037

1038+
def test_failed_migration_cleanup_relative_path(self):
1039+
self.log.info("Test that a failed migration with a relative path is cleaned up")
1040+
1041+
# Get the nearest common path of both nodes' wallet paths.
1042+
common_parent = os.path.commonpath([self.master_node.wallets_path, self.old_node.wallets_path])
1043+
1044+
# This test assumes that the relative path from each wallet directory to the common path is identical.
1045+
assert_equal(os.path.relpath(common_parent, start=self.master_node.wallets_path), os.path.relpath(common_parent, start=self.old_node.wallets_path))
1046+
1047+
wallet_name = "relativefailure"
1048+
absolute_path = os.path.abspath(os.path.join(common_parent, wallet_name))
1049+
relative_name = os.path.relpath(absolute_path, start=self.master_node.wallets_path)
1050+
1051+
wallet = self.create_legacy_wallet(relative_name)
1052+
1053+
# Make a copy of the wallet with the solvables wallet name so that we are unable
1054+
# to create the solvables wallet when migrating, thus failing to migrate
1055+
wallet.unloadwallet()
1056+
solvables_path = os.path.join(common_parent, f"{wallet_name}_solvables")
1057+
1058+
shutil.copytree(self.old_node.wallets_path / relative_name, solvables_path)
1059+
original_shasum = sha256sum_file(os.path.join(solvables_path, "wallet.dat"))
1060+
1061+
self.old_node.loadwallet(relative_name)
1062+
1063+
# Add a multisig so that a solvables wallet is created
1064+
wallet.addmultisigaddress(2, [wallet.getnewaddress(), get_generate_key().pubkey])
1065+
wallet.importaddress(get_generate_key().p2pkh_addr)
1066+
1067+
self.old_node.unloadwallet(relative_name)
1068+
assert_raises_rpc_error(-4, "Failed to create database", self.master_node.migratewallet, relative_name)
1069+
1070+
assert all(wallet not in self.master_node.listwallets() for wallet in [f"{wallet_name}", f"{wallet_name}_watchonly", f"{wallet_name}_solvables"])
1071+
1072+
assert not (self.master_node.wallets_path / f"{wallet_name}_watchonly").exists()
1073+
# Since the file in failed_solvables is one that we put there, migration shouldn't touch it
1074+
assert os.path.exists(solvables_path)
1075+
new_shasum = sha256sum_file(os.path.join(solvables_path , "wallet.dat"))
1076+
assert_equal(original_shasum, new_shasum)
1077+
1078+
# Check the wallet we tried to migrate is still BDB
1079+
datfile = os.path.join(absolute_path, "wallet.dat")
1080+
with open(datfile, "rb") as f:
1081+
data = f.read(16)
1082+
_, _, magic = struct.unpack("QII", data)
1083+
assert_equal(magic, BTREE_MAGIC)
1084+
9271085
def test_blank(self):
9281086
self.log.info("Test that a blank wallet is migrated")
9291087
wallet = self.create_legacy_wallet("blank", blank=True)
@@ -1411,13 +1569,17 @@ def run_test(self):
14111569
self.test_encrypted()
14121570
self.test_nonexistent()
14131571
self.test_unloaded_by_path()
1572+
self.test_wallet_with_relative_path()
1573+
self.test_wallet_with_path_ending_in_slash()
1574+
self.test_wallet_with_path_ending_in_relative_specifier()
14141575
self.test_default_wallet()
14151576
self.test_direct_file()
14161577
self.test_addressbook()
14171578
self.test_migrate_raw_p2sh()
14181579
self.test_conflict_txs()
14191580
self.test_hybrid_pubkey()
14201581
self.test_failed_migration_cleanup()
1582+
self.test_failed_migration_cleanup_relative_path()
14211583
self.test_avoidreuse()
14221584
self.test_preserve_tx_extra_info()
14231585
self.test_blank()

0 commit comments

Comments
 (0)