LCOV - code coverage report
Current view: top level - src/wallet - walletdb.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 81.7 % 830 678
Test Date: 2025-03-28 05:06:44 Functions: 97.6 % 84 82
Branches: 49.8 % 1054 525

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

Generated by: LCOV version 2.0-1