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