Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <bitcoin-build-config.h> // IWYU pragma: keep
7 : :
8 : : #include <wallet/walletdb.h>
9 : :
10 : : #include <common/system.h>
11 : : #include <key_io.h>
12 : : #include <primitives/transaction_identifier.h>
13 : : #include <protocol.h>
14 : : #include <script/script.h>
15 : : #include <serialize.h>
16 : : #include <sync.h>
17 : : #include <util/bip32.h>
18 : : #include <util/check.h>
19 : : #include <util/fs.h>
20 : : #include <util/time.h>
21 : : #include <util/translation.h>
22 : : #include <wallet/migrate.h>
23 : : #include <wallet/sqlite.h>
24 : : #include <wallet/wallet.h>
25 : :
26 : : #include <atomic>
27 : : #include <optional>
28 : : #include <string>
29 : :
30 : : namespace wallet {
31 : : namespace DBKeys {
32 : : const std::string ACENTRY{"acentry"};
33 : : const std::string ACTIVEEXTERNALSPK{"activeexternalspk"};
34 : : const std::string ACTIVEINTERNALSPK{"activeinternalspk"};
35 : : const std::string BESTBLOCK_NOMERKLE{"bestblock_nomerkle"};
36 : : const std::string BESTBLOCK{"bestblock"};
37 : : const std::string CRYPTED_KEY{"ckey"};
38 : : const std::string CSCRIPT{"cscript"};
39 : : const std::string DEFAULTKEY{"defaultkey"};
40 : : const std::string DESTDATA{"destdata"};
41 : : const std::string FLAGS{"flags"};
42 : : const std::string HDCHAIN{"hdchain"};
43 : : const std::string KEYMETA{"keymeta"};
44 : : const std::string KEY{"key"};
45 : : const std::string LOCKED_UTXO{"lockedutxo"};
46 : : const std::string MASTER_KEY{"mkey"};
47 : : const std::string MINVERSION{"minversion"};
48 : : const std::string NAME{"name"};
49 : : const std::string OLD_KEY{"wkey"};
50 : : const std::string ORDERPOSNEXT{"orderposnext"};
51 : : const std::string POOL{"pool"};
52 : : const std::string PURPOSE{"purpose"};
53 : : const std::string SETTINGS{"settings"};
54 : : const std::string TX{"tx"};
55 : : const std::string VERSION{"version"};
56 : : const std::string WALLETDESCRIPTOR{"walletdescriptor"};
57 : : const std::string WALLETDESCRIPTORCACHE{"walletdescriptorcache"};
58 : : const std::string WALLETDESCRIPTORLHCACHE{"walletdescriptorlhcache"};
59 : : const std::string WALLETDESCRIPTORCKEY{"walletdescriptorckey"};
60 : : const std::string WALLETDESCRIPTORKEY{"walletdescriptorkey"};
61 : : const std::string WATCHMETA{"watchmeta"};
62 : : const std::string WATCHS{"watchs"};
63 : : const std::unordered_set<std::string> LEGACY_TYPES{CRYPTED_KEY, CSCRIPT, DEFAULTKEY, HDCHAIN, KEYMETA, KEY, OLD_KEY, POOL, WATCHMETA, WATCHS};
64 : : } // namespace DBKeys
65 : :
66 : 5 : void LogDBInfo()
67 : : {
68 : : // Add useful DB information here. This will be printed during startup.
69 [ + - ]: 5 : LogInfo("Using SQLite Version %s", SQLiteDatabaseVersion());
70 : 5 : }
71 : :
72 : : //
73 : : // WalletBatch
74 : : //
75 : :
76 : 6251 : bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
77 : : {
78 [ + - ]: 18753 : return WriteIC(std::make_pair(DBKeys::NAME, strAddress), strName);
79 : : }
80 : :
81 : 0 : bool WalletBatch::EraseName(const std::string& strAddress)
82 : : {
83 : : // This should only be used for sending addresses, never for receiving addresses,
84 : : // receiving addresses must always have an address book entry if they're not change return.
85 [ # # ]: 0 : return EraseIC(std::make_pair(DBKeys::NAME, strAddress));
86 : : }
87 : :
88 : 6251 : bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
89 : : {
90 [ + - ]: 18753 : return WriteIC(std::make_pair(DBKeys::PURPOSE, strAddress), strPurpose);
91 : : }
92 : :
93 : 0 : bool WalletBatch::ErasePurpose(const std::string& strAddress)
94 : : {
95 [ # # ]: 0 : return EraseIC(std::make_pair(DBKeys::PURPOSE, strAddress));
96 : : }
97 : :
98 : 426 : bool WalletBatch::WriteTx(const CWalletTx& wtx)
99 : : {
100 [ + - ]: 852 : return WriteIC(std::make_pair(DBKeys::TX, wtx.GetHash()), wtx);
101 : : }
102 : :
103 : 1 : bool WalletBatch::EraseTx(Txid hash)
104 : : {
105 [ + - ]: 2 : return EraseIC(std::make_pair(DBKeys::TX, hash.ToUint256()));
106 : : }
107 : :
108 : 0 : bool WalletBatch::WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite)
109 : : {
110 [ # # ]: 0 : return WriteIC(std::make_pair(DBKeys::KEYMETA, pubkey), meta, overwrite);
111 : : }
112 : :
113 : 0 : bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
114 : : {
115 [ # # ]: 0 : if (!WriteKeyMetadata(keyMeta, vchPubKey, false)) {
116 : : return false;
117 : : }
118 : :
119 : : // hash pubkey/privkey to accelerate wallet load
120 : 0 : const auto keypair_hash = Hash(vchPubKey, vchPrivKey);
121 : :
122 [ # # # # ]: 0 : return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, keypair_hash), false);
123 : : }
124 : :
125 : 0 : bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
126 : : const std::vector<unsigned char>& vchCryptedSecret,
127 : : const CKeyMetadata &keyMeta)
128 : : {
129 [ # # ]: 0 : if (!WriteKeyMetadata(keyMeta, vchPubKey, true)) {
130 : : return false;
131 : : }
132 : :
133 : : // Compute a checksum of the encrypted key
134 : 0 : uint256 checksum = Hash(vchCryptedSecret);
135 : :
136 : 0 : const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey);
137 [ # # # # : 0 : if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) {
# # ]
138 : : // It may already exist, so try writing just the checksum
139 : 0 : std::vector<unsigned char> val;
140 [ # # # # ]: 0 : if (!m_batch->Read(key, val)) {
141 : : return false;
142 : : }
143 [ # # # # : 0 : if (!WriteIC(key, std::make_pair(val, checksum), true)) {
# # ]
144 : : return false;
145 : : }
146 : 0 : }
147 [ # # # # ]: 0 : EraseIC(std::make_pair(DBKeys::KEY, vchPubKey));
148 : 0 : return true;
149 : 0 : }
150 : :
151 : 0 : bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
152 : : {
153 [ # # # # ]: 0 : return WriteIC(std::make_pair(DBKeys::MASTER_KEY, nID), kMasterKey, true);
154 : : }
155 : :
156 : 0 : bool WalletBatch::EraseMasterKey(unsigned int id)
157 : : {
158 [ # # # # ]: 0 : return EraseIC(std::make_pair(DBKeys::MASTER_KEY, id));
159 : : }
160 : :
161 : 0 : bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
162 : : {
163 [ # # # # ]: 0 : if (!WriteIC(std::make_pair(DBKeys::WATCHMETA, dest), keyMeta)) {
164 : : return false;
165 : : }
166 [ # # ]: 0 : return WriteIC(std::make_pair(DBKeys::WATCHS, dest), uint8_t{'1'});
167 : : }
168 : :
169 : 0 : bool WalletBatch::EraseWatchOnly(const CScript &dest)
170 : : {
171 [ # # # # ]: 0 : if (!EraseIC(std::make_pair(DBKeys::WATCHMETA, dest))) {
172 : : return false;
173 : : }
174 [ # # ]: 0 : return EraseIC(std::make_pair(DBKeys::WATCHS, dest));
175 : : }
176 : :
177 : 21 : bool WalletBatch::WriteBestBlock(const CBlockLocator& locator)
178 : : {
179 [ + - ]: 21 : WriteIC(DBKeys::BESTBLOCK, CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
180 : 42 : return WriteIC(DBKeys::BESTBLOCK_NOMERKLE, locator);
181 : : }
182 : :
183 : 10 : bool WalletBatch::ReadBestBlock(CBlockLocator& locator)
184 : : {
185 [ + - + - ]: 10 : if (m_batch->Read(DBKeys::BESTBLOCK, locator) && !locator.vHave.empty()) return true;
186 : 10 : return m_batch->Read(DBKeys::BESTBLOCK_NOMERKLE, locator);
187 : : }
188 : :
189 : 0 : bool WalletBatch::IsEncrypted()
190 : : {
191 : 0 : DataStream prefix;
192 [ # # ]: 0 : prefix << DBKeys::MASTER_KEY;
193 [ # # # # : 0 : if (auto cursor = m_batch->GetNewPrefixCursor(prefix)) {
# # ]
194 : 0 : DataStream k, v;
195 [ # # # # ]: 0 : if (cursor->Next(k, v) == DatabaseCursor::Status::MORE) return true;
196 : 0 : }
197 : 0 : return false;
198 : 0 : }
199 : :
200 : 425 : bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
201 : : {
202 : 425 : return WriteIC(DBKeys::ORDERPOSNEXT, nOrderPosNext);
203 : : }
204 : :
205 : 273 : bool WalletBatch::WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal)
206 : : {
207 [ + + ]: 273 : std::string key = internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK;
208 [ - + + - ]: 819 : return WriteIC(make_pair(key, type), id);
209 : 273 : }
210 : :
211 : 0 : bool WalletBatch::EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
212 : : {
213 [ # # ]: 0 : const std::string key{internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK};
214 [ # # # # ]: 0 : return EraseIC(make_pair(key, type));
215 : 0 : }
216 : :
217 : 303 : bool WalletBatch::WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey)
218 : : {
219 : : // hash pubkey/privkey to accelerate wallet load
220 : 303 : const auto keypair_hash = Hash(pubkey, privkey);
221 : :
222 [ + - + - ]: 606 : return WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)), std::make_pair(privkey, keypair_hash), false);
223 : : }
224 : :
225 : 0 : bool WalletBatch::WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret)
226 : : {
227 [ # # # # ]: 0 : if (!WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORCKEY, std::make_pair(desc_id, pubkey)), secret, false)) {
228 : : return false;
229 : : }
230 [ # # ]: 0 : EraseIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)));
231 : 0 : return true;
232 : : }
233 : :
234 : 13496 : bool WalletBatch::WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor)
235 : : {
236 [ + - ]: 26992 : return WriteIC(make_pair(DBKeys::WALLETDESCRIPTOR, desc_id), descriptor);
237 : : }
238 : :
239 : 1000 : bool WalletBatch::WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index)
240 : : {
241 : 1000 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
242 [ + - ]: 1000 : xpub.Encode(ser_xpub.data());
243 [ + - + - ]: 2000 : return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), std::make_pair(key_exp_index, der_index)), ser_xpub);
244 : 1000 : }
245 : :
246 : 276 : bool WalletBatch::WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
247 : : {
248 : 276 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
249 [ + - ]: 276 : xpub.Encode(ser_xpub.data());
250 [ + - + - ]: 552 : return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), key_exp_index), ser_xpub);
251 : 276 : }
252 : :
253 : 276 : bool WalletBatch::WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
254 : : {
255 : 276 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
256 [ + - ]: 276 : xpub.Encode(ser_xpub.data());
257 [ + - + - ]: 552 : return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORLHCACHE, desc_id), key_exp_index), ser_xpub);
258 : 276 : }
259 : :
260 : 279212 : bool WalletBatch::WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache)
261 : : {
262 [ + + + - ]: 279488 : for (const auto& parent_xpub_pair : cache.GetCachedParentExtPubKeys()) {
263 [ - + + - ]: 276 : if (!WriteDescriptorParentCache(parent_xpub_pair.second, desc_id, parent_xpub_pair.first)) {
264 : 0 : return false;
265 : : }
266 : 0 : }
267 [ + + ]: 280212 : for (const auto& derived_xpub_map_pair : cache.GetCachedDerivedExtPubKeys()) {
268 [ + + + - ]: 2000 : for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
269 [ - + + - ]: 1000 : if (!WriteDescriptorDerivedCache(derived_xpub_pair.second, desc_id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
270 : 0 : return false;
271 : : }
272 : : }
273 : 0 : }
274 [ + + + - ]: 279488 : for (const auto& lh_xpub_pair : cache.GetCachedLastHardenedExtPubKeys()) {
275 [ - + + - ]: 276 : if (!WriteDescriptorLastHardenedCache(lh_xpub_pair.second, desc_id, lh_xpub_pair.first)) {
276 : 0 : return false;
277 : : }
278 : 0 : }
279 : 279212 : return true;
280 : : }
281 : :
282 : 0 : bool WalletBatch::WriteLockedUTXO(const COutPoint& output)
283 : : {
284 [ # # ]: 0 : return WriteIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)), uint8_t{'1'});
285 : : }
286 : :
287 : 0 : bool WalletBatch::EraseLockedUTXO(const COutPoint& output)
288 : : {
289 [ # # ]: 0 : return EraseIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)));
290 : : }
291 : :
292 : 0 : bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
293 : : {
294 : 0 : LOCK(pwallet->cs_wallet);
295 : 0 : try {
296 [ # # ]: 0 : CPubKey vchPubKey;
297 [ # # ]: 0 : ssKey >> vchPubKey;
298 [ # # ]: 0 : if (!vchPubKey.IsValid())
299 : : {
300 [ # # # # ]: 0 : strErr = "Error reading wallet database: CPubKey corrupt";
301 : : return false;
302 : : }
303 : 0 : CKey key;
304 : 0 : CPrivKey pkey;
305 : 0 : uint256 hash;
306 : :
307 [ # # ]: 0 : ssValue >> pkey;
308 : :
309 : : // Old wallets store keys as DBKeys::KEY [pubkey] => [privkey]
310 : : // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
311 : : // using EC operations as a checksum.
312 : : // Newer wallets store keys as DBKeys::KEY [pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
313 : : // remaining backwards-compatible.
314 : 0 : try
315 : : {
316 [ # # ]: 0 : ssValue >> hash;
317 : : }
318 [ - - ]: 0 : catch (const std::ios_base::failure&) {}
319 : :
320 : 0 : bool fSkipCheck = false;
321 : :
322 [ # # ]: 0 : if (!hash.IsNull())
323 : : {
324 : : // hash pubkey/privkey to accelerate wallet load
325 [ # # ]: 0 : const auto keypair_hash = Hash(vchPubKey, pkey);
326 : :
327 [ # # ]: 0 : if (keypair_hash != hash)
328 : : {
329 [ # # ]: 0 : strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
330 : : return false;
331 : : }
332 : :
333 : : fSkipCheck = true;
334 : : }
335 : :
336 [ # # # # ]: 0 : if (!key.Load(pkey, vchPubKey, fSkipCheck))
337 : : {
338 [ # # ]: 0 : strErr = "Error reading wallet database: CPrivKey corrupt";
339 : : return false;
340 : : }
341 [ # # # # : 0 : if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadKey(key, vchPubKey))
# # ]
342 : : {
343 [ # # ]: 0 : strErr = "Error reading wallet database: LegacyDataSPKM::LoadKey failed";
344 : : return false;
345 : : }
346 [ # # ]: 0 : } catch (const std::exception& e) {
347 [ - - ]: 0 : if (strErr.empty()) {
348 [ - - ]: 0 : strErr = e.what();
349 : : }
350 : 0 : return false;
351 : 0 : }
352 : 0 : return true;
353 : 0 : }
354 : :
355 : 0 : bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
356 : : {
357 : 0 : LOCK(pwallet->cs_wallet);
358 : 0 : try {
359 [ # # ]: 0 : CPubKey vchPubKey;
360 [ # # ]: 0 : ssKey >> vchPubKey;
361 [ # # ]: 0 : if (!vchPubKey.IsValid())
362 : : {
363 [ # # # # ]: 0 : strErr = "Error reading wallet database: CPubKey corrupt";
364 : : return false;
365 : : }
366 : 0 : std::vector<unsigned char> vchPrivKey;
367 [ # # ]: 0 : ssValue >> vchPrivKey;
368 : :
369 : : // Get the checksum and check it
370 : 0 : bool checksum_valid = false;
371 [ # # # # ]: 0 : if (!ssValue.empty()) {
372 : 0 : uint256 checksum;
373 [ # # ]: 0 : ssValue >> checksum;
374 [ # # # # ]: 0 : if (!(checksum_valid = Hash(vchPrivKey) == checksum)) {
375 [ # # ]: 0 : strErr = "Error reading wallet database: Encrypted key corrupt";
376 : : return false;
377 : : }
378 : : }
379 : :
380 [ # # # # : 0 : if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCryptedKey(vchPubKey, vchPrivKey, checksum_valid))
# # ]
381 : : {
382 [ # # ]: 0 : strErr = "Error reading wallet database: LegacyDataSPKM::LoadCryptedKey failed";
383 : : return false;
384 : : }
385 [ # # ]: 0 : } catch (const std::exception& e) {
386 [ - - ]: 0 : if (strErr.empty()) {
387 [ - - ]: 0 : strErr = e.what();
388 : : }
389 : 0 : return false;
390 : 0 : }
391 : 0 : return true;
392 : 0 : }
393 : :
394 : 0 : bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
395 : : {
396 : 0 : LOCK(pwallet->cs_wallet);
397 : 0 : try {
398 : : // Master encryption key is loaded into only the wallet and not any of the ScriptPubKeyMans.
399 : 0 : unsigned int nID;
400 [ # # ]: 0 : ssKey >> nID;
401 [ # # ]: 0 : CMasterKey kMasterKey;
402 [ # # ]: 0 : ssValue >> kMasterKey;
403 [ # # ]: 0 : if(pwallet->mapMasterKeys.contains(nID))
404 : : {
405 [ # # ]: 0 : strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
406 : 0 : return false;
407 : : }
408 [ # # # # ]: 0 : pwallet->mapMasterKeys[nID] = kMasterKey;
409 [ # # ]: 0 : if (pwallet->nMasterKeyMaxID < nID)
410 : 0 : pwallet->nMasterKeyMaxID = nID;
411 : :
412 [ # # ]: 0 : } catch (const std::exception& e) {
413 [ - - ]: 0 : if (strErr.empty()) {
414 [ - - ]: 0 : strErr = e.what();
415 : : }
416 : 0 : return false;
417 : 0 : }
418 : 0 : return true;
419 : 0 : }
420 : :
421 : 0 : bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr)
422 : : {
423 : 0 : LOCK(pwallet->cs_wallet);
424 : 0 : try {
425 : 0 : CHDChain chain;
426 [ # # ]: 0 : ssValue >> chain;
427 [ # # # # ]: 0 : pwallet->GetOrCreateLegacyDataSPKM()->LoadHDChain(chain);
428 [ - - ]: 0 : } catch (const std::exception& e) {
429 [ - - ]: 0 : if (strErr.empty()) {
430 [ - - ]: 0 : strErr = e.what();
431 : : }
432 : 0 : return false;
433 : 0 : }
434 : : return true;
435 : 0 : }
436 : :
437 : 7 : static DBErrors LoadWalletFlags(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
438 : : {
439 : 7 : AssertLockHeld(pwallet->cs_wallet);
440 : 7 : uint64_t flags;
441 [ + + ]: 7 : if (batch.Read(DBKeys::FLAGS, flags)) {
442 [ - + ]: 2 : if (!pwallet->LoadWalletFlags(flags)) {
443 : 0 : pwallet->WalletLogPrintf("Error reading wallet database: Unknown non-tolerable wallet flags found\n");
444 : 0 : return DBErrors::TOO_NEW;
445 : : }
446 : : // All wallets must be descriptor wallets unless opened with a bdb_ro db
447 : : // bdb_ro is only used for legacy to descriptor migration.
448 [ + - + - : 4 : if (pwallet->GetDatabase().Format() != "bdb_ro" && !pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
+ - - + ]
449 : 0 : return DBErrors::LEGACY_WALLET;
450 : : }
451 : : }
452 : : return DBErrors::LOAD_OK;
453 : : }
454 : :
455 : : struct LoadResult
456 : : {
457 : : DBErrors m_result{DBErrors::LOAD_OK};
458 : : int m_records{0};
459 : : };
460 : :
461 : : using LoadFunc = std::function<DBErrors(CWallet* pwallet, DataStream& key, DataStream& value, std::string& err)>;
462 : 178 : static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, DataStream& prefix, LoadFunc load_func)
463 : : {
464 : 178 : LoadResult result;
465 : 178 : DataStream ssKey;
466 : 178 : DataStream ssValue{};
467 : :
468 [ - + + - ]: 178 : Assume(!prefix.empty());
469 [ + - ]: 178 : std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
470 [ - + ]: 178 : if (!cursor) {
471 [ # # ]: 0 : pwallet->WalletLogPrintf("Error getting database cursor for '%s' records\n", key);
472 : 0 : result.m_result = DBErrors::CORRUPT;
473 : 0 : return result;
474 : : }
475 : :
476 : 390 : while (true) {
477 [ + - ]: 284 : DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
478 [ + + ]: 284 : if (status == DatabaseCursor::Status::DONE) {
479 : : break;
480 [ - + ]: 106 : } else if (status == DatabaseCursor::Status::FAIL) {
481 [ # # ]: 0 : pwallet->WalletLogPrintf("Error reading next '%s' record for wallet database\n", key);
482 : 0 : result.m_result = DBErrors::CORRUPT;
483 : 0 : return result;
484 : : }
485 [ + - ]: 106 : std::string type;
486 [ + - ]: 106 : ssKey >> type;
487 [ - + ]: 106 : assert(type == key);
488 [ + - ]: 106 : std::string error;
489 [ + - ]: 106 : DBErrors record_res = load_func(pwallet, ssKey, ssValue, error);
490 [ + + ]: 106 : if (record_res != DBErrors::LOAD_OK) {
491 [ + - ]: 2 : pwallet->WalletLogPrintf("%s\n", error);
492 : : }
493 [ + + ]: 106 : result.m_result = std::max(result.m_result, record_res);
494 : 106 : ++result.m_records;
495 : 106 : }
496 : 178 : return result;
497 : 178 : }
498 : :
499 : 106 : static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, LoadFunc load_func)
500 : : {
501 : 106 : DataStream prefix;
502 [ + - ]: 106 : prefix << key;
503 [ + - + - ]: 212 : return LoadRecords(pwallet, batch, key, prefix, load_func);
504 : 106 : }
505 : :
506 : 0 : bool HasLegacyRecords(CWallet& wallet)
507 : : {
508 : 0 : const auto& batch = wallet.GetDatabase().MakeBatch();
509 [ # # ]: 0 : return HasLegacyRecords(wallet, *batch);
510 : : }
511 : :
512 : 2 : bool HasLegacyRecords(CWallet& wallet, DatabaseBatch& batch)
513 : : {
514 [ + + + - ]: 22 : for (const auto& type : DBKeys::LEGACY_TYPES) {
515 : 20 : DataStream key;
516 : 20 : DataStream value{};
517 : 20 : DataStream prefix;
518 : :
519 [ + - ]: 20 : prefix << type;
520 [ - + + - ]: 20 : std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
521 [ - + ]: 20 : if (!cursor) {
522 : : // Could only happen on a closed db, which means there is an error in the code flow.
523 [ # # # # ]: 0 : throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", type));
524 : : }
525 : :
526 [ + - ]: 20 : DatabaseCursor::Status status = cursor->Next(key, value);
527 [ - + ]: 20 : if (status != DatabaseCursor::Status::DONE) {
528 : 0 : return true;
529 : : }
530 : 20 : }
531 : : return false;
532 : : }
533 : :
534 : 7 : static DBErrors LoadLegacyWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
535 : : {
536 : 7 : AssertLockHeld(pwallet->cs_wallet);
537 : 7 : DBErrors result = DBErrors::LOAD_OK;
538 : :
539 : : // Make sure descriptor wallets don't have any legacy records
540 [ + + ]: 7 : if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
541 [ - + ]: 2 : if (HasLegacyRecords(*pwallet, batch)) {
542 : 0 : pwallet->WalletLogPrintf("Error: Unexpected legacy entry found in descriptor wallet %s. The wallet might have been tampered with or created with malicious intent.\n", pwallet->GetName());
543 : 0 : return DBErrors::UNEXPECTED_LEGACY_ENTRY;
544 : : }
545 : :
546 : : return DBErrors::LOAD_OK;
547 : : }
548 : :
549 : : // Load HD Chain
550 : : // Note: There should only be one HDCHAIN record with no data following the type
551 [ + - ]: 5 : LoadResult hd_chain_res = LoadRecords(pwallet, batch, DBKeys::HDCHAIN,
552 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
553 [ # # ]: 0 : return LoadHDChain(pwallet, value, err) ? DBErrors:: LOAD_OK : DBErrors::CORRUPT;
554 : : });
555 [ + - ]: 5 : result = std::max(result, hd_chain_res.m_result);
556 : :
557 : : // Load unencrypted keys
558 [ + - ]: 5 : LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::KEY,
559 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
560 [ # # ]: 0 : return LoadKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
561 : : });
562 [ + - ]: 5 : result = std::max(result, key_res.m_result);
563 : :
564 : : // Load encrypted keys
565 [ + - ]: 5 : LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::CRYPTED_KEY,
566 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
567 [ # # ]: 0 : return LoadCryptedKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
568 : : });
569 [ + - ]: 5 : result = std::max(result, ckey_res.m_result);
570 : :
571 : : // Load scripts
572 [ + - ]: 5 : LoadResult script_res = LoadRecords(pwallet, batch, DBKeys::CSCRIPT,
573 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
574 : 0 : uint160 hash;
575 : 0 : key >> hash;
576 : 0 : CScript script;
577 [ # # ]: 0 : value >> script;
578 [ # # # # : 0 : if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCScript(script))
# # ]
579 : : {
580 [ # # ]: 0 : strErr = "Error reading wallet database: LegacyDataSPKM::LoadCScript failed";
581 : : return DBErrors::NONCRITICAL_ERROR;
582 : : }
583 : : return DBErrors::LOAD_OK;
584 : 0 : });
585 [ + - ]: 5 : result = std::max(result, script_res.m_result);
586 : :
587 : : // Load keymeta
588 [ + - ]: 5 : std::map<uint160, CHDChain> hd_chains;
589 : 5 : LoadResult keymeta_res = LoadRecords(pwallet, batch, DBKeys::KEYMETA,
590 [ + - ]: 5 : [&hd_chains] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
591 : 0 : CPubKey vchPubKey;
592 : 0 : key >> vchPubKey;
593 : 0 : CKeyMetadata keyMeta;
594 [ # # ]: 0 : value >> keyMeta;
595 [ # # # # : 0 : pwallet->GetOrCreateLegacyDataSPKM()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
# # ]
596 : :
597 : : // Extract some CHDChain info from this metadata if it has any
598 [ # # # # : 0 : if (keyMeta.nVersion >= CKeyMetadata::VERSION_WITH_HDDATA && !keyMeta.hd_seed_id.IsNull() && keyMeta.hdKeypath.size() > 0) {
# # ]
599 : : // Get the path from the key origin or from the path string
600 : : // Not applicable when path is "s" or "m" as those indicate a seed
601 : : // See https://github.com/bitcoin/bitcoin/pull/12924
602 : 0 : bool internal = false;
603 : 0 : uint32_t index = 0;
604 [ # # # # ]: 0 : if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
605 : 0 : std::vector<uint32_t> path;
606 [ # # ]: 0 : if (keyMeta.has_key_origin) {
607 : : // We have a key origin, so pull it from its path vector
608 [ # # ]: 0 : path = keyMeta.key_origin.path;
609 : : } else {
610 : : // No key origin, have to parse the string
611 [ # # # # ]: 0 : if (!ParseHDKeypath(keyMeta.hdKeypath, path)) {
612 [ # # ]: 0 : strErr = "Error reading wallet database: keymeta with invalid HD keypath";
613 : : return DBErrors::NONCRITICAL_ERROR;
614 : : }
615 : : }
616 : :
617 : : // Extract the index and internal from the path
618 : : // Path string is m/0'/k'/i'
619 : : // Path vector is [0', k', i'] (but as ints OR'd with the hardened bit
620 : : // k == 0 for external, 1 for internal. i is the index
621 [ # # # # ]: 0 : if (path.size() != 3) {
622 [ # # ]: 0 : strErr = "Error reading wallet database: keymeta found with unexpected path";
623 : : return DBErrors::NONCRITICAL_ERROR;
624 : : }
625 [ # # ]: 0 : if (path[0] != 0x80000000) {
626 [ # # ]: 0 : strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
627 : 0 : return DBErrors::NONCRITICAL_ERROR;
628 : : }
629 [ # # # # ]: 0 : if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
630 [ # # ]: 0 : strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
631 : 0 : return DBErrors::NONCRITICAL_ERROR;
632 : : }
633 [ # # ]: 0 : if ((path[2] & 0x80000000) == 0) {
634 [ # # ]: 0 : strErr = strprintf("Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
635 : 0 : return DBErrors::NONCRITICAL_ERROR;
636 : : }
637 : 0 : internal = path[1] == (1 | 0x80000000);
638 : 0 : index = path[2] & ~0x80000000;
639 : 0 : }
640 : :
641 : : // Insert a new CHDChain, or get the one that already exists
642 [ # # # # ]: 0 : auto [ins, inserted] = hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
643 [ # # ]: 0 : CHDChain& chain = ins->second;
644 [ # # ]: 0 : if (inserted) {
645 : : // For new chains, we want to default to VERSION_HD_BASE until we see an internal
646 : 0 : chain.nVersion = CHDChain::VERSION_HD_BASE;
647 : 0 : chain.seed_id = keyMeta.hd_seed_id;
648 : : }
649 [ # # ]: 0 : if (internal) {
650 : 0 : chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
651 [ # # ]: 0 : chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index + 1);
652 : : } else {
653 [ # # ]: 0 : chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index + 1);
654 : : }
655 : : }
656 : : return DBErrors::LOAD_OK;
657 : 0 : });
658 [ + - ]: 5 : result = std::max(result, keymeta_res.m_result);
659 : :
660 : : // Set inactive chains
661 [ - + ]: 5 : if (!hd_chains.empty()) {
662 [ # # ]: 0 : LegacyDataSPKM* legacy_spkm = pwallet->GetLegacyDataSPKM();
663 [ # # ]: 0 : if (legacy_spkm) {
664 [ # # # # ]: 0 : for (const auto& [hd_seed_id, chain] : hd_chains) {
665 [ # # ]: 0 : if (hd_seed_id != legacy_spkm->GetHDChain().seed_id) {
666 [ # # ]: 0 : legacy_spkm->AddInactiveHDChain(chain);
667 : : }
668 : : }
669 : : } else {
670 [ # # ]: 0 : pwallet->WalletLogPrintf("Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
671 : 0 : result = DBErrors::CORRUPT;
672 : : }
673 : : }
674 : :
675 : : // Load watchonly scripts
676 [ + - ]: 5 : LoadResult watch_script_res = LoadRecords(pwallet, batch, DBKeys::WATCHS,
677 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
678 : 0 : CScript script;
679 [ # # ]: 0 : key >> script;
680 : 0 : uint8_t fYes;
681 [ # # ]: 0 : value >> fYes;
682 [ # # ]: 0 : if (fYes == '1') {
683 [ # # # # ]: 0 : pwallet->GetOrCreateLegacyDataSPKM()->LoadWatchOnly(script);
684 : : }
685 : 0 : return DBErrors::LOAD_OK;
686 : 0 : });
687 [ + - ]: 5 : result = std::max(result, watch_script_res.m_result);
688 : :
689 : : // Load watchonly meta
690 [ + - ]: 5 : LoadResult watch_meta_res = LoadRecords(pwallet, batch, DBKeys::WATCHMETA,
691 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
692 : 0 : CScript script;
693 [ # # ]: 0 : key >> script;
694 : 0 : CKeyMetadata keyMeta;
695 [ # # ]: 0 : value >> keyMeta;
696 [ # # # # : 0 : pwallet->GetOrCreateLegacyDataSPKM()->LoadScriptMetadata(CScriptID(script), keyMeta);
# # ]
697 : 0 : return DBErrors::LOAD_OK;
698 : 0 : });
699 [ + - ]: 5 : result = std::max(result, watch_meta_res.m_result);
700 : :
701 : : // Deal with old "wkey" and "defaultkey" records.
702 : : // These are not actually loaded, but we need to check for them
703 : :
704 : : // We don't want or need the default key, but if there is one set,
705 : : // we want to make sure that it is valid so that we can detect corruption
706 : : // Note: There should only be one DEFAULTKEY with nothing trailing the type
707 [ + - ]: 5 : LoadResult default_key_res = LoadRecords(pwallet, batch, DBKeys::DEFAULTKEY,
708 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
709 [ # # ]: 0 : CPubKey default_pubkey;
710 : 0 : try {
711 [ # # ]: 0 : value >> default_pubkey;
712 [ - - ]: 0 : } catch (const std::exception& e) {
713 [ - - ]: 0 : err = e.what();
714 : 0 : return DBErrors::CORRUPT;
715 : 0 : }
716 [ # # ]: 0 : if (!default_pubkey.IsValid()) {
717 : 0 : err = "Error reading wallet database: Default Key corrupt";
718 : 0 : return DBErrors::CORRUPT;
719 : : }
720 : : return DBErrors::LOAD_OK;
721 : : });
722 [ + - ]: 5 : result = std::max(result, default_key_res.m_result);
723 : :
724 : : // "wkey" records are unsupported, if we see any, throw an error
725 [ + - ]: 5 : LoadResult wkey_res = LoadRecords(pwallet, batch, DBKeys::OLD_KEY,
726 [ + - ]: 5 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
727 : 0 : err = "Found unsupported 'wkey' record, try loading with version 0.18";
728 : 0 : return DBErrors::LOAD_FAIL;
729 : : });
730 [ + - ]: 5 : result = std::max(result, wkey_res.m_result);
731 : :
732 [ + - ]: 5 : if (result <= DBErrors::NONCRITICAL_ERROR) {
733 : : // Only do logging and time first key update if there were no critical errors
734 : 5 : pwallet->WalletLogPrintf("Legacy Wallet Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total.\n",
735 [ + - ]: 5 : key_res.m_records, ckey_res.m_records, keymeta_res.m_records, key_res.m_records + ckey_res.m_records);
736 : : }
737 : :
738 : 5 : return result;
739 : 5 : }
740 : :
741 : : template<typename... Args>
742 : 72 : static DataStream PrefixStream(const Args&... args)
743 : : {
744 : 72 : DataStream prefix;
745 [ + - ]: 72 : SerializeMany(prefix, args...);
746 : 72 : return prefix;
747 : 0 : }
748 : :
749 : 7 : static DBErrors LoadDescriptorWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
750 : : {
751 : 7 : AssertLockHeld(pwallet->cs_wallet);
752 : :
753 : : // Load descriptor record
754 : 7 : int num_keys = 0;
755 : 7 : int num_ckeys= 0;
756 [ + - ]: 7 : LoadResult desc_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTOR,
757 : 7 : [&batch, &num_keys, &num_ckeys, &last_client] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
758 : 20 : DBErrors result = DBErrors::LOAD_OK;
759 : :
760 : 20 : uint256 id;
761 : 20 : key >> id;
762 : 20 : WalletDescriptor desc;
763 : 20 : try {
764 [ + + ]: 20 : value >> desc;
765 [ - + ]: 1 : } catch (const std::ios_base::failure& e) {
766 [ + - ]: 1 : strErr = strprintf("Error: Unrecognized descriptor found in wallet %s. ", pwallet->GetName());
767 : 1 : strErr += (last_client > CLIENT_VERSION) ? "The wallet might have been created on a newer version. " :
768 [ + - ]: 1 : "The database might be corrupted or the software version is not compatible with one of your wallet descriptors. ";
769 [ + - ]: 1 : strErr += "Please try running the latest software version";
770 : : // Also include error details
771 [ + - ]: 1 : strErr = strprintf("%s\nDetails: %s", strErr, e.what());
772 : 1 : return DBErrors::UNKNOWN_DESCRIPTOR;
773 : 1 : }
774 [ + - ]: 19 : DescriptorScriptPubKeyMan& spkm = pwallet->LoadDescriptorScriptPubKeyMan(id, desc);
775 : :
776 : : // Prior to doing anything with this spkm, verify ID compatibility
777 [ + - + + ]: 19 : if (id != spkm.GetID()) {
778 [ + - ]: 1 : strErr = "The descriptor ID calculated by the wallet differs from the one in DB";
779 : : return DBErrors::CORRUPT;
780 : : }
781 : :
782 : 18 : DescriptorCache cache;
783 : :
784 : : // Get key cache for this descriptor
785 [ + - ]: 18 : DataStream prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCACHE, id);
786 : 18 : LoadResult key_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCACHE, prefix,
787 [ + - ]: 18 : [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
788 : 16 : bool parent = true;
789 : 16 : uint256 desc_id;
790 : 16 : uint32_t key_exp_index;
791 : 16 : uint32_t der_index;
792 : 16 : key >> desc_id;
793 [ - + ]: 16 : assert(desc_id == id);
794 : 16 : key >> key_exp_index;
795 : :
796 : : // if the der_index exists, it's a derived xpub
797 : 16 : try
798 : : {
799 [ - + ]: 16 : key >> der_index;
800 : : parent = false;
801 : : }
802 : 16 : catch (...) {}
803 : :
804 : 16 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
805 [ + - ]: 16 : value >> ser_xpub;
806 [ + - ]: 16 : CExtPubKey xpub;
807 [ + - ]: 16 : xpub.Decode(ser_xpub.data());
808 [ + - ]: 16 : if (parent) {
809 [ + - ]: 16 : cache.CacheParentExtPubKey(key_exp_index, xpub);
810 : : } else {
811 [ # # ]: 0 : cache.CacheDerivedExtPubKey(key_exp_index, der_index, xpub);
812 : : }
813 : 16 : return DBErrors::LOAD_OK;
814 : 16 : });
815 [ + - ]: 18 : result = std::max(result, key_cache_res.m_result);
816 : :
817 : : // Get last hardened cache for this descriptor
818 [ + - ]: 36 : prefix = PrefixStream(DBKeys::WALLETDESCRIPTORLHCACHE, id);
819 : 18 : LoadResult lh_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORLHCACHE, prefix,
820 [ + - ]: 18 : [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
821 : 16 : uint256 desc_id;
822 : 16 : uint32_t key_exp_index;
823 : 16 : key >> desc_id;
824 [ - + ]: 16 : assert(desc_id == id);
825 : 16 : key >> key_exp_index;
826 : :
827 : 16 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
828 [ + - ]: 16 : value >> ser_xpub;
829 [ + - ]: 16 : CExtPubKey xpub;
830 [ + - ]: 16 : xpub.Decode(ser_xpub.data());
831 [ + - ]: 16 : cache.CacheLastHardenedExtPubKey(key_exp_index, xpub);
832 : 16 : return DBErrors::LOAD_OK;
833 : 16 : });
834 [ + - ]: 18 : result = std::max(result, lh_cache_res.m_result);
835 : :
836 : : // Set the cache for this descriptor
837 [ + - ]: 18 : auto spk_man = (DescriptorScriptPubKeyMan*)pwallet->GetScriptPubKeyMan(id);
838 [ - + ]: 18 : assert(spk_man);
839 [ + - ]: 18 : spk_man->SetCache(cache);
840 : :
841 : : // Get unencrypted keys
842 [ + - ]: 36 : prefix = PrefixStream(DBKeys::WALLETDESCRIPTORKEY, id);
843 : 18 : LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORKEY, prefix,
844 [ + - ]: 18 : [&id, &spk_man] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
845 : 18 : uint256 desc_id;
846 : 18 : CPubKey pubkey;
847 : 18 : key >> desc_id;
848 [ - + ]: 18 : assert(desc_id == id);
849 : 18 : key >> pubkey;
850 [ - + ]: 18 : if (!pubkey.IsValid())
851 : : {
852 : 0 : strErr = "Error reading wallet database: descriptor unencrypted key CPubKey corrupt";
853 : 0 : return DBErrors::CORRUPT;
854 : : }
855 : 18 : CKey privkey;
856 : 18 : CPrivKey pkey;
857 : 18 : uint256 hash;
858 : :
859 [ + - ]: 18 : value >> pkey;
860 [ + - ]: 18 : value >> hash;
861 : :
862 : : // hash pubkey/privkey to accelerate wallet load
863 [ + - ]: 18 : const auto keypair_hash = Hash(pubkey, pkey);
864 : :
865 [ - + ]: 18 : if (keypair_hash != hash)
866 : : {
867 [ # # ]: 0 : strErr = "Error reading wallet database: descriptor unencrypted key CPubKey/CPrivKey corrupt";
868 : : return DBErrors::CORRUPT;
869 : : }
870 : :
871 [ + - - + ]: 18 : if (!privkey.Load(pkey, pubkey, true))
872 : : {
873 [ # # ]: 0 : strErr = "Error reading wallet database: descriptor unencrypted key CPrivKey corrupt";
874 : : return DBErrors::CORRUPT;
875 : : }
876 [ + - + - ]: 18 : spk_man->AddKey(pubkey.GetID(), privkey);
877 : : return DBErrors::LOAD_OK;
878 : 18 : });
879 [ + - ]: 18 : result = std::max(result, key_res.m_result);
880 : 18 : num_keys = key_res.m_records;
881 : :
882 : : // Get encrypted keys
883 [ + - ]: 36 : prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCKEY, id);
884 : 18 : LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCKEY, prefix,
885 [ + - ]: 18 : [&id, &spk_man] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
886 : 0 : uint256 desc_id;
887 : 0 : CPubKey pubkey;
888 : 0 : key >> desc_id;
889 [ # # ]: 0 : assert(desc_id == id);
890 : 0 : key >> pubkey;
891 [ # # ]: 0 : if (!pubkey.IsValid())
892 : : {
893 : 0 : err = "Error reading wallet database: descriptor encrypted key CPubKey corrupt";
894 : 0 : return DBErrors::CORRUPT;
895 : : }
896 : 0 : std::vector<unsigned char> privkey;
897 [ # # ]: 0 : value >> privkey;
898 : :
899 [ # # # # ]: 0 : spk_man->AddCryptedKey(pubkey.GetID(), pubkey, privkey);
900 : 0 : return DBErrors::LOAD_OK;
901 : 0 : });
902 [ + - ]: 18 : result = std::max(result, ckey_res.m_result);
903 : 18 : num_ckeys = ckey_res.m_records;
904 : :
905 : 18 : return result;
906 : 20 : });
907 : :
908 [ + + ]: 7 : if (desc_res.m_result <= DBErrors::NONCRITICAL_ERROR) {
909 : : // Only log if there are no critical errors
910 : 5 : pwallet->WalletLogPrintf("Descriptors: %u, Descriptor Keys: %u plaintext, %u encrypted, %u total.\n",
911 : 5 : desc_res.m_records, num_keys, num_ckeys, num_keys + num_ckeys);
912 : : }
913 : :
914 : 7 : return desc_res.m_result;
915 : : }
916 : :
917 : 6 : static DBErrors LoadAddressBookRecords(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
918 : : {
919 : 6 : AssertLockHeld(pwallet->cs_wallet);
920 : 6 : DBErrors result = DBErrors::LOAD_OK;
921 : :
922 : : // Load name record
923 [ + - ]: 6 : LoadResult name_res = LoadRecords(pwallet, batch, DBKeys::NAME,
924 [ + - ]: 6 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
925 [ + - ]: 6 : std::string strAddress;
926 [ + - ]: 6 : key >> strAddress;
927 [ + - ]: 6 : std::string label;
928 [ + - ]: 6 : value >> label;
929 [ + - + - : 12 : pwallet->m_address_book[DecodeDestination(strAddress)].SetLabel(label);
- + ]
930 : 6 : return DBErrors::LOAD_OK;
931 : 6 : });
932 [ + - ]: 6 : result = std::max(result, name_res.m_result);
933 : :
934 : : // Load purpose record
935 [ + - ]: 6 : LoadResult purpose_res = LoadRecords(pwallet, batch, DBKeys::PURPOSE,
936 [ + - ]: 6 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
937 [ + - ]: 6 : std::string strAddress;
938 [ + - ]: 6 : key >> strAddress;
939 [ + - ]: 6 : std::string purpose_str;
940 [ + - ]: 6 : value >> purpose_str;
941 [ - + ]: 6 : std::optional<AddressPurpose> purpose{PurposeFromString(purpose_str)};
942 [ - + ]: 6 : if (!purpose) {
943 [ # # ]: 0 : pwallet->WalletLogPrintf("Warning: nonstandard purpose string '%s' for address '%s'\n", purpose_str, strAddress);
944 : : }
945 [ + - + - ]: 6 : pwallet->m_address_book[DecodeDestination(strAddress)].purpose = purpose;
946 : 6 : return DBErrors::LOAD_OK;
947 : 6 : });
948 [ + - ]: 6 : result = std::max(result, purpose_res.m_result);
949 : :
950 : : // Load destination data record
951 [ + - ]: 6 : LoadResult dest_res = LoadRecords(pwallet, batch, DBKeys::DESTDATA,
952 [ + - ]: 6 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
953 [ + - ]: 5 : std::string strAddress, strKey, strValue;
954 [ + - ]: 5 : key >> strAddress;
955 [ + - ]: 5 : key >> strKey;
956 [ + - ]: 5 : value >> strValue;
957 [ + - ]: 5 : const CTxDestination& dest{DecodeDestination(strAddress)};
958 [ + + ]: 5 : if (strKey.compare("used") == 0) {
959 : : // Load "used" key indicating if an IsMine address has
960 : : // previously been spent from with avoid_reuse option enabled.
961 : : // The strValue is not used for anything currently, but could
962 : : // hold more information in the future. Current values are just
963 : : // "1" or "p" for present (which was written prior to
964 : : // f5ba424cd44619d9b9be88b8593d69a7ba96db26).
965 [ + - ]: 2 : pwallet->LoadAddressPreviouslySpent(dest);
966 [ - + + - ]: 3 : } else if (strKey.starts_with("rr")) {
967 : : // Load "rr##" keys where ## is a decimal number, and strValue
968 : : // is a serialized RecentRequestEntry object.
969 [ + - + - ]: 6 : pwallet->LoadAddressReceiveRequest(dest, strKey.substr(2), strValue);
970 : : }
971 : 5 : return DBErrors::LOAD_OK;
972 : 5 : });
973 [ + - ]: 6 : result = std::max(result, dest_res.m_result);
974 : :
975 : 6 : return result;
976 : : }
977 : :
978 : 6 : static DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch, bool& any_unordered) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
979 : : {
980 : 6 : AssertLockHeld(pwallet->cs_wallet);
981 : 6 : DBErrors result = DBErrors::LOAD_OK;
982 : :
983 : : // Load tx record
984 : 6 : any_unordered = false;
985 : 6 : LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,
986 [ + - ]: 6 : [&any_unordered] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
987 : 2 : DBErrors result = DBErrors::LOAD_OK;
988 : 2 : Txid hash;
989 : 2 : key >> hash;
990 : : // LoadToWallet call below creates a new CWalletTx that fill_wtx
991 : : // callback fills with transaction metadata.
992 : 4 : auto fill_wtx = [&](CWalletTx& wtx, bool new_tx) {
993 [ - + ]: 2 : if(!new_tx) {
994 : : // There's some corruption here since the tx we just tried to load was already in the wallet.
995 : 0 : err = "Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.";
996 : 0 : result = DBErrors::CORRUPT;
997 : 0 : return false;
998 : : }
999 : 2 : value >> wtx;
1000 [ + - ]: 2 : if (wtx.GetHash() != hash)
1001 : : return false;
1002 : :
1003 [ - + ]: 2 : if (wtx.nOrderPos == -1)
1004 : 0 : any_unordered = true;
1005 : :
1006 : : return true;
1007 : 2 : };
1008 [ + - - + ]: 2 : if (!pwallet->LoadToWallet(hash, fill_wtx)) {
1009 : : // Use std::max as fill_wtx may have already set result to CORRUPT
1010 [ # # ]: 0 : result = std::max(result, DBErrors::NEED_RESCAN);
1011 : : }
1012 : 2 : return result;
1013 : : });
1014 [ + - ]: 6 : result = std::max(result, tx_res.m_result);
1015 : :
1016 : : // Load locked utxo record
1017 [ + - ]: 6 : LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,
1018 [ + - ]: 6 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1019 : 0 : Txid hash;
1020 : 0 : uint32_t n;
1021 : 0 : key >> hash;
1022 : 0 : key >> n;
1023 : 0 : pwallet->LoadLockedCoin(COutPoint(hash, n), /*persistent=*/true);
1024 : 0 : return DBErrors::LOAD_OK;
1025 : : });
1026 [ + - ]: 6 : result = std::max(result, locked_utxo_res.m_result);
1027 : :
1028 : : // Load orderposnext record
1029 : : // Note: There should only be one ORDERPOSNEXT record with nothing trailing the type
1030 [ + - ]: 6 : LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,
1031 [ + - ]: 6 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1032 : 1 : try {
1033 [ + - ]: 2 : value >> pwallet->nOrderPosNext;
1034 [ - - ]: 0 : } catch (const std::exception& e) {
1035 [ - - ]: 0 : err = e.what();
1036 : 0 : return DBErrors::NONCRITICAL_ERROR;
1037 : 0 : }
1038 : : return DBErrors::LOAD_OK;
1039 : : });
1040 [ + - ]: 6 : result = std::max(result, order_pos_res.m_result);
1041 : :
1042 : : // After loading all tx records, abandon any coinbase that is no longer in the active chain.
1043 : : // This could happen during an external wallet load, or if the user replaced the chain data.
1044 [ + + - + ]: 8 : for (auto& [id, wtx] : pwallet->mapWallet) {
1045 [ - + ]: 2 : if (wtx.IsCoinBase() && wtx.isInactive()) {
1046 : 0 : pwallet->AbandonTransaction(wtx);
1047 : : }
1048 : : }
1049 : :
1050 : 6 : return result;
1051 : : }
1052 : :
1053 : 6 : static DBErrors LoadActiveSPKMs(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1054 : : {
1055 : 6 : AssertLockHeld(pwallet->cs_wallet);
1056 : 6 : DBErrors result = DBErrors::LOAD_OK;
1057 : :
1058 : : // Load spk records
1059 [ - + ]: 6 : std::set<std::pair<OutputType, bool>> seen_spks;
1060 [ - + - + : 42 : for (const auto& spk_key : {DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK}) {
+ + - - ]
1061 : 12 : LoadResult spkm_res = LoadRecords(pwallet, batch, spk_key,
1062 [ + - ]: 12 : [&seen_spks, &spk_key] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
1063 : 16 : uint8_t output_type;
1064 : 16 : key >> output_type;
1065 : 16 : uint256 id;
1066 : 16 : value >> id;
1067 : :
1068 : 16 : bool internal = spk_key == DBKeys::ACTIVEINTERNALSPK;
1069 [ - + ]: 16 : auto [it, insert] = seen_spks.emplace(static_cast<OutputType>(output_type), internal);
1070 [ - + ]: 16 : if (!insert) {
1071 : 0 : strErr = "Multiple ScriptpubKeyMans specified for a single type";
1072 : 0 : return DBErrors::CORRUPT;
1073 : : }
1074 : 16 : pwallet->LoadActiveScriptPubKeyMan(id, static_cast<OutputType>(output_type), /*internal=*/internal);
1075 : 16 : return DBErrors::LOAD_OK;
1076 : : });
1077 [ + - ]: 24 : result = std::max(result, spkm_res.m_result);
1078 [ + + - - ]: 18 : }
1079 : 6 : return result;
1080 : 6 : }
1081 : :
1082 : 6 : static DBErrors LoadDecryptionKeys(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1083 : : {
1084 : 6 : AssertLockHeld(pwallet->cs_wallet);
1085 : :
1086 : : // Load decryption key (mkey) records
1087 [ + - ]: 6 : LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,
1088 [ + - ]: 6 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
1089 [ # # ]: 0 : if (!LoadEncryptionKey(pwallet, key, value, err)) {
1090 : 0 : return DBErrors::CORRUPT;
1091 : : }
1092 : : return DBErrors::LOAD_OK;
1093 : : });
1094 : 6 : return mkey_res.m_result;
1095 : : }
1096 : :
1097 : 7 : DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
1098 : : {
1099 : 7 : DBErrors result = DBErrors::LOAD_OK;
1100 : 7 : bool any_unordered = false;
1101 : :
1102 : 7 : LOCK(pwallet->cs_wallet);
1103 : :
1104 : : // Last client version to open this wallet
1105 : 7 : int last_client = CLIENT_VERSION;
1106 [ + - ]: 7 : bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);
1107 [ + + + - ]: 7 : if (has_last_client) pwallet->WalletLogPrintf("Last client version = %d\n", last_client);
1108 : :
1109 : 7 : try {
1110 : : // Load wallet flags, so they are known when processing other records.
1111 : : // The FLAGS key is absent during wallet creation.
1112 [ + - + - ]: 7 : if ((result = LoadWalletFlags(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1113 : :
1114 : : #ifndef ENABLE_EXTERNAL_SIGNER
1115 : : if (pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
1116 : : pwallet->WalletLogPrintf("Error: External signer wallet being loaded without external signer support compiled\n");
1117 : : return DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED;
1118 : : }
1119 : : #endif
1120 : :
1121 : : // Load legacy wallet keys
1122 [ + - + - ]: 7 : result = std::max(LoadLegacyWalletRecords(pwallet, *m_batch, last_client), result);
1123 : :
1124 : : // Load descriptors
1125 [ + - + - ]: 7 : result = std::max(LoadDescriptorWalletRecords(pwallet, *m_batch, last_client), result);
1126 : : // Early return if there are unknown descriptors. Later loading of ACTIVEINTERNALSPK and ACTIVEEXTERNALEXPK
1127 : : // may reference the unknown descriptor's ID which can result in a misleading corruption error
1128 : : // when in reality the wallet is simply too new.
1129 [ + + ]: 7 : if (result == DBErrors::UNKNOWN_DESCRIPTOR) return result;
1130 : :
1131 : : // Load address book
1132 [ + - + + ]: 6 : result = std::max(LoadAddressBookRecords(pwallet, *m_batch), result);
1133 : :
1134 : : // Load SPKMs
1135 [ + - + + ]: 6 : result = std::max(LoadActiveSPKMs(pwallet, *m_batch), result);
1136 : :
1137 : : // Load decryption keys
1138 [ + - + + ]: 6 : result = std::max(LoadDecryptionKeys(pwallet, *m_batch), result);
1139 : :
1140 : : // Load tx records
1141 [ + - + + ]: 11 : result = std::max(LoadTxRecords(pwallet, *m_batch, any_unordered), result);
1142 [ - - ]: 0 : } catch (std::runtime_error& e) {
1143 : : // Exceptions that can be ignored or treated as non-critical are handled by the individual loading functions.
1144 : : // Any uncaught exceptions will be caught here and treated as critical.
1145 : : // Catch std::runtime_error specifically as many functions throw these and they at least have some message that
1146 : : // we can log
1147 [ - - ]: 0 : pwallet->WalletLogPrintf("%s\n", e.what());
1148 : 0 : result = DBErrors::CORRUPT;
1149 : 0 : } catch (...) {
1150 : : // All other exceptions are still problematic, but we can't log them
1151 : 0 : result = DBErrors::CORRUPT;
1152 [ - - ]: 0 : }
1153 : :
1154 : : // Any wallet corruption at all: skip any rewriting or
1155 : : // upgrading, we don't want to make it worse.
1156 [ + + ]: 6 : if (result != DBErrors::LOAD_OK)
1157 : : return result;
1158 : :
1159 [ + + - + ]: 5 : if (!has_last_client || last_client != CLIENT_VERSION) // Update
1160 [ + - ]: 1 : this->WriteVersion(CLIENT_VERSION);
1161 : :
1162 [ - + ]: 5 : if (any_unordered)
1163 [ # # ]: 0 : result = pwallet->ReorderTransactions();
1164 : :
1165 : : // Upgrade all of the descriptor caches to cache the last hardened xpub
1166 : : // This operation is not atomic, but if it fails, only new entries are added so it is backwards compatible
1167 : 5 : try {
1168 [ + - ]: 5 : pwallet->UpgradeDescriptorCache();
1169 : 0 : } catch (...) {
1170 : 0 : result = DBErrors::CORRUPT;
1171 [ - - ]: 0 : }
1172 : :
1173 : : // Since it was accidentally possible to "encrypt" a wallet with private keys disabled, we should check if this is
1174 : : // such a wallet and remove the encryption key records to avoid any future issues.
1175 : : // Although wallets without private keys should not have *ckey records, we should double check that.
1176 : : // Removing the mkey records is only safe if there are no *ckey records.
1177 [ + - - + : 5 : if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && pwallet->HasEncryptionKeys() && !pwallet->HaveCryptedKeys()) {
- - - - -
- - - ]
1178 [ # # ]: 0 : pwallet->WalletLogPrintf("Detected extraneous encryption keys in this wallet without private keys. Removing extraneous encryption keys.\n");
1179 [ # # # # ]: 0 : for (const auto& [id, _] : pwallet->mapMasterKeys) {
1180 [ # # # # ]: 0 : if (!EraseMasterKey(id)) {
1181 [ # # ]: 0 : pwallet->WalletLogPrintf("Error: Unable to remove extraneous encryption key '%u'. Wallet corrupt.\n", id);
1182 : : return DBErrors::CORRUPT;
1183 : : }
1184 : : }
1185 : 0 : pwallet->mapMasterKeys.clear();
1186 : : }
1187 : :
1188 : 5 : return result;
1189 : 7 : }
1190 : :
1191 : 36 : static bool RunWithinTxn(WalletBatch& batch, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1192 : : {
1193 [ - + ]: 36 : if (!batch.TxnBegin()) {
1194 [ # # ]: 0 : LogDebug(BCLog::WALLETDB, "Error: cannot create db txn for %s\n", process_desc);
1195 : 0 : return false;
1196 : : }
1197 : :
1198 : : // Run procedure
1199 [ - + ]: 36 : if (!func(batch)) {
1200 [ # # ]: 0 : LogDebug(BCLog::WALLETDB, "Error: %s failed\n", process_desc);
1201 : 0 : batch.TxnAbort();
1202 : 0 : return false;
1203 : : }
1204 : :
1205 [ - + ]: 36 : if (!batch.TxnCommit()) {
1206 [ # # ]: 0 : LogDebug(BCLog::WALLETDB, "Error: cannot commit db txn for %s\n", process_desc);
1207 : 0 : return false;
1208 : : }
1209 : :
1210 : : // All good
1211 : : return true;
1212 : : }
1213 : :
1214 : 36 : bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1215 : : {
1216 : 36 : WalletBatch batch(database);
1217 [ + - ]: 36 : return RunWithinTxn(batch, process_desc, func);
1218 : 36 : }
1219 : :
1220 : 3 : bool WalletBatch::WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent)
1221 : : {
1222 [ + - + - ]: 9 : auto key{std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), std::string("used")))};
1223 [ + + + - : 6 : return previously_spent ? WriteIC(key, std::string("1")) : EraseIC(key);
+ - ]
1224 : 3 : }
1225 : :
1226 : 4 : bool WalletBatch::WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request)
1227 : : {
1228 [ + - + - : 16 : return WriteIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)), receive_request);
+ - ]
1229 : : }
1230 : :
1231 : 1 : bool WalletBatch::EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id)
1232 : : {
1233 [ + - + - : 4 : return EraseIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)));
+ - ]
1234 : : }
1235 : :
1236 : 1 : bool WalletBatch::EraseAddressData(const CTxDestination& dest)
1237 : : {
1238 : 1 : DataStream prefix;
1239 [ + - + - ]: 2 : prefix << DBKeys::DESTDATA << EncodeDestination(dest);
1240 [ - + + - ]: 1 : return m_batch->ErasePrefix(prefix);
1241 : 1 : }
1242 : :
1243 : 334 : bool WalletBatch::WriteWalletFlags(const uint64_t flags)
1244 : : {
1245 : 334 : return WriteIC(DBKeys::FLAGS, flags);
1246 : : }
1247 : :
1248 : 0 : bool WalletBatch::EraseRecords(const std::unordered_set<std::string>& types)
1249 : : {
1250 : 0 : return std::all_of(types.begin(), types.end(), [&](const std::string& type) {
1251 [ # # # # : 0 : return m_batch->ErasePrefix(DataStream() << type);
# # ]
1252 : 0 : });
1253 : : }
1254 : :
1255 : 6740 : bool WalletBatch::TxnBegin()
1256 : : {
1257 : 6740 : return m_batch->TxnBegin();
1258 : : }
1259 : :
1260 : 6740 : bool WalletBatch::TxnCommit()
1261 : : {
1262 : 6740 : bool res = m_batch->TxnCommit();
1263 [ + - ]: 6740 : if (res) {
1264 [ + + ]: 6741 : for (const auto& listener : m_txn_listeners) {
1265 : 1 : listener.on_commit();
1266 : : }
1267 : : // txn finished, clear listeners
1268 : 6740 : m_txn_listeners.clear();
1269 : : }
1270 : 6740 : return res;
1271 : : }
1272 : :
1273 : 0 : bool WalletBatch::TxnAbort()
1274 : : {
1275 : 0 : bool res = m_batch->TxnAbort();
1276 [ # # ]: 0 : if (res) {
1277 [ # # ]: 0 : for (const auto& listener : m_txn_listeners) {
1278 : 0 : listener.on_abort();
1279 : : }
1280 : : // txn finished, clear listeners
1281 : 0 : m_txn_listeners.clear();
1282 : : }
1283 : 0 : return res;
1284 : : }
1285 : :
1286 : 1 : void WalletBatch::RegisterTxnListener(const DbTxnListener& l)
1287 : : {
1288 [ - + ]: 1 : assert(m_batch->HasActiveTxn());
1289 : 1 : m_txn_listeners.emplace_back(l);
1290 : 1 : }
1291 : :
1292 : 13 : std::unique_ptr<WalletDatabase> MakeDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
1293 : : {
1294 : 13 : bool exists;
1295 : 13 : try {
1296 [ + - ]: 13 : exists = fs::symlink_status(path).type() != fs::file_type::not_found;
1297 [ - - ]: 0 : } catch (const fs::filesystem_error& e) {
1298 [ - - - - : 0 : error = Untranslated(strprintf("Failed to access database path '%s': %s", fs::PathToString(path), e.code().message()));
- - - - ]
1299 : 0 : status = DatabaseStatus::FAILED_BAD_PATH;
1300 : 0 : return nullptr;
1301 : 0 : }
1302 : :
1303 : 13 : std::optional<DatabaseFormat> format;
1304 [ + + ]: 13 : if (exists) {
1305 [ + - - + ]: 24 : if (IsBDBFile(BDBDataFile(path))) {
1306 : 0 : format = DatabaseFormat::BERKELEY_RO;
1307 : : }
1308 [ + - + + ]: 24 : if (IsSQLiteFile(SQLiteDataFile(path))) {
1309 [ - + ]: 4 : if (format) {
1310 [ # # # # : 0 : error = Untranslated(strprintf("Failed to load database path '%s'. Data is in ambiguous format.", fs::PathToString(path)));
# # ]
1311 : 0 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1312 : 0 : return nullptr;
1313 : : }
1314 : 4 : format = DatabaseFormat::SQLITE;
1315 : : }
1316 [ - + ]: 1 : } else if (options.require_existing) {
1317 [ # # # # : 0 : error = Untranslated(strprintf("Failed to load database path '%s'. Path does not exist.", fs::PathToString(path)));
# # ]
1318 : 0 : status = DatabaseStatus::FAILED_NOT_FOUND;
1319 : 0 : return nullptr;
1320 : : }
1321 : :
1322 [ + + + + ]: 13 : if (!format && options.require_existing) {
1323 [ - + + - : 15 : error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in recognized format.", fs::PathToString(path)));
+ - ]
1324 : 5 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1325 : 5 : return nullptr;
1326 : : }
1327 : :
1328 [ + + + - ]: 8 : if (format && options.require_create) {
1329 [ # # # # : 0 : error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", fs::PathToString(path)));
# # ]
1330 : 0 : status = DatabaseStatus::FAILED_ALREADY_EXISTS;
1331 : 0 : return nullptr;
1332 : : }
1333 : :
1334 : : // BERKELEY_RO can only be opened if require_format was set, which only occurs in migration.
1335 [ + + - + : 8 : if (format && format == DatabaseFormat::BERKELEY_RO && (!options.require_format || options.require_format != DatabaseFormat::BERKELEY_RO)) {
- - - - ]
1336 [ # # # # : 0 : error = Untranslated(strprintf("Failed to open database path '%s'. The wallet appears to be a Legacy wallet, please use the wallet migration tool (migratewallet RPC or the GUI option).", fs::PathToString(path)));
# # ]
1337 : 0 : status = DatabaseStatus::FAILED_LEGACY_DISABLED;
1338 : 0 : return nullptr;
1339 : : }
1340 : :
1341 : : // A db already exists so format is set, but options also specifies the format, so make sure they agree
1342 [ + + + + : 8 : if (format && options.require_format && format != options.require_format) {
+ - ]
1343 [ # # # # : 0 : error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in required format.", fs::PathToString(path)));
# # ]
1344 : 0 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1345 : 0 : return nullptr;
1346 : : }
1347 : :
1348 : : // Format is not set when a db doesn't already exist, so use the format specified by the options if it is set.
1349 [ + + + + ]: 8 : if (!format && options.require_format) format = options.require_format;
1350 : :
1351 [ + + ]: 8 : if (!format) {
1352 : 3 : format = DatabaseFormat::SQLITE;
1353 : : }
1354 : :
1355 [ + - ]: 8 : if (format == DatabaseFormat::SQLITE) {
1356 : 8 : return MakeSQLiteDatabase(path, options, status, error);
1357 : : }
1358 : :
1359 [ # # ]: 0 : if (format == DatabaseFormat::BERKELEY_RO) {
1360 : 0 : return MakeBerkeleyRODatabase(path, options, status, error);
1361 : : }
1362 : :
1363 [ # # ]: 0 : error = Untranslated(STR_INTERNAL_BUG("Could not determine wallet format"));
1364 : 0 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1365 : 0 : return nullptr;
1366 : : }
1367 : : } // namespace wallet
|