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