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