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 : 28333 : bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
71 : : {
72 [ + - ]: 84999 : 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 : 28333 : bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
83 : : {
84 [ + - ]: 84999 : 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 : 23490 : bool WalletBatch::WriteTx(const CWalletTx& wtx)
93 : : {
94 [ + - ]: 46980 : return WriteIC(std::make_pair(DBKeys::TX, wtx.GetHash()), wtx);
95 : : }
96 : :
97 : 14 : bool WalletBatch::EraseTx(Txid hash)
98 : : {
99 [ + - ]: 28 : 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 : 16777 : bool WalletBatch::WriteBestBlock(const CBlockLocator& locator)
175 : : {
176 [ + - ]: 16777 : WriteIC(DBKeys::BESTBLOCK, CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
177 : 33554 : return WriteIC(DBKeys::BESTBLOCK_NOMERKLE, locator);
178 : : }
179 : :
180 : 1592 : bool WalletBatch::ReadBestBlock(CBlockLocator& locator)
181 : : {
182 [ + + + - ]: 1592 : if (m_batch->Read(DBKeys::BESTBLOCK, locator) && !locator.vHave.empty()) return true;
183 : 1592 : 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 : 17984 : bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
198 : : {
199 : 17984 : return WriteIC(DBKeys::ORDERPOSNEXT, nOrderPosNext);
200 : : }
201 : :
202 : 514 : bool WalletBatch::WriteMinVersion(int nVersion)
203 : : {
204 : 514 : return WriteIC(DBKeys::MINVERSION, nVersion);
205 : : }
206 : :
207 : 3224 : bool WalletBatch::WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal)
208 : : {
209 [ + + ]: 4867 : std::string key = internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK;
210 [ + - + - ]: 6448 : return WriteIC(make_pair(key, type), id);
211 : 3224 : }
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 : 3422 : bool WalletBatch::WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey)
220 : : {
221 : : // hash pubkey/privkey to accelerate wallet load
222 : 3422 : std::vector<unsigned char> key;
223 [ + - ]: 3422 : key.reserve(pubkey.size() + privkey.size());
224 [ + - ]: 3422 : key.insert(key.end(), pubkey.begin(), pubkey.end());
225 [ + - ]: 3422 : key.insert(key.end(), privkey.begin(), privkey.end());
226 : :
227 [ + - + - : 10266 : return WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)), std::make_pair(privkey, Hash(key)), false);
+ - ]
228 : 3422 : }
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 : 96304 : bool WalletBatch::WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor)
240 : : {
241 [ + - ]: 192608 : return WriteIC(make_pair(DBKeys::WALLETDESCRIPTOR, desc_id), descriptor);
242 : : }
243 : :
244 : 9994 : bool WalletBatch::WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index)
245 : : {
246 : 9994 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
247 [ + - ]: 9994 : xpub.Encode(ser_xpub.data());
248 [ + - + - ]: 19988 : return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), std::make_pair(key_exp_index, der_index)), ser_xpub);
249 : 9994 : }
250 : :
251 : 3745 : bool WalletBatch::WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
252 : : {
253 : 3745 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
254 [ + - ]: 3745 : xpub.Encode(ser_xpub.data());
255 [ + - + - ]: 7490 : return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), key_exp_index), ser_xpub);
256 : 3745 : }
257 : :
258 : 3026 : bool WalletBatch::WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
259 : : {
260 : 3026 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
261 [ + - ]: 3026 : xpub.Encode(ser_xpub.data());
262 [ + - + - ]: 6052 : return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORLHCACHE, desc_id), key_exp_index), ser_xpub);
263 : 3026 : }
264 : :
265 : 437034 : bool WalletBatch::WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache)
266 : : {
267 [ + + + - ]: 440779 : for (const auto& parent_xpub_pair : cache.GetCachedParentExtPubKeys()) {
268 [ - + + - ]: 3745 : if (!WriteDescriptorParentCache(parent_xpub_pair.second, desc_id, parent_xpub_pair.first)) {
269 : 0 : return false;
270 : : }
271 : 0 : }
272 [ + + ]: 447028 : for (const auto& derived_xpub_map_pair : cache.GetCachedDerivedExtPubKeys()) {
273 [ + + + - ]: 19988 : for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
274 [ - + + - ]: 9994 : 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 [ + + + - ]: 440060 : for (const auto& lh_xpub_pair : cache.GetCachedLastHardenedExtPubKeys()) {
280 [ - + + - ]: 3026 : if (!WriteDescriptorLastHardenedCache(lh_xpub_pair.second, desc_id, lh_xpub_pair.first)) {
281 : 0 : return false;
282 : : }
283 : 0 : }
284 : 437034 : 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 : 173 : bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
298 : : {
299 : 173 : LOCK(pwallet->cs_wallet);
300 : 173 : try {
301 [ + - ]: 173 : CPubKey vchPubKey;
302 [ + - ]: 173 : ssKey >> vchPubKey;
303 [ - + ]: 173 : if (!vchPubKey.IsValid())
304 : : {
305 [ - - + - ]: 173 : strErr = "Error reading wallet database: CPubKey corrupt";
306 : : return false;
307 : : }
308 : 173 : CKey key;
309 : 173 : CPrivKey pkey;
310 : 173 : uint256 hash;
311 : :
312 [ + - ]: 173 : 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 : 173 : try
320 : : {
321 [ + - ]: 173 : ssValue >> hash;
322 : : }
323 [ - - ]: 0 : catch (const std::ios_base::failure&) {}
324 : :
325 : 173 : bool fSkipCheck = false;
326 : :
327 [ + - ]: 173 : if (!hash.IsNull())
328 : : {
329 : : // hash pubkey/privkey to accelerate wallet load
330 : 173 : std::vector<unsigned char> vchKey;
331 [ + - ]: 173 : vchKey.reserve(vchPubKey.size() + pkey.size());
332 [ + - ]: 173 : vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
333 [ + - ]: 173 : vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
334 : :
335 [ + - - + ]: 173 : if (Hash(vchKey) != hash)
336 : : {
337 [ # # ]: 0 : strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
338 : 0 : return false;
339 : : }
340 : :
341 : 173 : fSkipCheck = true;
342 : 173 : }
343 : :
344 [ + - - + ]: 173 : if (!key.Load(pkey, vchPubKey, fSkipCheck))
345 : : {
346 [ # # ]: 0 : strErr = "Error reading wallet database: CPrivKey corrupt";
347 : : return false;
348 : : }
349 [ + - + - : 173 : if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadKey(key, vchPubKey))
- + ]
350 : : {
351 [ # # ]: 0 : strErr = "Error reading wallet database: LegacyDataSPKM::LoadKey failed";
352 : : return false;
353 : : }
354 [ - - ]: 173 : } catch (const std::exception& e) {
355 [ - - ]: 0 : if (strErr.empty()) {
356 [ - - ]: 0 : strErr = e.what();
357 : : }
358 : 0 : return false;
359 : 0 : }
360 : 173 : return true;
361 : 173 : }
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 : 893 : static DBErrors LoadMinVersion(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
446 : : {
447 : 893 : AssertLockHeld(pwallet->cs_wallet);
448 : 893 : int nMinVersion = 0;
449 [ + + ]: 893 : 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 : 893 : static DBErrors LoadWalletFlags(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
459 : : {
460 : 893 : AssertLockHeld(pwallet->cs_wallet);
461 : 893 : uint64_t flags;
462 [ + + ]: 893 : 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 : 23878 : static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, DataStream& prefix, LoadFunc load_func)
484 : : {
485 : 23878 : LoadResult result;
486 : 23878 : DataStream ssKey;
487 : 23878 : DataStream ssValue{};
488 : :
489 [ + - ]: 23878 : Assume(!prefix.empty());
490 [ + - ]: 23878 : std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
491 [ - + ]: 23878 : 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 : 74318 : while (true) {
498 [ + - ]: 49098 : DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
499 [ + + ]: 49098 : if (status == DatabaseCursor::Status::DONE) {
500 : : break;
501 [ - + ]: 25220 : } 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 [ + - ]: 25220 : std::string type;
507 [ + - ]: 25220 : ssKey >> type;
508 [ - + ]: 25220 : assert(type == key);
509 [ + - ]: 25220 : std::string error;
510 [ + - ]: 25220 : DBErrors record_res = load_func(pwallet, ssKey, ssValue, error);
511 [ + + ]: 25220 : if (record_res != DBErrors::LOAD_OK) {
512 [ + - ]: 3 : pwallet->WalletLogPrintf("%s\n", error);
513 : : }
514 [ + + ]: 25220 : result.m_result = std::max(result.m_result, record_res);
515 : 25220 : ++result.m_records;
516 : 25220 : }
517 : 23878 : return result;
518 : 23878 : }
519 : :
520 : 14330 : static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, LoadFunc load_func)
521 : : {
522 : 14330 : DataStream prefix;
523 [ + - ]: 14330 : prefix << key;
524 [ + - + - ]: 28660 : return LoadRecords(pwallet, batch, key, prefix, load_func);
525 : 14330 : }
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 : 893 : static DBErrors LoadLegacyWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
556 : : {
557 : 893 : AssertLockHeld(pwallet->cs_wallet);
558 : 893 : DBErrors result = DBErrors::LOAD_OK;
559 : :
560 : : // Make sure descriptor wallets don't have any legacy records
561 [ + + ]: 893 : 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 [ + - ]: 601 : 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 [ + - ]: 601 : result = std::max(result, hd_chain_res.m_result);
577 : :
578 : : // Load unencrypted keys
579 [ + - ]: 601 : LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::KEY,
580 : 173 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
581 [ - + ]: 173 : return LoadKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
582 : : });
583 [ + - ]: 601 : result = std::max(result, key_res.m_result);
584 : :
585 : : // Load encrypted keys
586 [ + - ]: 601 : 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 [ + - ]: 601 : result = std::max(result, ckey_res.m_result);
591 : :
592 : : // Load scripts
593 [ + - ]: 601 : LoadResult script_res = LoadRecords(pwallet, batch, DBKeys::CSCRIPT,
594 : 83 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
595 : 83 : uint160 hash;
596 : 83 : key >> hash;
597 : 83 : CScript script;
598 [ + - ]: 83 : value >> script;
599 [ + - + - : 83 : if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCScript(script))
- + ]
600 : : {
601 [ - - ]: 83 : strErr = "Error reading wallet database: LegacyDataSPKM::LoadCScript failed";
602 : : return DBErrors::NONCRITICAL_ERROR;
603 : : }
604 : : return DBErrors::LOAD_OK;
605 : 83 : });
606 [ + - ]: 601 : result = std::max(result, script_res.m_result);
607 : :
608 : : // Check whether rewrite is needed
609 [ + + ]: 601 : 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 [ + - ]: 601 : std::map<uint160, CHDChain> hd_chains;
616 : 0 : LoadResult keymeta_res = LoadRecords(pwallet, batch, DBKeys::KEYMETA,
617 [ + - ]: 601 : [&hd_chains] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
618 : 201 : CPubKey vchPubKey;
619 : 201 : key >> vchPubKey;
620 : 201 : CKeyMetadata keyMeta;
621 [ + - ]: 201 : value >> keyMeta;
622 [ + - + - : 201 : pwallet->GetOrCreateLegacyDataSPKM()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
+ - ]
623 : :
624 : : // Extract some CHDChain info from this metadata if it has any
625 [ + - + + : 201 : 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 : 192 : bool internal = false;
630 : 192 : uint32_t index = 0;
631 [ + + + - ]: 192 : if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
632 : 159 : std::vector<uint32_t> path;
633 [ + - ]: 159 : if (keyMeta.has_key_origin) {
634 : : // We have a key origin, so pull it from its path vector
635 [ + - ]: 159 : 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 [ + + ]: 159 : if (path.size() != 3) {
649 [ + - ]: 1 : strErr = "Error reading wallet database: keymeta found with unexpected path";
650 : : return DBErrors::NONCRITICAL_ERROR;
651 : : }
652 [ - + ]: 158 : 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 [ + + + - ]: 158 : 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 [ - + ]: 158 : 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 : 158 : internal = path[1] == (1 | 0x80000000);
665 : 158 : index = path[2] & ~0x80000000;
666 : 159 : }
667 : :
668 : : // Insert a new CHDChain, or get the one that already exists
669 [ + - + + ]: 191 : auto [ins, inserted] = hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
670 [ + + ]: 191 : CHDChain& chain = ins->second;
671 [ + + ]: 191 : 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 [ + + ]: 191 : if (internal) {
677 : 64 : chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
678 [ + + ]: 86 : chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index + 1);
679 : : } else {
680 [ + + ]: 205 : chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index + 1);
681 : : }
682 : : }
683 : : return DBErrors::LOAD_OK;
684 : 201 : });
685 [ + + ]: 601 : result = std::max(result, keymeta_res.m_result);
686 : :
687 : : // Set inactive chains
688 [ + + ]: 601 : 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 [ + - ]: 601 : 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 [ + - ]: 601 : result = std::max(result, watch_script_res.m_result);
715 : :
716 : : // Load watchonly meta
717 [ + - ]: 601 : 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 [ + - ]: 601 : 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 [ + - ]: 601 : 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 [ + - ]: 601 : result = std::max(result, default_key_res.m_result);
750 : :
751 : : // "wkey" records are unsupported, if we see any, throw an error
752 [ + - ]: 601 : 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 [ + - ]: 601 : result = std::max(result, wkey_res.m_result);
758 : :
759 [ + - ]: 601 : if (result <= DBErrors::NONCRITICAL_ERROR) {
760 : : // Only do logging and time first key update if there were no critical errors
761 : 601 : pwallet->WalletLogPrintf("Legacy Wallet Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total.\n",
762 [ + - ]: 601 : key_res.m_records, ckey_res.m_records, keymeta_res.m_records, key_res.m_records + ckey_res.m_records);
763 : : }
764 : :
765 : 601 : return result;
766 : 601 : }
767 : :
768 : : template<typename... Args>
769 : 9548 : static DataStream PrefixStream(const Args&... args)
770 : : {
771 : 9548 : DataStream prefix;
772 [ + - ]: 9548 : SerializeMany(prefix, args...);
773 : 9548 : return prefix;
774 : 0 : }
775 : :
776 : 893 : static DBErrors LoadDescriptorWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
777 : : {
778 : 893 : AssertLockHeld(pwallet->cs_wallet);
779 : :
780 : : // Load descriptor record
781 : 893 : int num_keys = 0;
782 : 893 : int num_ckeys= 0;
783 [ + - ]: 893 : LoadResult desc_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTOR,
784 : 893 : [&batch, &num_keys, &num_ckeys, &last_client] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
785 : 2389 : DBErrors result = DBErrors::LOAD_OK;
786 : :
787 : 2389 : uint256 id;
788 : 2389 : key >> id;
789 : 2389 : WalletDescriptor desc;
790 : 2389 : try {
791 [ + + ]: 2389 : 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 [ + - ]: 2388 : DescriptorScriptPubKeyMan& spkm = pwallet->LoadDescriptorScriptPubKeyMan(id, desc);
802 : :
803 : : // Prior to doing anything with this spkm, verify ID compatibility
804 [ + - + + ]: 2388 : 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 : 2387 : DescriptorCache cache;
810 : :
811 : : // Get key cache for this descriptor
812 [ + - ]: 2387 : DataStream prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCACHE, id);
813 : 0 : LoadResult key_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCACHE, prefix,
814 [ + - ]: 2387 : [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
815 : 2276 : bool parent = true;
816 : 2276 : uint256 desc_id;
817 : 2276 : uint32_t key_exp_index;
818 : 2276 : uint32_t der_index;
819 : 2276 : key >> desc_id;
820 [ - + ]: 2276 : assert(desc_id == id);
821 : 2276 : key >> key_exp_index;
822 : :
823 : : // if the der_index exists, it's a derived xpub
824 : 2276 : try
825 : : {
826 [ + + ]: 2276 : key >> der_index;
827 : : parent = false;
828 : : }
829 : 2105 : catch (...) {}
830 : :
831 : 2276 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
832 [ + - ]: 2276 : value >> ser_xpub;
833 [ + - ]: 2276 : CExtPubKey xpub;
834 [ + - ]: 2276 : xpub.Decode(ser_xpub.data());
835 [ + + ]: 2276 : if (parent) {
836 [ + - ]: 2105 : cache.CacheParentExtPubKey(key_exp_index, xpub);
837 : : } else {
838 [ + - ]: 171 : cache.CacheDerivedExtPubKey(key_exp_index, der_index, xpub);
839 : : }
840 : 2276 : return DBErrors::LOAD_OK;
841 : 2276 : });
842 [ + - ]: 2387 : result = std::max(result, key_cache_res.m_result);
843 : :
844 : : // Get last hardened cache for this descriptor
845 [ + - ]: 4774 : prefix = PrefixStream(DBKeys::WALLETDESCRIPTORLHCACHE, id);
846 : 0 : LoadResult lh_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORLHCACHE, prefix,
847 [ + - ]: 2387 : [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
848 : 2086 : uint256 desc_id;
849 : 2086 : uint32_t key_exp_index;
850 : 2086 : key >> desc_id;
851 [ - + ]: 2086 : assert(desc_id == id);
852 : 2086 : key >> key_exp_index;
853 : :
854 : 2086 : std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
855 [ + - ]: 2086 : value >> ser_xpub;
856 [ + - ]: 2086 : CExtPubKey xpub;
857 [ + - ]: 2086 : xpub.Decode(ser_xpub.data());
858 [ + - ]: 2086 : cache.CacheLastHardenedExtPubKey(key_exp_index, xpub);
859 : 2086 : return DBErrors::LOAD_OK;
860 : 2086 : });
861 [ + - ]: 2387 : result = std::max(result, lh_cache_res.m_result);
862 : :
863 : : // Set the cache for this descriptor
864 [ + - ]: 2387 : auto spk_man = (DescriptorScriptPubKeyMan*)pwallet->GetScriptPubKeyMan(id);
865 [ - + ]: 2387 : assert(spk_man);
866 [ + - ]: 2387 : spk_man->SetCache(cache);
867 : :
868 : : // Get unencrypted keys
869 [ + - ]: 4774 : prefix = PrefixStream(DBKeys::WALLETDESCRIPTORKEY, id);
870 : 0 : LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORKEY, prefix,
871 [ + - ]: 2387 : [&id, &spk_man] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
872 : 2070 : uint256 desc_id;
873 : 2070 : CPubKey pubkey;
874 : 2070 : key >> desc_id;
875 [ - + ]: 2070 : assert(desc_id == id);
876 : 2070 : key >> pubkey;
877 [ - + ]: 2070 : if (!pubkey.IsValid())
878 : : {
879 : 0 : strErr = "Error reading wallet database: descriptor unencrypted key CPubKey corrupt";
880 : 0 : return DBErrors::CORRUPT;
881 : : }
882 : 2070 : CKey privkey;
883 : 2070 : CPrivKey pkey;
884 : 2070 : uint256 hash;
885 : :
886 [ + - ]: 2070 : value >> pkey;
887 [ + - ]: 2070 : value >> hash;
888 : :
889 : : // hash pubkey/privkey to accelerate wallet load
890 : 2070 : std::vector<unsigned char> to_hash;
891 [ + - ]: 2070 : to_hash.reserve(pubkey.size() + pkey.size());
892 [ + - ]: 2070 : to_hash.insert(to_hash.end(), pubkey.begin(), pubkey.end());
893 [ + - ]: 2070 : to_hash.insert(to_hash.end(), pkey.begin(), pkey.end());
894 : :
895 [ + - - + ]: 2070 : 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 [ + - - + ]: 2070 : if (!privkey.Load(pkey, pubkey, true))
902 : : {
903 [ - - ]: 2070 : strErr = "Error reading wallet database: descriptor unencrypted key CPrivKey corrupt";
904 : : return DBErrors::CORRUPT;
905 : : }
906 [ + - + - ]: 2070 : spk_man->AddKey(pubkey.GetID(), privkey);
907 : : return DBErrors::LOAD_OK;
908 : 2070 : });
909 [ + - ]: 2387 : result = std::max(result, key_res.m_result);
910 : 2387 : num_keys = key_res.m_records;
911 : :
912 : : // Get encrypted keys
913 [ + - ]: 4774 : prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCKEY, id);
914 : 0 : LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCKEY, prefix,
915 [ + - ]: 2387 : [&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 [ + - ]: 2387 : result = std::max(result, ckey_res.m_result);
933 : 2387 : num_ckeys = ckey_res.m_records;
934 : :
935 : 2387 : return result;
936 : 2389 : });
937 : :
938 [ + + ]: 893 : if (desc_res.m_result <= DBErrors::NONCRITICAL_ERROR) {
939 : : // Only log if there are no critical errors
940 : 891 : pwallet->WalletLogPrintf("Descriptors: %u, Descriptor Keys: %u plaintext, %u encrypted, %u total.\n",
941 : 891 : desc_res.m_records, num_keys, num_ckeys, num_keys + num_ckeys);
942 : : }
943 : :
944 : 893 : return desc_res.m_result;
945 : : }
946 : :
947 : 892 : static DBErrors LoadAddressBookRecords(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
948 : : {
949 : 892 : AssertLockHeld(pwallet->cs_wallet);
950 : 892 : DBErrors result = DBErrors::LOAD_OK;
951 : :
952 : : // Load name record
953 [ + - ]: 892 : LoadResult name_res = LoadRecords(pwallet, batch, DBKeys::NAME,
954 : 2888 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
955 [ + - ]: 2888 : std::string strAddress;
956 [ + - ]: 2888 : key >> strAddress;
957 [ + - ]: 2888 : std::string label;
958 [ + - ]: 2888 : value >> label;
959 [ + - + - : 5776 : pwallet->m_address_book[DecodeDestination(strAddress)].SetLabel(label);
+ - ]
960 : 2888 : return DBErrors::LOAD_OK;
961 : 2888 : });
962 [ + - ]: 892 : result = std::max(result, name_res.m_result);
963 : :
964 : : // Load purpose record
965 [ + - ]: 892 : LoadResult purpose_res = LoadRecords(pwallet, batch, DBKeys::PURPOSE,
966 : 2888 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
967 [ + - ]: 2888 : std::string strAddress;
968 [ + - ]: 2888 : key >> strAddress;
969 [ + - ]: 2888 : std::string purpose_str;
970 [ + - ]: 2888 : value >> purpose_str;
971 [ - + ]: 2888 : std::optional<AddressPurpose> purpose{PurposeFromString(purpose_str)};
972 [ - + ]: 2888 : if (!purpose) {
973 [ # # ]: 0 : pwallet->WalletLogPrintf("Warning: nonstandard purpose string '%s' for address '%s'\n", purpose_str, strAddress);
974 : : }
975 [ + - + - ]: 2888 : pwallet->m_address_book[DecodeDestination(strAddress)].purpose = purpose;
976 : 2888 : return DBErrors::LOAD_OK;
977 : 2888 : });
978 [ + - ]: 892 : result = std::max(result, purpose_res.m_result);
979 : :
980 : : // Load destination data record
981 [ + - ]: 892 : 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 [ + - ]: 892 : result = std::max(result, dest_res.m_result);
1004 : :
1005 : 892 : return result;
1006 : : }
1007 : :
1008 : 892 : static DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch, std::vector<Txid>& upgraded_txs, bool& any_unordered) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1009 : : {
1010 : 892 : AssertLockHeld(pwallet->cs_wallet);
1011 : 892 : DBErrors result = DBErrors::LOAD_OK;
1012 : :
1013 : : // Load tx record
1014 : 892 : any_unordered = false;
1015 : 0 : LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,
1016 [ + - ]: 892 : [&any_unordered, &upgraded_txs] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1017 : 7599 : DBErrors result = DBErrors::LOAD_OK;
1018 : 7599 : Txid hash;
1019 : 7599 : key >> hash;
1020 : : // LoadToWallet call below creates a new CWalletTx that fill_wtx
1021 : : // callback fills with transaction metadata.
1022 : 15198 : auto fill_wtx = [&](CWalletTx& wtx, bool new_tx) {
1023 [ - + ]: 7599 : 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 : 7599 : value >> wtx;
1030 [ + - ]: 7599 : if (wtx.GetHash() != hash)
1031 : : return false;
1032 : :
1033 : : // Undo serialize changes in 31600
1034 [ - + ]: 7599 : if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
1035 : : {
1036 [ # # ]: 0 : if (!value.empty())
1037 : : {
1038 : 0 : uint8_t fTmp;
1039 : 0 : uint8_t fUnused;
1040 [ # # ]: 0 : std::string unused_string;
1041 [ # # # # : 0 : value >> fTmp >> fUnused >> unused_string;
# # ]
1042 : 0 : pwallet->WalletLogPrintf("LoadWallet() upgrading tx ver=%d %d %s\n",
1043 [ # # # # ]: 0 : wtx.fTimeReceivedIsTxTime, fTmp, hash.ToString());
1044 : 0 : wtx.fTimeReceivedIsTxTime = fTmp;
1045 : 0 : }
1046 : : else
1047 : : {
1048 [ # # ]: 0 : pwallet->WalletLogPrintf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString());
1049 : 0 : wtx.fTimeReceivedIsTxTime = 0;
1050 : : }
1051 : 0 : upgraded_txs.push_back(hash);
1052 : : }
1053 : :
1054 [ - + ]: 7599 : if (wtx.nOrderPos == -1)
1055 : 0 : any_unordered = true;
1056 : :
1057 : : return true;
1058 : 7599 : };
1059 [ + - - + ]: 7599 : if (!pwallet->LoadToWallet(hash, fill_wtx)) {
1060 : : // Use std::max as fill_wtx may have already set result to CORRUPT
1061 [ # # ]: 0 : result = std::max(result, DBErrors::NEED_RESCAN);
1062 : : }
1063 : 7599 : return result;
1064 : : });
1065 [ + - ]: 892 : result = std::max(result, tx_res.m_result);
1066 : :
1067 : : // Load locked utxo record
1068 [ + - ]: 892 : LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,
1069 : 2 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1070 : 2 : Txid hash;
1071 : 2 : uint32_t n;
1072 : 2 : key >> hash;
1073 : 2 : key >> n;
1074 : 2 : pwallet->LockCoin(COutPoint(hash, n));
1075 : 2 : return DBErrors::LOAD_OK;
1076 : : });
1077 [ + - ]: 892 : result = std::max(result, locked_utxo_res.m_result);
1078 : :
1079 : : // Load orderposnext record
1080 : : // Note: There should only be one ORDERPOSNEXT record with nothing trailing the type
1081 [ + - ]: 892 : LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,
1082 : 172 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1083 : 172 : try {
1084 [ + - ]: 344 : value >> pwallet->nOrderPosNext;
1085 [ - - ]: 0 : } catch (const std::exception& e) {
1086 [ - - ]: 0 : err = e.what();
1087 : 0 : return DBErrors::NONCRITICAL_ERROR;
1088 : 0 : }
1089 : : return DBErrors::LOAD_OK;
1090 : : });
1091 [ + - ]: 892 : result = std::max(result, order_pos_res.m_result);
1092 : :
1093 : : // After loading all tx records, abandon any coinbase that is no longer in the active chain.
1094 : : // This could happen during an external wallet load, or if the user replaced the chain data.
1095 [ + + + + ]: 8491 : for (auto& [id, wtx] : pwallet->mapWallet) {
1096 [ + + ]: 14172 : if (wtx.IsCoinBase() && wtx.isInactive()) {
1097 : 592 : pwallet->AbandonTransaction(wtx);
1098 : : }
1099 : : }
1100 : :
1101 : 892 : return result;
1102 : : }
1103 : :
1104 : 892 : static DBErrors LoadActiveSPKMs(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1105 : : {
1106 : 892 : AssertLockHeld(pwallet->cs_wallet);
1107 : 892 : DBErrors result = DBErrors::LOAD_OK;
1108 : :
1109 : : // Load spk records
1110 [ + - ]: 892 : std::set<std::pair<OutputType, bool>> seen_spks;
1111 [ + - + - : 4460 : for (const auto& spk_key : {DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK}) {
+ + - - ]
1112 : 0 : LoadResult spkm_res = LoadRecords(pwallet, batch, spk_key,
1113 [ + - ]: 1784 : [&seen_spks, &spk_key] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
1114 : 1994 : uint8_t output_type;
1115 : 1994 : key >> output_type;
1116 : 1994 : uint256 id;
1117 : 1994 : value >> id;
1118 : :
1119 : 1994 : bool internal = spk_key == DBKeys::ACTIVEINTERNALSPK;
1120 [ - + ]: 1994 : auto [it, insert] = seen_spks.emplace(static_cast<OutputType>(output_type), internal);
1121 [ - + ]: 1994 : if (!insert) {
1122 : 0 : strErr = "Multiple ScriptpubKeyMans specified for a single type";
1123 : 0 : return DBErrors::CORRUPT;
1124 : : }
1125 : 1994 : pwallet->LoadActiveScriptPubKeyMan(id, static_cast<OutputType>(output_type), /*internal=*/internal);
1126 : 1994 : return DBErrors::LOAD_OK;
1127 : : });
1128 [ + - ]: 3568 : result = std::max(result, spkm_res.m_result);
1129 [ + + - - ]: 2676 : }
1130 : 892 : return result;
1131 : 892 : }
1132 : :
1133 : 892 : static DBErrors LoadDecryptionKeys(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1134 : : {
1135 : 892 : AssertLockHeld(pwallet->cs_wallet);
1136 : :
1137 : : // Load decryption key (mkey) records
1138 [ + - ]: 892 : LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,
1139 : 19 : [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
1140 [ - + ]: 19 : if (!LoadEncryptionKey(pwallet, key, value, err)) {
1141 : 0 : return DBErrors::CORRUPT;
1142 : : }
1143 : : return DBErrors::LOAD_OK;
1144 : : });
1145 : 892 : return mkey_res.m_result;
1146 : : }
1147 : :
1148 : 893 : DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
1149 : : {
1150 : 893 : DBErrors result = DBErrors::LOAD_OK;
1151 : 893 : bool any_unordered = false;
1152 : 893 : std::vector<Txid> upgraded_txs;
1153 : :
1154 [ + - ]: 893 : LOCK(pwallet->cs_wallet);
1155 : :
1156 : : // Last client version to open this wallet
1157 : 893 : int last_client = CLIENT_VERSION;
1158 [ + - ]: 893 : bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);
1159 [ + + + - ]: 893 : if (has_last_client) pwallet->WalletLogPrintf("Last client version = %d\n", last_client);
1160 : :
1161 : 893 : try {
1162 [ + - + - ]: 893 : if ((result = LoadMinVersion(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1163 : :
1164 : : // Load wallet flags, so they are known when processing other records.
1165 : : // The FLAGS key is absent during wallet creation.
1166 [ + - + - ]: 893 : if ((result = LoadWalletFlags(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1167 : :
1168 : : #ifndef ENABLE_EXTERNAL_SIGNER
1169 : : if (pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
1170 : : pwallet->WalletLogPrintf("Error: External signer wallet being loaded without external signer support compiled\n");
1171 : : return DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED;
1172 : : }
1173 : : #endif
1174 : :
1175 : : // Load legacy wallet keys
1176 [ + - + - ]: 893 : result = std::max(LoadLegacyWalletRecords(pwallet, *m_batch, last_client), result);
1177 : :
1178 : : // Load descriptors
1179 [ + - + + ]: 893 : result = std::max(LoadDescriptorWalletRecords(pwallet, *m_batch, last_client), result);
1180 : : // Early return if there are unknown descriptors. Later loading of ACTIVEINTERNALSPK and ACTIVEEXTERNALEXPK
1181 : : // may reference the unknown descriptor's ID which can result in a misleading corruption error
1182 : : // when in reality the wallet is simply too new.
1183 [ + + ]: 893 : if (result == DBErrors::UNKNOWN_DESCRIPTOR) return result;
1184 : :
1185 : : // Load address book
1186 [ + - + + ]: 892 : result = std::max(LoadAddressBookRecords(pwallet, *m_batch), result);
1187 : :
1188 : : // Load tx records
1189 [ + - + + ]: 892 : result = std::max(LoadTxRecords(pwallet, *m_batch, upgraded_txs, any_unordered), result);
1190 : :
1191 : : // Load SPKMs
1192 [ + - + + ]: 892 : result = std::max(LoadActiveSPKMs(pwallet, *m_batch), result);
1193 : :
1194 : : // Load decryption keys
1195 [ + - + + ]: 1781 : result = std::max(LoadDecryptionKeys(pwallet, *m_batch), result);
1196 [ - - ]: 0 : } catch (std::runtime_error& e) {
1197 : : // Exceptions that can be ignored or treated as non-critical are handled by the individual loading functions.
1198 : : // Any uncaught exceptions will be caught here and treated as critical.
1199 : : // Catch std::runtime_error specifically as many functions throw these and they at least have some message that
1200 : : // we can log
1201 [ - - ]: 0 : pwallet->WalletLogPrintf("%s\n", e.what());
1202 : 0 : result = DBErrors::CORRUPT;
1203 : 0 : } catch (...) {
1204 : : // All other exceptions are still problematic, but we can't log them
1205 : 0 : result = DBErrors::CORRUPT;
1206 [ - - ]: 0 : }
1207 : :
1208 : : // Any wallet corruption at all: skip any rewriting or
1209 : : // upgrading, we don't want to make it worse.
1210 [ + + ]: 892 : if (result != DBErrors::LOAD_OK)
1211 : : return result;
1212 : :
1213 [ - + ]: 889 : for (const Txid& hash : upgraded_txs)
1214 [ # # # # ]: 0 : WriteTx(pwallet->mapWallet.at(hash));
1215 : :
1216 [ + + + + ]: 889 : if (!has_last_client || last_client != CLIENT_VERSION) // Update
1217 [ + - ]: 638 : m_batch->Write(DBKeys::VERSION, CLIENT_VERSION);
1218 : :
1219 [ - + ]: 889 : if (any_unordered)
1220 [ # # ]: 0 : result = pwallet->ReorderTransactions();
1221 : :
1222 : : // Upgrade all of the descriptor caches to cache the last hardened xpub
1223 : : // This operation is not atomic, but if it fails, only new entries are added so it is backwards compatible
1224 : 889 : try {
1225 [ + - ]: 889 : pwallet->UpgradeDescriptorCache();
1226 : 0 : } catch (...) {
1227 : 0 : result = DBErrors::CORRUPT;
1228 [ - - ]: 0 : }
1229 : :
1230 : : // Since it was accidentally possible to "encrypt" a wallet with private keys disabled, we should check if this is
1231 : : // such a wallet and remove the encryption key records to avoid any future issues.
1232 : : // Although wallets without private keys should not have *ckey records, we should double check that.
1233 : : // Removing the mkey records is only safe if there are no *ckey records.
1234 [ + - + + : 889 : if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && pwallet->HasEncryptionKeys() && !pwallet->HaveCryptedKeys()) {
+ - + + +
- + - ]
1235 [ + - ]: 1 : pwallet->WalletLogPrintf("Detected extraneous encryption keys in this wallet without private keys. Removing extraneous encryption keys.\n");
1236 [ + - + + ]: 2 : for (const auto& [id, _] : pwallet->mapMasterKeys) {
1237 [ + - - + ]: 1 : if (!EraseMasterKey(id)) {
1238 [ # # ]: 0 : pwallet->WalletLogPrintf("Error: Unable to remove extraneous encryption key '%u'. Wallet corrupt.\n", id);
1239 : : return DBErrors::CORRUPT;
1240 : : }
1241 : : }
1242 : 1 : pwallet->mapMasterKeys.clear();
1243 : : }
1244 : :
1245 : 889 : return result;
1246 : 893 : }
1247 : :
1248 : 379 : static bool RunWithinTxn(WalletBatch& batch, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1249 : : {
1250 [ - + ]: 379 : if (!batch.TxnBegin()) {
1251 [ # # ]: 0 : LogDebug(BCLog::WALLETDB, "Error: cannot create db txn for %s\n", process_desc);
1252 : 0 : return false;
1253 : : }
1254 : :
1255 : : // Run procedure
1256 [ + + ]: 379 : if (!func(batch)) {
1257 [ + - ]: 1 : LogDebug(BCLog::WALLETDB, "Error: %s failed\n", process_desc);
1258 : 1 : batch.TxnAbort();
1259 : 1 : return false;
1260 : : }
1261 : :
1262 [ - + ]: 378 : if (!batch.TxnCommit()) {
1263 [ # # ]: 0 : LogDebug(BCLog::WALLETDB, "Error: cannot commit db txn for %s\n", process_desc);
1264 : 0 : return false;
1265 : : }
1266 : :
1267 : : // All good
1268 : : return true;
1269 : : }
1270 : :
1271 : 379 : bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1272 : : {
1273 : 379 : WalletBatch batch(database);
1274 [ + - ]: 379 : return RunWithinTxn(batch, process_desc, func);
1275 : 379 : }
1276 : :
1277 : 24 : bool WalletBatch::WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent)
1278 : : {
1279 [ + - + - ]: 96 : auto key{std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), std::string("used")))};
1280 [ + + + - : 48 : return previously_spent ? WriteIC(key, std::string("1")) : EraseIC(key);
+ - ]
1281 : 24 : }
1282 : :
1283 : 4 : bool WalletBatch::WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request)
1284 : : {
1285 [ + - + - : 20 : return WriteIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)), receive_request);
+ - ]
1286 : : }
1287 : :
1288 : 1 : bool WalletBatch::EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id)
1289 : : {
1290 [ + - + - : 5 : return EraseIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)));
+ - ]
1291 : : }
1292 : :
1293 : 27 : bool WalletBatch::EraseAddressData(const CTxDestination& dest)
1294 : : {
1295 : 27 : DataStream prefix;
1296 [ + - + - ]: 54 : prefix << DBKeys::DESTDATA << EncodeDestination(dest);
1297 [ + - ]: 27 : return m_batch->ErasePrefix(prefix);
1298 : 27 : }
1299 : :
1300 : 3777 : bool WalletBatch::WriteWalletFlags(const uint64_t flags)
1301 : : {
1302 : 3777 : return WriteIC(DBKeys::FLAGS, flags);
1303 : : }
1304 : :
1305 : 28 : bool WalletBatch::EraseRecords(const std::unordered_set<std::string>& types)
1306 : : {
1307 : 28 : return std::all_of(types.begin(), types.end(), [&](const std::string& type) {
1308 [ + - + - ]: 280 : return m_batch->ErasePrefix(DataStream() << type);
1309 : 28 : });
1310 : : }
1311 : :
1312 : 71848 : bool WalletBatch::TxnBegin()
1313 : : {
1314 : 71848 : return m_batch->TxnBegin();
1315 : : }
1316 : :
1317 : 71845 : bool WalletBatch::TxnCommit()
1318 : : {
1319 : 71845 : bool res = m_batch->TxnCommit();
1320 [ + - ]: 71845 : if (res) {
1321 [ + + ]: 71854 : for (const auto& listener : m_txn_listeners) {
1322 : 9 : listener.on_commit();
1323 : : }
1324 : : // txn finished, clear listeners
1325 : 71845 : m_txn_listeners.clear();
1326 : : }
1327 : 71845 : return res;
1328 : : }
1329 : :
1330 : 1 : bool WalletBatch::TxnAbort()
1331 : : {
1332 : 1 : bool res = m_batch->TxnAbort();
1333 [ + - ]: 1 : if (res) {
1334 [ - + ]: 1 : for (const auto& listener : m_txn_listeners) {
1335 : 0 : listener.on_abort();
1336 : : }
1337 : : // txn finished, clear listeners
1338 : 1 : m_txn_listeners.clear();
1339 : : }
1340 : 1 : return res;
1341 : : }
1342 : :
1343 : 9 : void WalletBatch::RegisterTxnListener(const DbTxnListener& l)
1344 : : {
1345 [ - + ]: 9 : assert(m_batch->HasActiveTxn());
1346 : 9 : m_txn_listeners.emplace_back(l);
1347 : 9 : }
1348 : :
1349 : 1270 : std::unique_ptr<WalletDatabase> MakeDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
1350 : : {
1351 : 1270 : bool exists;
1352 : 1270 : try {
1353 [ + - ]: 1270 : exists = fs::symlink_status(path).type() != fs::file_type::not_found;
1354 [ - - ]: 0 : } catch (const fs::filesystem_error& e) {
1355 [ - - - - : 0 : error = Untranslated(strprintf("Failed to access database path '%s': %s", fs::PathToString(path), e.code().message()));
- - - - ]
1356 : 0 : status = DatabaseStatus::FAILED_BAD_PATH;
1357 : 0 : return nullptr;
1358 : 0 : }
1359 : :
1360 : 1270 : std::optional<DatabaseFormat> format;
1361 [ + + ]: 1270 : if (exists) {
1362 [ + - + + ]: 1500 : if (IsBDBFile(BDBDataFile(path))) {
1363 : 42 : format = DatabaseFormat::BERKELEY_RO;
1364 : : }
1365 [ + - + + ]: 1500 : if (IsSQLiteFile(SQLiteDataFile(path))) {
1366 [ - + ]: 402 : if (format) {
1367 [ # # # # ]: 0 : error = Untranslated(strprintf("Failed to load database path '%s'. Data is in ambiguous format.", fs::PathToString(path)));
1368 : 0 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1369 : 0 : return nullptr;
1370 : : }
1371 : 402 : format = DatabaseFormat::SQLITE;
1372 : : }
1373 [ + + ]: 520 : } else if (options.require_existing) {
1374 [ + - + - ]: 6 : error = Untranslated(strprintf("Failed to load database path '%s'. Path does not exist.", fs::PathToString(path)));
1375 : 3 : status = DatabaseStatus::FAILED_NOT_FOUND;
1376 : 3 : return nullptr;
1377 : : }
1378 : :
1379 [ + + + + ]: 1267 : if (!format && options.require_existing) {
1380 [ + - + - ]: 538 : error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in recognized format.", fs::PathToString(path)));
1381 : 269 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1382 : 269 : return nullptr;
1383 : : }
1384 : :
1385 [ + + + + ]: 998 : if (format && options.require_create) {
1386 [ + - + - ]: 8 : error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", fs::PathToString(path)));
1387 : 4 : status = DatabaseStatus::FAILED_ALREADY_EXISTS;
1388 : 4 : return nullptr;
1389 : : }
1390 : :
1391 : : // BERKELEY_RO can only be opened if require_format was set, which only occurs in migration.
1392 [ + + + + : 994 : if (format && format == DatabaseFormat::BERKELEY_RO && (!options.require_format || options.require_format != DatabaseFormat::BERKELEY_RO)) {
+ + - + ]
1393 [ + - + - ]: 12 : 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).", fs::PathToString(path)));
1394 : 6 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1395 : 6 : return nullptr;
1396 : : }
1397 : :
1398 : : // A db already exists so format is set, but options also specifies the format, so make sure they agree
1399 [ + + + + : 988 : if (format && options.require_format && format != options.require_format) {
+ - ]
1400 [ # # # # ]: 0 : error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in required format.", fs::PathToString(path)));
1401 : 0 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1402 : 0 : return nullptr;
1403 : : }
1404 : :
1405 : : // Format is not set when a db doesn't already exist, so use the format specified by the options if it is set.
1406 [ + + + + ]: 988 : if (!format && options.require_format) format = options.require_format;
1407 : :
1408 [ + + ]: 988 : if (!format) {
1409 : 3 : format = DatabaseFormat::SQLITE;
1410 : : }
1411 : :
1412 [ + - ]: 988 : if (format == DatabaseFormat::SQLITE) {
1413 : 953 : return MakeSQLiteDatabase(path, options, status, error);
1414 : : }
1415 : :
1416 [ + - ]: 35 : if (format == DatabaseFormat::BERKELEY_RO) {
1417 : 35 : return MakeBerkeleyRODatabase(path, options, status, error);
1418 : : }
1419 : :
1420 [ # # ]: 0 : error = Untranslated(STR_INTERNAL_BUG("Could not determine wallet format"));
1421 : 0 : status = DatabaseStatus::FAILED_BAD_FORMAT;
1422 : 0 : return nullptr;
1423 : : }
1424 : : } // namespace wallet
|