Branch data Line data Source code
1 : : // Copyright (c) The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or https://opensource.org/license/mit.
4 : :
5 : : #include <key_io.h>
6 : :
7 : : #include <wallet/context.h>
8 : : #include <wallet/migration.h>
9 : : #include <wallet/wallet.h>
10 : : #include <wallet/walletutil.h>
11 : :
12 : : namespace wallet {
13 : :
14 : 1042 : LegacyDataSPKM* CWallet::GetLegacyDataSPKM() const
15 : : {
16 [ + - ]: 1042 : if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
17 : : return nullptr;
18 : : }
19 : 1042 : auto it = m_internal_spk_managers.find(OutputType::LEGACY);
20 [ + - ]: 1042 : if (it == m_internal_spk_managers.end()) return nullptr;
21 [ + - ]: 1042 : return dynamic_cast<LegacyDataSPKM*>(it->second);
22 : : }
23 : :
24 : 911 : LegacyDataSPKM* CWallet::GetOrCreateLegacyDataSPKM()
25 : : {
26 : 911 : SetupLegacyDataSPKM();
27 : 911 : return GetLegacyDataSPKM();
28 : : }
29 : :
30 : 911 : void CWallet::SetupLegacyDataSPKM()
31 : : {
32 [ + + + - : 911 : if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() || !m_spk_managers.empty() || IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
+ - - + ]
33 : 859 : return;
34 : : }
35 : :
36 [ + - - + : 52 : Assert(m_database->Format() == "bdb_ro" || m_database->Format() == "sqlite-mock");
- - - - +
- - + - -
- - ]
37 : 52 : std::unique_ptr<ScriptPubKeyMan> spk_manager = std::make_unique<LegacyDataSPKM>(*this);
38 : :
39 [ + + + - ]: 208 : for (const auto& type : LEGACY_OUTPUT_TYPES) {
40 [ + - ]: 156 : m_internal_spk_managers[type] = spk_manager.get();
41 [ + - ]: 156 : m_external_spk_managers[type] = spk_manager.get();
42 : : }
43 [ + - ]: 52 : uint256 id = spk_manager->GetID();
44 [ + - ]: 52 : AddScriptPubKeyMan(id, std::move(spk_manager));
45 : 52 : }
46 : :
47 : : // Returns wallet prefix for migration.
48 : : // Used to name the backup file and newly created wallets.
49 : : // E.g. a watch-only wallet is named "<prefix>_watchonly".
50 : 35 : static std::string MigrationPrefixName(CWallet& wallet)
51 : : {
52 [ + + ]: 35 : const std::string& name{wallet.GetName()};
53 [ + + ]: 35 : return name.empty() ? "default_wallet" : name;
54 : : }
55 : :
56 : : // Returns prefix for files created in the wallets directory during migration:
57 : : // the backup file and the temporary database. Unlike MigrationPrefixName(),
58 : : // this is a single path component, because the wallet name can be a path.
59 : 107 : static std::string MigrationFilePrefix(CWallet& wallet)
60 : : {
61 [ + + ]: 107 : const std::string& name{wallet.GetName()};
62 [ + + ]: 107 : if (name.empty()) return MigrationPrefixName(wallet);
63 : : // fs::weakly_canonical resolves relative specifiers and removes trailing slashes.
64 [ + - + - ]: 570 : const fs::path legacy_wallet_path{fs::weakly_canonical(GetWalletDir() / fs::PathFromString(name))};
65 [ + - - + ]: 475 : return fs::PathToString(legacy_wallet_path.filename());
66 : 95 : }
67 : :
68 : 52 : bool CWallet::MigrateToSQLite(bilingual_str& error)
69 : : {
70 : 52 : AssertLockHeld(cs_wallet);
71 : :
72 : 52 : WalletLogPrintf("Migrating wallet storage database from BerkeleyDB to SQLite.");
73 : :
74 [ - + ]: 52 : if (m_database->Format() == "sqlite") {
75 : 0 : error = _("Error: This wallet already uses SQLite");
76 : 0 : return false;
77 : : }
78 : :
79 : : // Get all of the records for DB type migration
80 : 52 : std::unique_ptr<DatabaseBatch> batch = m_database->MakeBatch();
81 [ + - ]: 52 : std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
82 : 52 : std::vector<std::pair<SerializeData, SerializeData>> records;
83 [ - + ]: 52 : if (!cursor) {
84 [ # # ]: 0 : error = _("Error: Unable to begin reading all records in the database");
85 : 0 : return false;
86 : : }
87 : 2055 : DatabaseCursor::Status status = DatabaseCursor::Status::FAIL;
88 : 4058 : while (true) {
89 : 2055 : DataStream ss_key{};
90 : 2055 : DataStream ss_value{};
91 [ + - ]: 2055 : status = cursor->Next(ss_key, ss_value);
92 [ + + ]: 2055 : if (status != DatabaseCursor::Status::MORE) {
93 : : break;
94 : : }
95 [ + - ]: 2003 : SerializeData key(ss_key.begin(), ss_key.end());
96 [ + - ]: 2003 : SerializeData value(ss_value.begin(), ss_value.end());
97 [ + - ]: 2003 : records.emplace_back(key, value);
98 : 2055 : }
99 [ + - ]: 52 : cursor.reset();
100 [ + - ]: 52 : batch.reset();
101 [ - + ]: 52 : if (status != DatabaseCursor::Status::DONE) {
102 [ # # ]: 0 : error = _("Error: Unable to read all records in the database");
103 : 0 : return false;
104 : : }
105 : :
106 : : // Close this database. It stays untouched until the new one is fully built
107 [ + - + - : 156 : const fs::path db_file = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_database->Filename()));
+ - + - ]
108 [ + - ]: 52 : m_database->Close();
109 : :
110 : : // Create a temporary database next to the original db file
111 [ + - + - : 52 : const std::string new_db_name = strprintf("%s_sqlite_%d.tmp", MigrationFilePrefix(*this), GetTime());
+ - ]
112 [ + - + - : 260 : const fs::path tmp_wallet_path = fs::path{db_file.parent_path()} / fs::PathFromString(new_db_name);
+ - ]
113 : : // Refuse any existing path, not just an existing database (all that require_create checks), so cleanup only
114 : : // deletes files this function created.
115 [ - + ]: 52 : if (std::error_code ec; fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {
116 [ # # # # ]: 0 : error = strprintf(_("Error: Unable to create the new database for wallet '%s'. Temporary path '%s' already exists."), GetName(), fs::PathToString(tmp_wallet_path));
117 : 0 : return false;
118 : : }
119 : :
120 : : // Generate the path for the location of the migrated wallet
121 : : // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
122 [ + - + - : 104 : const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
+ - ]
123 : :
124 : : // Make new DB
125 [ + - ]: 52 : DatabaseOptions opts;
126 : 52 : opts.require_create = true;
127 : 52 : opts.require_format = DatabaseFormat::SQLITE;
128 : 52 : DatabaseStatus db_status;
129 [ + - ]: 52 : std::unique_ptr<WalletDatabase> new_db = MakeDatabase(tmp_wallet_path, opts, db_status, error);
130 : :
131 : : // Set the error, then delete the temporary database and its directory. The directory did not exist before, so it
132 : : // only holds files of the new db, including any left by a failed creation.
133 : 54 : const auto remove_tmp_and_fail = [&](bilingual_str err) {
134 : 2 : error = std::move(err);
135 [ + - ]: 2 : new_db.reset(); // Close the db before deleting its files
136 : 2 : std::error_code ec;
137 [ + - + - : 6 : for (auto it{fs::directory_iterator(tmp_wallet_path, ec)}; !ec && it != fs::directory_iterator(); it.increment(ec)) {
+ + + + ]
138 : 2 : fs::remove(it->path(), ec);
139 : 0 : }
140 : 2 : fs::remove(tmp_wallet_path, ec);
141 [ - + ]: 2 : if (ec) {
142 [ # # # # : 0 : error += Untranslated(" ") + strprintf(_("The temporary database at %s could not be removed."), fs::PathToString(tmp_wallet_path));
# # # # #
# ]
143 : : }
144 : 2 : return false;
145 : 52 : };
146 : :
147 [ - + ]: 52 : if (!new_db) {
148 [ # # # # : 0 : return remove_tmp_and_fail(strprintf(_("Error: Unable to create the new database for wallet '%s'."), GetName()) + Untranslated(" ") + error);
# # # # #
# ]
149 : : }
150 : :
151 : : // Write existing records into the new DB
152 [ + - ]: 52 : const bool written = RunWithinTxn(*new_db, "migration: write records to new db", [&records](DatabaseBatch& in_batch) {
153 [ - + + + ]: 2055 : for (const auto& [key, value] : records) {
154 [ - + - + : 2003 : if (!in_batch.Write(std::span{key}, std::span{value})) return false;
+ - ]
155 : : }
156 : : return true;
157 : : });
158 [ - + ]: 52 : if (!written) {
159 [ # # # # ]: 0 : return remove_tmp_and_fail(strprintf(_("Error: Unable to write records into the new database for wallet '%s'"), GetName()));
160 : : }
161 : :
162 : : // ######################################################################
163 : : // At this point, the new database has all records. #
164 : : // Move it into the wallet location, replacing the original db file. #
165 : : // ######################################################################
166 : :
167 : : // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be
168 : : // atomically replaced by a directory, the original db is erased first in that case. The original db is a single
169 : : // file, so if Erase() fails nothing was removed, and returning false is still correct.
170 [ + + ]: 52 : if (db_file == dst_wallet_dir) {
171 [ + - ]: 2 : Assume(m_database->Files().size() == 1);
172 [ + - - + : 2 : if (auto res{m_database->Erase()}; !res) return remove_tmp_and_fail(util::ErrorString(res));
- - - - ]
173 : : }
174 : :
175 : : // From here on, the original db may have been erased or replaced. Never return false after this point, as the
176 : : // caller would skip the restore. Throw instead, so it deletes the wallet files and restores the backup.
177 [ + - + + ]: 52 : if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) {
178 [ + - + - ]: 2 : remove_tmp_and_fail(util::ErrorString(res));
179 [ + - ]: 2 : throw std::runtime_error(error.original);
180 : 2 : }
181 : : // The caller's rollback deletes m_database's files, so point it at the new db as soon as it replaces the original
182 : 50 : m_database = std::move(new_db);
183 : : // The temporary dir only held the new db files, which were just moved out. If it can't be removed, something
184 : : // unexpected happened, so stop and let the caller restore the backup.
185 [ - + ]: 50 : if (std::error_code ec; !fs::remove(tmp_wallet_path, ec)) {
186 [ # # # # : 0 : 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"));
# # # # #
# ]
187 : : }
188 : : return true;
189 : 214 : }
190 : :
191 : 47 : std::optional<MigrationData> CWallet::GetDescriptorsForLegacy(bilingual_str& error) const
192 : : {
193 : 47 : AssertLockHeld(cs_wallet);
194 : :
195 : 47 : LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();
196 [ - + ]: 47 : if (!Assume(legacy_spkm)) {
197 : : // This shouldn't happen
198 [ # # ]: 0 : error = Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"));
199 : 0 : return std::nullopt;
200 : : }
201 : :
202 : 47 : std::optional<MigrationData> res = legacy_spkm->MigrateToDescriptor();
203 [ - + ]: 47 : if (res == std::nullopt) {
204 [ # # ]: 0 : error = _("Error: Unable to produce descriptors for this legacy wallet. Make sure to provide the wallet's passphrase if it is encrypted.");
205 : 0 : return std::nullopt;
206 : : }
207 : 47 : return res;
208 : 47 : }
209 : :
210 : 43 : util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data)
211 : : {
212 : 43 : AssertLockHeld(cs_wallet);
213 : :
214 : 43 : LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();
215 [ - + ]: 43 : if (!Assume(legacy_spkm)) {
216 : : // This shouldn't happen
217 [ # # ]: 0 : return util::Error{Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"))};
218 : : }
219 : :
220 : : // Note: when the legacy wallet has no spendable scripts, it must be empty at the end of the process.
221 [ + + - + ]: 43 : bool has_spendable_material = !data.desc_spkms.empty() || data.master_key.key.IsValid();
222 : :
223 : : // Get all invalid or non-watched scripts that will not be migrated
224 [ + - ]: 43 : std::set<CTxDestination> not_migrated_dests;
225 [ + - + + : 47 : for (const auto& script : legacy_spkm->GetNotMineScriptPubKeys()) {
+ - ]
226 : 4 : CTxDestination dest;
227 [ + - + - : 4 : if (ExtractDestination(script, dest)) not_migrated_dests.emplace(dest);
+ - ]
228 : 4 : }
229 : :
230 : : // When the legacy wallet has no spendable scripts, the main wallet will be empty, leaving its script cache empty as well.
231 : : // The watch-only and/or solvable wallet(s) will contain the scripts in their respective caches.
232 [ + + ]: 43 : if (!data.desc_spkms.empty()) Assume(!m_cached_spks.empty());
233 [ + + ]: 43 : if (!data.watch_descs.empty()) Assume(!data.watchonly_wallet->m_cached_spks.empty());
234 [ + + ]: 43 : if (!data.solvable_descs.empty()) Assume(!data.solvable_wallet->m_cached_spks.empty());
235 : :
236 [ + + ]: 231 : for (auto& desc_spkm : data.desc_spkms) {
237 [ + - - + ]: 188 : if (m_spk_managers.contains(desc_spkm->GetID())) {
238 [ # # ]: 0 : return util::Error{_("Error: Duplicate descriptors created during migration. Your wallet may be corrupted.")};
239 : : }
240 [ + - ]: 188 : uint256 id = desc_spkm->GetID();
241 [ + - ]: 188 : AddScriptPubKeyMan(id, std::move(desc_spkm));
242 : : }
243 : :
244 : : // Remove the LegacyDataSPKM's records from disk
245 [ + - - + ]: 43 : if (!legacy_spkm->DeleteRecordsWithDB(local_wallet_batch)) {
246 [ # # ]: 0 : return util::Error{_("Error: cannot remove legacy wallet records")};
247 : : }
248 : :
249 : : // Remove the LegacyDataSPKM from memory
250 [ + - ]: 43 : m_spk_managers.erase(legacy_spkm->GetID());
251 : 43 : m_external_spk_managers.clear();
252 : 43 : m_internal_spk_managers.clear();
253 : :
254 : : // Setup new descriptors (only if we are migrating any key material)
255 [ + - ]: 43 : SetWalletFlagWithDB(local_wallet_batch, WALLET_FLAG_DESCRIPTORS | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
256 [ + + + - : 43 : if (has_spendable_material && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
+ + ]
257 : : // Use the existing master key if we have it
258 [ + + ]: 38 : if (data.master_key.key.IsValid()) {
259 [ + - ]: 35 : SetupDescriptorScriptPubKeyMans(local_wallet_batch, data.master_key);
260 : : } else {
261 : : // Setup with a new seed if we don't.
262 [ + - ]: 3 : SetupOwnDescriptorScriptPubKeyMans(local_wallet_batch);
263 : : }
264 : : }
265 : :
266 : : // Set the last opened version and features
267 [ + - - + ]: 43 : if (!local_wallet_batch.WriteLastOpenedVersion()) {
268 [ # # ]: 0 : return util::Error{_("Error: Unable to write last opened version")};
269 : : }
270 [ + - - + ]: 43 : if (!local_wallet_batch.WriteLastOpenedFeatures()) {
271 [ # # ]: 0 : return util::Error{_("Error: Unable to write last opened features")};
272 : : }
273 [ + - + + ]: 43 : if (HasEncryptionKeys()) {
274 [ + - - + ]: 3 : if (!local_wallet_batch.WriteLastDecryptedFeatures()) {
275 [ # # ]: 0 : return util::Error{_("Error: Unable to write last decrypted features")};
276 : : }
277 : : }
278 : :
279 : : // Get best block locator so that we can copy it to the watchonly and solvables
280 : : // Note: The best block locator was introduced in #152 so ancient wallets do not have it
281 : 43 : CBlockLocator best_block_locator;
282 [ + - ]: 43 : (void)local_wallet_batch.ReadBestBlock(best_block_locator);
283 : :
284 : : // Update m_txos to match the descriptors remaining in this wallet
285 : 43 : m_txos.clear();
286 [ + - ]: 43 : RefreshAllTXOs();
287 : :
288 : : // Check if the transactions in the wallet are still ours. Either they belong here, or they belong in the watchonly wallet.
289 : : // We need to go through these in the tx insertion order so that lookups to spends works.
290 : 43 : std::vector<Txid> txids_to_delete;
291 : 43 : std::unique_ptr<WalletBatch> watchonly_batch;
292 [ + + ]: 43 : if (data.watchonly_wallet) {
293 [ + - ]: 24 : watchonly_batch = std::make_unique<WalletBatch>(data.watchonly_wallet->GetDatabase());
294 [ + - - + : 12 : if (!watchonly_batch->TxnBegin()) return util::Error{strprintf(_("Error: database transaction cannot be executed for wallet %s"), data.watchonly_wallet->GetName())};
- - ]
295 : : // Copy the next tx order pos to the watchonly wallet
296 [ + - ]: 12 : LOCK(data.watchonly_wallet->cs_wallet);
297 [ + - ]: 12 : data.watchonly_wallet->nOrderPosNext = nOrderPosNext;
298 [ + - ]: 12 : watchonly_batch->WriteOrderPosNext(data.watchonly_wallet->nOrderPosNext);
299 : : // Write the locator record. An empty locator is valid and triggers rescan on load.
300 [ + - - + ]: 12 : if (!watchonly_batch->WriteBestBlock(best_block_locator)) {
301 [ # # # # ]: 0 : return util::Error{_("Error: Unable to write watchonly wallet best block locator record")};
302 : : }
303 : 12 : }
304 : 43 : std::unique_ptr<WalletBatch> solvables_batch;
305 [ + + ]: 43 : if (data.solvable_wallet) {
306 [ + - ]: 12 : solvables_batch = std::make_unique<WalletBatch>(data.solvable_wallet->GetDatabase());
307 [ + - - + : 6 : if (!solvables_batch->TxnBegin()) return util::Error{strprintf(_("Error: database transaction cannot be executed for wallet %s"), data.solvable_wallet->GetName())};
- - ]
308 : : // Write the locator record. An empty locator is valid and triggers rescan on load.
309 [ + - - + ]: 6 : if (!solvables_batch->WriteBestBlock(best_block_locator)) {
310 [ # # ]: 0 : return util::Error{_("Error: Unable to write solvable wallet best block locator record")};
311 : : }
312 : : }
313 [ + - + + ]: 520 : for (const auto& [_pos, wtx] : wtxOrdered) {
314 : : // Check it is the watchonly wallet's
315 : : // solvable_wallet doesn't need to be checked because transactions for those scripts weren't being watched for
316 [ + - + - : 489 : bool is_mine = IsMine(*wtx->GetTx()) || IsFromMe(*wtx->GetTx());
+ + + - +
- + + - -
- - ]
317 [ + + ]: 477 : if (data.watchonly_wallet) {
318 [ + - ]: 22 : LOCK(data.watchonly_wallet->cs_wallet);
319 [ + - + - : 54 : if (data.watchonly_wallet->IsMine(*wtx->GetTx()) || data.watchonly_wallet->IsFromMe(*wtx->GetTx())) {
+ + + - +
- + + + +
- - - - ]
320 : : // Add to watchonly wallet
321 [ + - ]: 14 : const Txid& hash = wtx->GetHash();
322 : 14 : DataStream wtx_ser;
323 [ + - ]: 14 : wtx_ser << *wtx;
324 [ + - ]: 14 : CWalletTx copy_wtx(deserialize, wtx_ser, wtx->GetTxs());
325 [ + - - + ]: 14 : if (!data.watchonly_wallet->LoadToWallet(std::move(copy_wtx))) {
326 [ # # # # : 0 : return util::Error{strprintf(_("Error: Could not add watchonly tx %s to watchonly wallet"), wtx->GetHash().GetHex())};
# # ]
327 : : }
328 [ + - + - ]: 14 : watchonly_batch->WriteFullTx(data.watchonly_wallet->mapWallet.at(hash));
329 : : // Mark as to remove from the migrated wallet only if it does not also belong to it
330 [ + + ]: 14 : if (!is_mine) {
331 [ + - ]: 11 : txids_to_delete.push_back(hash);
332 : 11 : continue;
333 : : }
334 [ - - + - ]: 14 : }
335 : 22 : }
336 [ - + ]: 466 : if (!is_mine) {
337 : : // Both not ours and not in the watchonly wallet
338 [ # # # # : 0 : return util::Error{strprintf(_("Error: Transaction %s in wallet cannot be identified to belong to migrated wallets"), wtx->GetHash().GetHex())};
# # ]
339 : : }
340 : : // Rewrite the transaction so that anything that may have changed about it in memory also persists to disk
341 [ + - ]: 466 : local_wallet_batch.WriteTxMetadata(*wtx);
342 : : }
343 : :
344 : : // Do the removes
345 [ - + + + ]: 43 : if (txids_to_delete.size() > 0) {
346 [ + - - + ]: 6 : if (auto res = RemoveTxs(local_wallet_batch, txids_to_delete); !res) {
347 [ # # # # ]: 0 : return util::Error{_("Error: Could not delete watchonly transactions. ") + util::ErrorString(res)};
348 : 6 : }
349 : : }
350 : :
351 : : // Pair external wallets with their corresponding db handler
352 : 43 : std::vector<std::pair<std::shared_ptr<CWallet>, std::unique_ptr<WalletBatch>>> wallets_vec;
353 [ + + + - ]: 43 : if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet, std::move(watchonly_batch));
354 [ + + + - ]: 43 : if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet, std::move(solvables_batch));
355 : :
356 : : // Write address book entry to disk
357 : 104 : auto func_store_addr = [](WalletBatch& batch, const CTxDestination& dest, const CAddressBookData& entry) {
358 : 61 : auto address{EncodeDestination(dest)};
359 [ + - + - : 122 : if (entry.purpose) batch.WritePurpose(address, PurposeToString(*entry.purpose));
+ - ]
360 [ + - + - ]: 61 : if (entry.label) batch.WriteName(address, *entry.label);
361 [ - - - + ]: 61 : for (const auto& [id, request] : entry.receive_requests) {
362 [ # # ]: 0 : batch.WriteAddressReceiveRequest(dest, id, request);
363 : : }
364 [ + + + - ]: 61 : if (entry.previously_spent) batch.WriteAddressPreviouslySpent(dest, true);
365 : 61 : };
366 : :
367 : : // Check the address book data in the same way we did for transactions
368 : 43 : std::vector<CTxDestination> dests_to_delete;
369 [ + - + + ]: 157 : for (const auto& [dest, record] : m_address_book) {
370 : : // Ensure "receive" entries that are no longer part of the original wallet are transferred to another wallet
371 : : // Entries for everything else ("send") will be cloned to all wallets.
372 [ + - + - : 220 : bool require_transfer = record.purpose == AddressPurpose::RECEIVE && !IsMine(dest);
+ + ]
373 : 114 : bool copied = false;
374 [ + - + + ]: 152 : for (auto& [wallet, batch] : wallets_vec) {
375 [ + - ]: 62 : LOCK(wallet->cs_wallet);
376 [ + + + - : 62 : if (require_transfer && !wallet->IsMine(dest)) continue;
+ + + - ]
377 : :
378 : : // Copy the entire address book entry
379 [ + - + - ]: 61 : wallet->m_address_book[dest] = record;
380 [ + - ]: 61 : func_store_addr(*batch, dest, record);
381 : :
382 : 61 : copied = true;
383 : : // Only delete 'receive' records that are no longer part of the original wallet
384 [ + + ]: 61 : if (require_transfer) {
385 [ + - ]: 24 : dests_to_delete.push_back(dest);
386 [ + - ]: 24 : break;
387 : : }
388 : 62 : }
389 : :
390 : : // Fail immediately if we ever found an entry that was ours and cannot be transferred
391 : : // to any of the created wallets (watch-only, solvable).
392 : : // Means that no inferred descriptor maps to the stored entry. Which mustn't happen.
393 [ + + ]: 114 : if (require_transfer && !copied) {
394 : :
395 : : // Skip invalid/non-watched scripts that will not be migrated
396 [ + - ]: 4 : if (not_migrated_dests.contains(dest)) {
397 [ + - ]: 4 : dests_to_delete.push_back(dest);
398 : 4 : continue;
399 : : }
400 : :
401 [ # # ]: 0 : return util::Error{_("Error: Address book data in wallet cannot be identified to belong to migrated wallets")};
402 : : }
403 : : }
404 : :
405 : : // Persist external wallets address book entries
406 [ + - + + ]: 61 : for (auto& [wallet, batch] : wallets_vec) {
407 [ + - - + ]: 18 : if (!batch->TxnCommit()) {
408 [ # # ]: 0 : return util::Error{strprintf(_("Error: Unable to write data to disk for wallet %s"), wallet->GetName())};
409 : : }
410 : : }
411 : :
412 : : // Remove the things to delete in this wallet
413 [ - + + + ]: 43 : if (dests_to_delete.size() > 0) {
414 [ + + ]: 40 : for (const auto& dest : dests_to_delete) {
415 [ + - - + ]: 28 : if (!DelAddressBookWithDB(local_wallet_batch, dest)) {
416 [ # # ]: 0 : return util::Error{_("Error: Unable to remove watchonly address book data")};
417 : : }
418 : : }
419 : : }
420 : :
421 : : // If there was no key material in the main wallet, there should be no records on it anymore.
422 : : // This wallet will be discarded at the end of the process. Only wallets that contain the
423 : : // migrated records will be presented to the user.
424 [ + + ]: 43 : if (!has_spendable_material) {
425 [ - + - - ]: 3 : if (!m_address_book.empty()) return util::Error{_("Error: Not all address book records were migrated")};
426 [ - + - - ]: 3 : if (!mapWallet.empty()) return util::Error{_("Error: Not all transaction records were migrated")};
427 : : }
428 : :
429 : 43 : return {}; // all good
430 : 86 : }
431 : :
432 : 47 : bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error, MigrationResult& res, const bool load_on_startup = true) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
433 : : {
434 : 47 : AssertLockHeld(wallet.cs_wallet);
435 : :
436 : : // Get all of the descriptors from the legacy wallet
437 : 47 : std::optional<MigrationData> data = wallet.GetDescriptorsForLegacy(error);
438 [ + - ]: 47 : if (data == std::nullopt) return false;
439 : :
440 : : // Create the watchonly and solvable wallets if necessary
441 [ - + + + : 47 : if (data->watch_descs.size() > 0 || data->solvable_descs.size() > 0) {
- + + + ]
442 [ + - ]: 17 : DatabaseOptions options;
443 : 17 : options.require_existing = false;
444 : 17 : options.require_create = true;
445 : 17 : options.require_format = DatabaseFormat::SQLITE;
446 : :
447 [ + - ]: 17 : WalletContext empty_context;
448 : 17 : empty_context.args = context.args;
449 : :
450 : : // Make the wallets
451 : 17 : options.create_flags = WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET | WALLET_FLAG_DESCRIPTORS;
452 [ + - + + ]: 17 : if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
453 : 1 : options.create_flags |= WALLET_FLAG_AVOID_REUSE;
454 : : }
455 [ + - + + ]: 17 : if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
456 : 13 : options.create_flags |= WALLET_FLAG_KEY_ORIGIN_METADATA;
457 : : }
458 : :
459 : 40 : const auto fn_create_wallet = [&context, &options, &empty_context, load_on_startup](const std::string& wallet_name,
460 : : const std::vector<std::pair<std::string, int64_t>>& descs_to_import,
461 : : std::shared_ptr<CWallet>& out_wallet, bilingual_str& error) {
462 : 23 : try {
463 : 23 : DatabaseStatus status;
464 : 23 : std::vector<bilingual_str> warnings;
465 [ + - ]: 23 : std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
466 [ + + ]: 23 : if (!database) {
467 [ + - ]: 4 : error = strprintf(_("Wallet file creation failed: %s"), error);
468 : 4 : return false;
469 : : }
470 : :
471 [ + - - + ]: 38 : out_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);
472 [ - + ]: 19 : if (!out_wallet) {
473 [ # # ]: 0 : error = strprintf(_("Error: Failed to create new wallet '%s'"), wallet_name);
474 : 0 : return false;
475 : : }
476 [ + - ]: 19 : LOCK(out_wallet->cs_wallet);
477 : :
478 : : // Parse the descriptors and add them to the new wallet
479 [ + + ]: 71 : for (const auto& [desc_str, creation_time] : descs_to_import) {
480 : : // Parse the descriptor
481 : 52 : FlatSigningProvider keys;
482 [ - + ]: 52 : std::string parse_err;
483 [ - + + - ]: 52 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
484 : : // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.
485 [ - + - + ]: 52 : assert(descs.size() == 1);
486 [ + - + - : 52 : assert(!descs.at(0)->IsRange());
- + ]
487 : :
488 : : // Add to the wallet
489 [ + - + - : 52 : WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
+ - ]
490 [ + - + - : 104 : if (auto spkm_res = out_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
- + ]
491 [ # # # # ]: 0 : throw std::runtime_error(util::ErrorString(spkm_res).original);
492 : 0 : }
493 : 52 : }
494 : :
495 : : // Add the wallet to settings
496 [ + - ]: 19 : UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);
497 [ + - ]: 19 : return true;
498 [ - - ]: 23 : } catch (std::exception& e) {
499 [ - - ]: 0 : error = strprintf(_("Failed to create new wallet '%s'. Error: %s"), wallet_name, e.what());
500 : 0 : return false;
501 : 0 : }
502 : 17 : };
503 : :
504 [ - + + + ]: 17 : if (data->watch_descs.size() > 0) {
505 [ + - ]: 16 : wallet.WalletLogPrintf("Making a new watchonly wallet containing the watched scripts");
506 [ + - + - ]: 32 : bool ret = fn_create_wallet(/*wallet_name=*/MigrationPrefixName(wallet) + "_watchonly", data->watch_descs, /*out_wallet=*/data->watchonly_wallet, error);
507 : 16 : res.watchonly_wallet = data->watchonly_wallet; // always set just so it can be cleaned up later
508 [ + + ]: 16 : if (!ret) return false;
509 : : }
510 [ - + + + ]: 14 : if (data->solvable_descs.size() > 0) {
511 [ + - ]: 7 : wallet.WalletLogPrintf("Making a new watchonly wallet containing the unwatched solvable scripts");
512 [ + - + - ]: 14 : bool ret = fn_create_wallet(/*wallet_name=*/MigrationPrefixName(wallet) + "_solvables", data->solvable_descs, /*out_wallet=*/data->solvable_wallet, error);
513 : 7 : res.solvables_wallet = data->solvable_wallet; // always set just so it can be cleaned up later
514 [ + + ]: 7 : if (!ret) return false;
515 : : }
516 : 17 : }
517 : :
518 : : // Add the descriptors to the wallet, remove the LegacyDataSPKM, and clean up transactions and address book data
519 [ + - + - ]: 43 : return RunWithinTxn(wallet.GetDatabase(), /*process_desc=*/"apply migration process", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet){
520 [ - + ]: 43 : if (auto res_migration = wallet.ApplyMigrationData(batch, *data); !res_migration) {
521 [ # # ]: 0 : error = util::ErrorString(res_migration);
522 : 0 : return false;
523 : 0 : }
524 : 43 : wallet.WalletLogPrintf("Wallet migration complete.");
525 : 43 : return true;
526 : : });
527 : 47 : }
528 : :
529 : 58 : util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context, bool load_wallet)
530 : : {
531 : 58 : std::vector<bilingual_str> warnings;
532 [ + - ]: 58 : bilingual_str error;
533 : :
534 : : // The only kind of wallets that could be loaded are descriptor ones, which don't need to be migrated.
535 [ + - + + ]: 58 : if (auto wallet = GetWallet(context, wallet_name)) {
536 [ + - - + ]: 1 : assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
537 [ + - ]: 3 : return util::Error{_("Error: This wallet is already a descriptor wallet")};
538 : : } else {
539 : : // Check if the wallet is BDB
540 [ + - - + ]: 112 : const auto& wallet_path = GetWalletPath(wallet_name);
541 [ - + ]: 57 : if (!wallet_path) {
542 [ # # ]: 0 : return util::Error{util::ErrorString(wallet_path)};
543 : : }
544 [ + - + + ]: 57 : if (!fs::exists(*wallet_path)) {
545 [ + - ]: 3 : return util::Error{_("Error: Wallet does not exist")};
546 : : }
547 [ + - + - : 112 : if (!IsBDBFile(BDBDataFile(*wallet_path))) {
+ + ]
548 [ + - ]: 3 : return util::Error{_("Error: This wallet is already a descriptor wallet")};
549 : : }
550 : 3 : }
551 : :
552 : : // Load the wallet but only in the context of this function.
553 : : // No signals should be connected nor should anything else be aware of this wallet
554 [ + - ]: 55 : WalletContext empty_context;
555 : 55 : empty_context.args = context.args;
556 [ + - ]: 55 : DatabaseOptions options;
557 : 55 : options.require_existing = true;
558 : 55 : options.require_format = DatabaseFormat::BERKELEY_RO;
559 : 55 : DatabaseStatus status;
560 [ + - ]: 55 : std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
561 [ - + ]: 55 : if (!database) {
562 [ # # # # : 0 : return util::Error{Untranslated("Wallet file verification failed.") + Untranslated(" ") + error};
# # # # #
# ]
563 : : }
564 : :
565 : : // Make the local wallet
566 [ + - ]: 55 : std::shared_ptr<CWallet> local_wallet = CWallet::LoadExisting(empty_context, wallet_name, std::move(database), error, warnings);
567 [ - + ]: 55 : if (!local_wallet) {
568 [ # # # # : 0 : return util::Error{Untranslated("Wallet loading failed.") + Untranslated(" ") + error};
# # # # #
# ]
569 : : }
570 : :
571 [ + - ]: 110 : return MigrateLegacyToDescriptor(std::move(local_wallet), passphrase, context, load_wallet);
572 : 113 : }
573 : :
574 : 55 : util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet> local_wallet, const SecureString& passphrase, WalletContext& context, bool load_wallet)
575 : : {
576 : 55 : MigrationResult res;
577 [ - + ]: 55 : bilingual_str error;
578 : 55 : std::vector<bilingual_str> warnings;
579 : :
580 [ - + ]: 55 : DatabaseOptions options;
581 : 55 : options.require_existing = true;
582 : 55 : DatabaseStatus status;
583 : :
584 [ - + ]: 55 : const std::string wallet_name = local_wallet->GetName();
585 : :
586 : : // Before anything else, check if there is something to migrate.
587 [ + - - + ]: 55 : if (local_wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
588 [ # # ]: 0 : return util::Error{_("Error: This wallet is already a descriptor wallet")};
589 : : }
590 : :
591 : : // Make a backup of the DB in the wallet's directory with a unique filename
592 : : // using the wallet name and current timestamp. The backup filename is based
593 : : // on the name of the parent directory containing the wallet data in most
594 : : // cases, but in the case where the wallet name is a path to a data file,
595 : : // the name of the data file is used, and in the case where the wallet name
596 : : // is blank, "default_wallet" is used.
597 [ + - ]: 55 : const std::string backup_prefix = MigrationFilePrefix(*local_wallet);
598 : :
599 [ + - + - : 55 : fs::path backup_filename = fs::PathFromString(strprintf("%s_%d.legacy.bak", backup_prefix, GetTime()));
+ - ]
600 [ + - + - ]: 55 : fs::path backup_path = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
601 [ - + + - : 110 : if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {
- + ]
602 [ # # ]: 0 : return util::Error{_("Error: Unable to make a backup of your wallet")};
603 : : }
604 [ + - ]: 55 : res.backup_path = backup_path;
605 : :
606 : 55 : bool success = false;
607 : :
608 : : // Unlock the wallet if needed
609 [ + - + + ]: 55 : if (local_wallet->IsLocked()) {
610 [ + - + + : 15 : if (auto unlocked{local_wallet->Unlock(passphrase)}; !unlocked) return util::Error{unlocked.error().message};
+ - ]
611 : : }
612 : :
613 : : // Indicates whether the current wallet is empty after migration.
614 : : // Notes:
615 : : // When non-empty: the local wallet becomes the main spendable wallet.
616 : : // When empty: The local wallet is excluded from the result, as the
617 : : // user does not expect an empty spendable wallet after
618 : : // migrating only watch-only scripts.
619 : 52 : bool empty_local_wallet = false;
620 : :
621 : 52 : try {
622 [ + - ]: 52 : LOCK(local_wallet->cs_wallet);
623 : : // First change to using SQLite
624 [ + + - + : 52 : if (!local_wallet->MigrateToSQLite(error)) return util::Error{error};
- - - - ]
625 : :
626 : : // Do the migration of keys and scripts for non-empty wallets, and cleanup if it fails
627 [ + - + + ]: 50 : if (HasLegacyRecords(*local_wallet)) {
628 [ + - ]: 47 : success = DoMigration(*local_wallet, context, error, res, load_wallet);
629 : : // No scripts mean empty wallet after migration
630 [ + - ]: 47 : empty_local_wallet = local_wallet->GetAllScriptPubKeyMans().empty();
631 : : } else {
632 : : // Make sure that descriptors flag is actually set
633 [ + - ]: 3 : local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
634 : : success = true;
635 : : }
636 [ - + ]: 52 : } catch (const std::exception& e) {
637 [ + - + - ]: 4 : error = Untranslated(strprintf("Migration failed: %s", e.what()));
638 : 2 : }
639 : :
640 : : // In case of loading failure, we need to remember the wallet files we have created to remove.
641 : : // A `set` is used as it may be populated with the same wallet directory paths multiple times,
642 : : // both before and after loading. This ensures the set is complete even if one of the wallets
643 : : // fails to load.
644 [ + + ]: 52 : std::set<fs::path> wallet_files_to_remove;
645 : 52 : std::set<fs::path> wallet_empty_dirs_to_remove;
646 : :
647 : : // Helper to track wallet files and directories for cleanup on failure.
648 : : // Only directories of wallets created during migration (not the main wallet) are tracked.
649 : 120 : auto track_for_cleanup = [&](const CWallet& wallet) {
650 : 68 : const auto files = wallet.GetDatabase().Files();
651 [ + - ]: 68 : wallet_files_to_remove.insert(files.begin(), files.end());
652 [ + + ]: 68 : if (wallet.GetName() != wallet_name) {
653 : : // If this isn’t the main wallet, mark its directory for removal.
654 : : // This applies to the watch-only and solvable wallets.
655 : : // Wallets stored directly as files in the top-level directory
656 : : // (e.g. default unnamed wallets) don’t have a removable parent directory.
657 [ + - + - : 95 : wallet_empty_dirs_to_remove.insert(fs::PathFromString(wallet.GetDatabase().Filename()).parent_path());
+ - + - ]
658 : : }
659 : 68 : };
660 : :
661 : :
662 [ + + ]: 52 : if (success) {
663 [ + + ]: 46 : Assume(!res.wallet); // We will set it here.
664 : : // Check if the local wallet is empty after migration
665 [ + + ]: 46 : if (empty_local_wallet) {
666 : : // This wallet has no records. We can safely remove it.
667 [ + - ]: 3 : std::vector<fs::path> paths_to_remove = local_wallet->GetDatabase().Files();
668 : 3 : local_wallet.reset();
669 [ + - + + ]: 9 : for (const auto& path_to_remove : paths_to_remove) fs::remove(path_to_remove);
670 : 3 : }
671 : :
672 [ + + ]: 46 : if (load_wallet) {
673 [ + - ]: 42 : LogInfo("Loading new wallets after migration...\n");
674 : : /** We only override the load_on_startup setting in case the user explicitly said
675 : : * that he does not want to load the wallet, otherwise keep the old wallet configuration */
676 : : } else {
677 [ + - ]: 4 : UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/false, warnings);
678 : : }
679 : : // Migration successful, if load_wallet is set load all the migrated wallets.
680 : 46 : bool main_wallet_set{false};
681 [ + + ]: 178 : for (std::shared_ptr<CWallet>* wallet_ptr : {&local_wallet, &res.watchonly_wallet, &res.solvables_wallet}) {
682 [ + + ]: 134 : if (success && *wallet_ptr) {
683 : 61 : std::shared_ptr<CWallet>& wallet = *wallet_ptr;
684 : : // Track db path
685 [ + - ]: 61 : track_for_cleanup(*wallet);
686 [ - + ]: 61 : assert(wallet.use_count() == 1);
687 [ - + ]: 61 : std::string wallet_name = wallet->GetName();
688 : 61 : wallet.reset();
689 [ + + ]: 61 : if (load_wallet) {
690 [ + - - + ]: 110 : wallet = LoadWallet(context, wallet_name, /*load_on_start=*/std::nullopt, options, status, error, warnings);
691 [ + + ]: 55 : if (!wallet) {
692 [ + - ]: 2 : LogError("Failed to load wallet '%s' after migration. Rolling back migration to preserve consistency. "
693 : : "Error cause: %s\n", wallet_name, error.original);
694 : 2 : success = false;
695 : 2 : break;
696 : : }
697 : : }
698 : : // Set the first wallet as the main one.
699 : : // The loop order is intentional and must always start with the local wallet.
700 [ + + ]: 59 : if (!main_wallet_set) {
701 [ + - ]: 44 : res.wallet_name = wallet_name;
702 [ + + ]: 44 : if (load_wallet) res.wallet = std::move(wallet);
703 : : main_wallet_set = true;
704 : : }
705 [ + + ]: 59 : if (wallet_ptr == &res.watchonly_wallet) {
706 [ + - ]: 12 : res.watchonly_wallet_name = wallet_name;
707 [ + + ]: 47 : } else if (wallet_ptr == &res.solvables_wallet) {
708 [ + - ]: 6 : res.solvables_wallet_name = wallet_name;
709 : : }
710 : 59 : }
711 : : }
712 : : }
713 : 2 : if (!success) {
714 : : // Make list of wallets to cleanup
715 : 8 : std::vector<std::shared_ptr<CWallet>> created_wallets;
716 [ + + + - ]: 8 : if (local_wallet) created_wallets.push_back(std::move(local_wallet));
717 [ + + + - ]: 8 : if (res.watchonly_wallet) created_wallets.push_back(std::move(res.watchonly_wallet));
718 [ - + - - ]: 8 : if (res.solvables_wallet) created_wallets.push_back(std::move(res.solvables_wallet));
719 : :
720 : : // Get the directories to remove after unloading
721 [ + + ]: 15 : for (std::shared_ptr<CWallet>& wallet : created_wallets) {
722 [ + - ]: 7 : track_for_cleanup(*wallet);
723 : : }
724 : :
725 : : // Unload the wallets
726 [ + + ]: 15 : for (std::shared_ptr<CWallet>& w : created_wallets) {
727 [ - + ]: 7 : if (w->HaveChain()) {
728 : : // Unloading for wallets that were loaded for normal use
729 [ # # # # ]: 0 : if (!RemoveWallet(context, w, /*load_on_start=*/false)) {
730 [ # # # # ]: 0 : error += _("\nUnable to cleanup failed migration");
731 [ # # ]: 0 : return util::Error{error};
732 : : }
733 [ # # ]: 0 : WaitForDeleteWallet(std::move(w));
734 : : } else {
735 : : // Unloading for wallets in local context
736 [ - + ]: 7 : assert(w.use_count() == 1);
737 : 7 : w.reset();
738 : : }
739 : : }
740 : :
741 : : // First, delete the db files we have created throughout this process and nothing else
742 [ + + ]: 24 : for (const fs::path& file : wallet_files_to_remove) {
743 [ + - ]: 16 : fs::remove(file);
744 : : }
745 : :
746 : : // Second, delete the created wallet directories and nothing else. They must be empty at this point.
747 [ + + ]: 9 : for (const fs::path& dir : wallet_empty_dirs_to_remove) {
748 [ + - + - ]: 1 : Assume(fs::is_empty(dir));
749 [ + - ]: 1 : fs::remove(dir);
750 : : }
751 : :
752 : : // Restore the backup
753 : : // Convert the backup file to the wallet db file by renaming it and moving it into the wallet's directory.
754 [ + - ]: 8 : bilingual_str restore_error;
755 [ + - ]: 8 : const auto& ptr_wallet = RestoreWallet(context, backup_path, wallet_name, /*load_on_start=*/std::nullopt, status, restore_error, warnings, /*load_after_restore=*/false, /*allow_unnamed=*/true);
756 [ - + ]: 8 : if (!restore_error.empty()) {
757 [ # # # # ]: 0 : error += restore_error + _("\nUnable to restore backup of wallet.");
758 [ # # ]: 0 : return util::Error{error};
759 : : }
760 : : // Verify that the legacy wallet is not loaded after restoring from the backup.
761 [ - + ]: 8 : assert(!ptr_wallet);
762 : :
763 [ + - ]: 24 : return util::Error{error};
764 : 16 : }
765 : 44 : return res;
766 : 272 : }
767 : :
768 : : } // namespace wallet
|