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