LCOV - code coverage report
Current view: top level - src/wallet - walletdb.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 66.8 % 808 540
Test Date: 2024-08-28 04:44:32 Functions: 80.7 % 83 67
Branches: 40.5 % 1026 416

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

Generated by: LCOV version 2.0-1