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