LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 93.9 % 917 861
Test Date: 2025-07-10 05:20:26 Functions: 98.8 % 83 82
Branches: 57.1 % 1451 829

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2019-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <hash.h>
       6                 :             : #include <key_io.h>
       7                 :             : #include <logging.h>
       8                 :             : #include <node/types.h>
       9                 :             : #include <outputtype.h>
      10                 :             : #include <script/descriptor.h>
      11                 :             : #include <script/script.h>
      12                 :             : #include <script/sign.h>
      13                 :             : #include <script/solver.h>
      14                 :             : #include <util/bip32.h>
      15                 :             : #include <util/check.h>
      16                 :             : #include <util/strencodings.h>
      17                 :             : #include <util/string.h>
      18                 :             : #include <util/time.h>
      19                 :             : #include <util/translation.h>
      20                 :             : #include <wallet/scriptpubkeyman.h>
      21                 :             : 
      22                 :             : #include <optional>
      23                 :             : 
      24                 :             : using common::PSBTError;
      25                 :             : using util::ToString;
      26                 :             : 
      27                 :             : namespace wallet {
      28                 :             : 
      29                 :             : typedef std::vector<unsigned char> valtype;
      30                 :             : 
      31                 :             : // Legacy wallet IsMine(). Used only in migration
      32                 :             : // DO NOT USE ANYTHING IN THIS NAMESPACE OUTSIDE OF MIGRATION
      33                 :             : namespace {
      34                 :             : 
      35                 :             : /**
      36                 :             :  * This is an enum that tracks the execution context of a script, similar to
      37                 :             :  * SigVersion in script/interpreter. It is separate however because we want to
      38                 :             :  * distinguish between top-level scriptPubKey execution and P2SH redeemScript
      39                 :             :  * execution (a distinction that has no impact on consensus rules).
      40                 :             :  */
      41                 :             : enum class IsMineSigVersion
      42                 :             : {
      43                 :             :     TOP = 0,        //!< scriptPubKey execution
      44                 :             :     P2SH = 1,       //!< P2SH redeemScript
      45                 :             :     WITNESS_V0 = 2, //!< P2WSH witness script execution
      46                 :             : };
      47                 :             : 
      48                 :             : /**
      49                 :             :  * This is an internal representation of isminetype + invalidity.
      50                 :             :  * Its order is significant, as we return the max of all explored
      51                 :             :  * possibilities.
      52                 :             :  */
      53                 :             : enum class IsMineResult
      54                 :             : {
      55                 :             :     NO = 0,         //!< Not ours
      56                 :             :     WATCH_ONLY = 1, //!< Included in watch-only balance
      57                 :             :     SPENDABLE = 2,  //!< Included in all balances
      58                 :             :     INVALID = 3,    //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
      59                 :             : };
      60                 :             : 
      61                 :        2448 : bool PermitsUncompressed(IsMineSigVersion sigversion)
      62                 :             : {
      63                 :        2448 :     return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
      64                 :             : }
      65                 :             : 
      66                 :          42 : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
      67                 :             : {
      68         [ +  + ]:         102 :     for (const valtype& pubkey : pubkeys) {
      69                 :          93 :         CKeyID keyID = CPubKey(pubkey).GetID();
      70         [ +  + ]:          93 :         if (!keystore.HaveKey(keyID)) return false;
      71                 :             :     }
      72                 :             :     return true;
      73                 :             : }
      74                 :             : 
      75                 :             : //! Recursively solve script and return spendable/watchonly/invalid status.
      76                 :             : //!
      77                 :             : //! @param keystore            legacy key and script store
      78                 :             : //! @param scriptPubKey        script to solve
      79                 :             : //! @param sigversion          script type (top-level / redeemscript / witnessscript)
      80                 :             : //! @param recurse_scripthash  whether to recurse into nested p2sh and p2wsh
      81                 :             : //!                            scripts or simply treat any script that has been
      82                 :             : //!                            stored in the keystore as spendable
      83                 :             : // NOLINTNEXTLINE(misc-no-recursion)
      84                 :        6675 : IsMineResult LegacyWalletIsMineInnerDONOTUSE(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
      85                 :             : {
      86                 :        6675 :     IsMineResult ret = IsMineResult::NO;
      87                 :             : 
      88                 :        6675 :     std::vector<valtype> vSolutions;
      89         [ +  - ]:        6675 :     TxoutType whichType = Solver(scriptPubKey, vSolutions);
      90                 :             : 
      91   [ +  +  +  +  :        6675 :     CKeyID keyID;
                +  +  + ]
      92   [ +  +  +  +  :        6675 :     switch (whichType) {
                +  +  + ]
      93                 :             :     case TxoutType::NONSTANDARD:
      94                 :             :     case TxoutType::NULL_DATA:
      95                 :             :     case TxoutType::WITNESS_UNKNOWN:
      96                 :             :     case TxoutType::WITNESS_V1_TAPROOT:
      97                 :             :     case TxoutType::ANCHOR:
      98                 :             :         break;
      99                 :         538 :     case TxoutType::PUBKEY:
     100         [ +  - ]:         538 :         keyID = CPubKey(vSolutions[0]).GetID();
     101   [ -  +  -  - ]:         538 :         if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
     102                 :             :             return IsMineResult::INVALID;
     103                 :             :         }
     104   [ +  -  +  + ]:         538 :         if (keystore.HaveKey(keyID)) {
     105         [ -  + ]:         508 :             ret = std::max(ret, IsMineResult::SPENDABLE);
     106                 :             :         }
     107                 :             :         break;
     108                 :        1323 :     case TxoutType::WITNESS_V0_KEYHASH:
     109                 :        1323 :     {
     110         [ +  - ]:        1323 :         if (sigversion == IsMineSigVersion::WITNESS_V0) {
     111                 :             :             // P2WPKH inside P2WSH is invalid.
     112                 :             :             return IsMineResult::INVALID;
     113                 :             :         }
     114   [ +  +  +  -  :        1862 :         if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
          +  -  +  -  +  
                +  +  + ]
     115                 :             :             // We do not support bare witness outputs unless the P2SH version of it would be
     116                 :             :             // acceptable as well. This protects against matching before segwit activates.
     117                 :             :             // This also applies to the P2WSH case.
     118                 :             :             break;
     119                 :             :         }
     120   [ +  -  +  -  :        1334 :         ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
                   +  + ]
     121                 :        1310 :         break;
     122                 :             :     }
     123                 :        1868 :     case TxoutType::PUBKEYHASH:
     124         [ +  + ]:        1868 :         keyID = CKeyID(uint160(vSolutions[0]));
     125         [ +  + ]:        1868 :         if (!PermitsUncompressed(sigversion)) {
     126         [ +  - ]:        1328 :             CPubKey pubkey;
     127   [ +  -  +  -  :        1328 :             if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
                   +  + ]
     128                 :             :                 return IsMineResult::INVALID;
     129                 :             :             }
     130                 :             :         }
     131   [ +  -  +  + ]:        1863 :         if (keystore.HaveKey(keyID)) {
     132         [ -  + ]:        1797 :             ret = std::max(ret, IsMineResult::SPENDABLE);
     133                 :             :         }
     134                 :             :         break;
     135                 :        1881 :     case TxoutType::SCRIPTHASH:
     136                 :        1881 :     {
     137         [ +  + ]:        1881 :         if (sigversion != IsMineSigVersion::TOP) {
     138                 :             :             // P2SH inside P2WSH or P2SH is invalid.
     139                 :             :             return IsMineResult::INVALID;
     140                 :             :         }
     141         [ +  - ]:        1871 :         CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
     142                 :        1871 :         CScript subscript;
     143   [ +  -  +  + ]:        1871 :         if (keystore.GetCScript(scriptID, subscript)) {
     144   [ +  +  +  -  :         906 :             ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
                   +  + ]
     145                 :             :         }
     146                 :        1871 :         break;
     147                 :        1871 :     }
     148                 :         993 :     case TxoutType::WITNESS_V0_SCRIPTHASH:
     149                 :         993 :     {
     150         [ +  + ]:         993 :         if (sigversion == IsMineSigVersion::WITNESS_V0) {
     151                 :             :             // P2WSH inside P2WSH is invalid.
     152                 :             :             return IsMineResult::INVALID;
     153                 :             :         }
     154   [ +  +  +  -  :        1946 :         if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
          +  -  +  -  +  
                +  +  + ]
     155                 :             :             break;
     156                 :             :         }
     157         [ +  - ]:          71 :         CScriptID scriptID{RIPEMD160(vSolutions[0])};
     158                 :          71 :         CScript subscript;
     159   [ +  -  +  + ]:          71 :         if (keystore.GetCScript(scriptID, subscript)) {
     160   [ +  +  +  -  :          87 :             ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
                   +  + ]
     161                 :             :         }
     162                 :          71 :         break;
     163                 :          71 :     }
     164                 :             : 
     165                 :          48 :     case TxoutType::MULTISIG:
     166                 :          48 :     {
     167                 :             :         // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
     168         [ +  + ]:          48 :         if (sigversion == IsMineSigVersion::TOP) {
     169                 :             :             break;
     170                 :             :         }
     171                 :             : 
     172                 :             :         // Only consider transactions "mine" if we own ALL the
     173                 :             :         // keys involved. Multi-signature transactions that are
     174                 :             :         // partially owned (somebody else has a key that can spend
     175                 :             :         // them) enable spend-out-from-under-you attacks, especially
     176                 :             :         // in shared-wallet situations.
     177         [ +  - ]:          42 :         std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
     178         [ +  + ]:          42 :         if (!PermitsUncompressed(sigversion)) {
     179         [ +  + ]:         104 :             for (size_t i = 0; i < keys.size(); i++) {
     180         [ -  + ]:          75 :                 if (keys[i].size() != 33) {
     181                 :           0 :                     return IsMineResult::INVALID;
     182                 :             :                 }
     183                 :             :             }
     184                 :             :         }
     185   [ +  -  +  + ]:          42 :         if (HaveKeys(keys, keystore)) {
     186         [ -  + ]:           9 :             ret = std::max(ret, IsMineResult::SPENDABLE);
     187                 :             :         }
     188                 :          42 :         break;
     189                 :          42 :     }
     190                 :             :     } // no default case, so the compiler can warn about missing cases
     191                 :             : 
     192   [ +  +  +  -  :        6655 :     if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
                   +  + ]
     193         [ -  + ]:         146 :         ret = std::max(ret, IsMineResult::WATCH_ONLY);
     194                 :             :     }
     195                 :        6655 :     return ret;
     196                 :        6675 : }
     197                 :             : 
     198                 :             : } // namespace
     199                 :             : 
     200                 :        3789 : isminetype LegacyDataSPKM::IsMine(const CScript& script) const
     201                 :             : {
     202      [ +  -  + ]:        3789 :     switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
     203                 :             :     case IsMineResult::INVALID:
     204                 :             :     case IsMineResult::NO:
     205                 :             :         return ISMINE_NO;
     206                 :        2460 :     case IsMineResult::WATCH_ONLY:
     207                 :        2460 :     case IsMineResult::SPENDABLE:
     208                 :        2460 :         return ISMINE_SPENDABLE;
     209                 :             :     }
     210                 :           0 :     assert(false);
     211                 :             : }
     212                 :             : 
     213                 :           1 : bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
     214                 :             : {
     215                 :           1 :     {
     216                 :           1 :         LOCK(cs_KeyStore);
     217         [ -  + ]:           1 :         assert(mapKeys.empty());
     218                 :             : 
     219         [ +  - ]:           1 :         bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
     220                 :           1 :         bool keyFail = false;
     221         [ +  - ]:           1 :         CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
     222   [ +  -  +  - ]:           1 :         WalletBatch batch(m_storage.GetDatabase());
     223         [ +  - ]:           1 :         for (; mi != mapCryptedKeys.end(); ++mi)
     224                 :             :         {
     225         [ +  - ]:           1 :             const CPubKey &vchPubKey = (*mi).second.first;
     226                 :           1 :             const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
     227                 :           1 :             CKey key;
     228   [ +  -  +  - ]:           1 :             if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
     229                 :             :             {
     230                 :             :                 keyFail = true;
     231                 :             :                 break;
     232                 :             :             }
     233                 :           1 :             keyPass = true;
     234         [ -  + ]:           1 :             if (fDecryptionThoroughlyChecked)
     235                 :             :                 break;
     236                 :             :             else {
     237                 :             :                 // Rewrite these encrypted keys with checksums
     238   [ #  #  #  #  :           0 :                 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
                   #  # ]
     239                 :             :             }
     240                 :           1 :         }
     241         [ -  + ]:           1 :         if (keyPass && keyFail)
     242                 :             :         {
     243         [ #  # ]:           0 :             LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
     244         [ #  # ]:           0 :             throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
     245                 :             :         }
     246         [ -  + ]:           1 :         if (keyFail || !keyPass)
     247                 :           0 :             return false;
     248                 :           1 :         fDecryptionThoroughlyChecked = true;
     249   [ -  -  +  - ]:           1 :     }
     250                 :           1 :     return true;
     251                 :             : }
     252                 :             : 
     253                 :          81 : std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
     254                 :             : {
     255                 :          81 :     return std::make_unique<LegacySigningProvider>(*this);
     256                 :             : }
     257                 :             : 
     258                 :         657 : bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
     259                 :             : {
     260                 :         657 :     IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
     261         [ +  + ]:         657 :     if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
     262                 :             :         // If ismine, it means we recognize keys or script ids in the script, or
     263                 :             :         // are watching the script itself, and we can at least provide metadata
     264                 :             :         // or solving information, even if not able to sign fully.
     265                 :             :         return true;
     266                 :             :     } else {
     267                 :             :         // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
     268                 :         632 :         ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
     269         [ +  + ]:         632 :         if (!sigdata.signatures.empty()) {
     270                 :             :             // If we could make signatures, make sure we have a private key to actually make a signature
     271                 :           1 :             bool has_privkeys = false;
     272         [ +  + ]:           2 :             for (const auto& key_sig_pair : sigdata.signatures) {
     273                 :           1 :                 has_privkeys |= HaveKey(key_sig_pair.first);
     274                 :             :             }
     275                 :             :             return has_privkeys;
     276                 :             :         }
     277                 :             :         return false;
     278                 :             :     }
     279                 :             : }
     280                 :             : 
     281                 :         248 : bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
     282                 :             : {
     283                 :         248 :     return AddKeyPubKeyInner(key, pubkey);
     284                 :             : }
     285                 :             : 
     286                 :         158 : bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
     287                 :             : {
     288                 :             :     /* A sanity check was added in pull #3843 to avoid adding redeemScripts
     289                 :             :      * that never can be redeemed. However, old wallets may still contain
     290                 :             :      * these. Do not add them to the wallet and warn. */
     291   [ +  +  -  + ]:         158 :     if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
     292                 :             :     {
     293         [ #  # ]:           0 :         std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
     294   [ #  #  #  # ]:           0 :         WalletLogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
     295                 :           0 :         return true;
     296                 :           0 :     }
     297                 :             : 
     298                 :         158 :     return FillableSigningProvider::AddCScript(redeemScript);
     299                 :             : }
     300                 :             : 
     301                 :         276 : void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
     302                 :             : {
     303                 :         276 :     LOCK(cs_KeyStore);
     304   [ +  -  +  - ]:         276 :     mapKeyMetadata[keyID] = meta;
     305                 :         276 : }
     306                 :             : 
     307                 :          44 : void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
     308                 :             : {
     309                 :          44 :     LOCK(cs_KeyStore);
     310   [ +  -  +  - ]:          44 :     m_script_metadata[script_id] = meta;
     311                 :          44 : }
     312                 :             : 
     313                 :         248 : bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
     314                 :             : {
     315                 :         248 :     LOCK(cs_KeyStore);
     316   [ +  -  +  - ]:         248 :     return FillableSigningProvider::AddKeyPubKey(key, pubkey);
     317                 :         248 : }
     318                 :             : 
     319                 :          24 : bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
     320                 :             : {
     321                 :             :     // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
     322         [ -  + ]:          24 :     if (!checksum_valid) {
     323                 :           0 :         fDecryptionThoroughlyChecked = false;
     324                 :             :     }
     325                 :             : 
     326                 :          24 :     return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
     327                 :             : }
     328                 :             : 
     329                 :          24 : bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
     330                 :             : {
     331                 :          24 :     LOCK(cs_KeyStore);
     332         [ -  + ]:          24 :     assert(mapKeys.empty());
     333                 :             : 
     334   [ +  -  +  -  :          48 :     mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
                   +  - ]
     335         [ +  - ]:          24 :     ImplicitlyLearnRelatedKeyScripts(vchPubKey);
     336         [ +  - ]:          24 :     return true;
     337                 :          24 : }
     338                 :             : 
     339                 :        2160 : bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
     340                 :             : {
     341                 :        2160 :     LOCK(cs_KeyStore);
     342         [ +  - ]:        2160 :     return setWatchOnly.count(dest) > 0;
     343                 :        2160 : }
     344                 :             : 
     345                 :          44 : bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
     346                 :             : {
     347                 :          44 :     return AddWatchOnlyInMem(dest);
     348                 :             : }
     349                 :             : 
     350                 :          44 : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
     351                 :             : {
     352                 :          44 :     std::vector<std::vector<unsigned char>> solutions;
     353   [ +  -  +  +  :          53 :     return Solver(dest, solutions) == TxoutType::PUBKEY &&
                   -  + ]
     354         [ +  - ]:          53 :         (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
     355                 :          44 : }
     356                 :             : 
     357                 :          44 : bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
     358                 :             : {
     359                 :          44 :     LOCK(cs_KeyStore);
     360         [ +  - ]:          44 :     setWatchOnly.insert(dest);
     361         [ +  - ]:          44 :     CPubKey pubKey;
     362   [ +  -  +  + ]:          44 :     if (ExtractPubKey(dest, pubKey)) {
     363   [ +  -  +  - ]:           9 :         mapWatchKeys[pubKey.GetID()] = pubKey;
     364         [ +  - ]:           9 :         ImplicitlyLearnRelatedKeyScripts(pubKey);
     365                 :             :     }
     366         [ +  - ]:          44 :     return true;
     367                 :          44 : }
     368                 :             : 
     369                 :          27 : void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
     370                 :             : {
     371                 :          27 :     LOCK(cs_KeyStore);
     372         [ +  - ]:          27 :     m_hd_chain = chain;
     373                 :          27 : }
     374                 :             : 
     375                 :           6 : void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
     376                 :             : {
     377                 :           6 :     LOCK(cs_KeyStore);
     378         [ -  + ]:           6 :     assert(!chain.seed_id.IsNull());
     379   [ +  -  +  - ]:           6 :     m_inactive_hd_chains[chain.seed_id] = chain;
     380                 :           6 : }
     381                 :             : 
     382                 :        2495 : bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
     383                 :             : {
     384                 :        2495 :     LOCK(cs_KeyStore);
     385   [ +  -  +  + ]:        2495 :     if (!m_storage.HasEncryptionKeys()) {
     386         [ +  - ]:        2441 :         return FillableSigningProvider::HaveKey(address);
     387                 :             :     }
     388                 :          54 :     return mapCryptedKeys.count(address) > 0;
     389                 :        2495 : }
     390                 :             : 
     391                 :        1527 : bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
     392                 :             : {
     393                 :        1527 :     LOCK(cs_KeyStore);
     394   [ +  -  +  + ]:        1527 :     if (!m_storage.HasEncryptionKeys()) {
     395         [ +  - ]:        1520 :         return FillableSigningProvider::GetKey(address, keyOut);
     396                 :             :     }
     397                 :             : 
     398                 :           7 :     CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
     399         [ +  - ]:           7 :     if (mi != mapCryptedKeys.end())
     400                 :             :     {
     401         [ +  - ]:           7 :         const CPubKey &vchPubKey = (*mi).second.first;
     402                 :           7 :         const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
     403   [ +  -  +  - ]:           7 :         return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
     404                 :           7 :             return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
     405                 :             :         });
     406                 :             :     }
     407                 :             :     return false;
     408                 :        1527 : }
     409                 :             : 
     410                 :         125 : bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
     411                 :             : {
     412                 :         125 :     CKeyMetadata meta;
     413                 :         125 :     {
     414         [ +  - ]:         125 :         LOCK(cs_KeyStore);
     415                 :         125 :         auto it = mapKeyMetadata.find(keyID);
     416         [ +  + ]:         125 :         if (it == mapKeyMetadata.end()) {
     417         [ +  - ]:          47 :             return false;
     418                 :             :         }
     419         [ +  - ]:          78 :         meta = it->second;
     420                 :          47 :     }
     421         [ +  + ]:          78 :     if (meta.has_key_origin) {
     422                 :          42 :         std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
     423         [ +  - ]:          42 :         info.path = meta.key_origin.path;
     424                 :             :     } else { // Single pubkeys get the master fingerprint of themselves
     425                 :          36 :         std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
     426                 :             :     }
     427                 :             :     return true;
     428                 :         125 : }
     429                 :             : 
     430                 :          72 : bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
     431                 :             : {
     432                 :          72 :     LOCK(cs_KeyStore);
     433                 :          72 :     WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
     434         [ +  + ]:          72 :     if (it != mapWatchKeys.end()) {
     435                 :          64 :         pubkey_out = it->second;
     436                 :          64 :         return true;
     437                 :             :     }
     438                 :             :     return false;
     439                 :          72 : }
     440                 :             : 
     441                 :        1366 : bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
     442                 :             : {
     443                 :        1366 :     LOCK(cs_KeyStore);
     444   [ +  -  +  + ]:        1366 :     if (!m_storage.HasEncryptionKeys()) {
     445   [ +  -  +  + ]:        1336 :         if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
     446         [ +  - ]:          72 :             return GetWatchPubKey(address, vchPubKeyOut);
     447                 :             :         }
     448                 :             :         return true;
     449                 :             :     }
     450                 :             : 
     451                 :          30 :     CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
     452         [ +  - ]:          30 :     if (mi != mapCryptedKeys.end())
     453                 :             :     {
     454                 :          30 :         vchPubKeyOut = (*mi).second.first;
     455                 :          30 :         return true;
     456                 :             :     }
     457                 :             :     // Check for watch-only pubkeys
     458         [ #  # ]:           0 :     return GetWatchPubKey(address, vchPubKeyOut);
     459                 :        1366 : }
     460                 :             : 
     461                 :          58 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
     462                 :             : {
     463                 :          58 :     LOCK(cs_KeyStore);
     464         [ +  - ]:          58 :     std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
     465                 :             : 
     466                 :             :     // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
     467                 :         566 :     const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
     468         [ +  - ]:         508 :         candidate_spks.insert(GetScriptForRawPubKey(pub));
     469         [ +  - ]:        1016 :         candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
     470                 :             : 
     471         [ +  - ]:         508 :         CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
     472         [ +  - ]:         508 :         candidate_spks.insert(wpkh);
     473   [ +  -  +  - ]:        1016 :         candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
     474                 :         508 :     };
     475   [ +  -  +  + ]:         554 :     for (const auto& [_, key] : mapKeys) {
     476   [ +  -  +  - ]:         496 :         add_pubkey(key.GetPubKey());
     477                 :             :     }
     478   [ +  -  +  + ]:          70 :     for (const auto& [_, ckeypair] : mapCryptedKeys) {
     479         [ +  - ]:          12 :         add_pubkey(ckeypair.first);
     480                 :             :     }
     481                 :             : 
     482                 :             :     // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
     483                 :             :     // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
     484                 :             :     // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
     485                 :             :     // Callers of this function will need to remove such scripts.
     486                 :         728 :     const auto& add_script = [&candidate_spks](const CScript& script) -> void {
     487                 :         670 :         candidate_spks.insert(script);
     488         [ +  - ]:        1340 :         candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
     489                 :             : 
     490         [ +  - ]:         670 :         CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
     491         [ +  - ]:         670 :         candidate_spks.insert(wsh);
     492   [ +  -  +  - ]:        1340 :         candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
     493                 :         670 :     };
     494   [ +  -  +  + ]:         640 :     for (const auto& [_, script] : mapScripts) {
     495         [ +  - ]:         582 :         add_script(script);
     496                 :             :     }
     497                 :             : 
     498                 :             :     // Although setWatchOnly should only contain output scripts, we will also include each script's
     499                 :             :     // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
     500         [ +  + ]:         146 :     for (const auto& script : setWatchOnly) {
     501         [ +  - ]:          88 :         add_script(script);
     502                 :             :     }
     503                 :             : 
     504         [ +  - ]:          58 :     return candidate_spks;
     505                 :          58 : }
     506                 :             : 
     507                 :          29 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
     508                 :             : {
     509                 :             :     // Run IsMine() on each candidate output script. Any script that is not ISMINE_NO is an output
     510                 :             :     // script to return.
     511                 :             :     // This both filters out things that are not watched by the wallet, and things that are invalid.
     512                 :          29 :     std::unordered_set<CScript, SaltedSipHasher> spks;
     513   [ +  -  +  +  :        1767 :     for (const CScript& script : GetCandidateScriptPubKeys()) {
                   +  - ]
     514   [ +  +  +  - ]:        1738 :         if (IsMine(script) != ISMINE_NO) {
     515         [ +  - ]:        1070 :             spks.insert(script);
     516                 :             :         }
     517                 :           0 :     }
     518                 :             : 
     519                 :          29 :     return spks;
     520                 :           0 : }
     521                 :             : 
     522                 :          28 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
     523                 :             : {
     524                 :          28 :     LOCK(cs_KeyStore);
     525         [ +  - ]:          28 :     std::unordered_set<CScript, SaltedSipHasher> spks;
     526         [ +  + ]:          71 :     for (const CScript& script : setWatchOnly) {
     527   [ +  -  +  +  :          43 :         if (IsMine(script) == ISMINE_NO) spks.insert(script);
                   +  - ]
     528                 :             :     }
     529         [ +  - ]:          28 :     return spks;
     530                 :          28 : }
     531                 :             : 
     532                 :          29 : std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
     533                 :             : {
     534                 :          29 :     LOCK(cs_KeyStore);
     535   [ +  -  -  + ]:          29 :     if (m_storage.IsLocked()) {
     536                 :           0 :         return std::nullopt;
     537                 :             :     }
     538                 :             : 
     539                 :          29 :     MigrationData out;
     540                 :             : 
     541         [ +  - ]:          29 :     std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
     542                 :             : 
     543                 :             :     // Get all key ids
     544                 :          29 :     std::set<CKeyID> keyids;
     545         [ +  + ]:         277 :     for (const auto& key_pair : mapKeys) {
     546         [ +  - ]:         248 :         keyids.insert(key_pair.first);
     547                 :             :     }
     548         [ +  + ]:          35 :     for (const auto& key_pair : mapCryptedKeys) {
     549         [ +  - ]:           6 :         keyids.insert(key_pair.first);
     550                 :             :     }
     551                 :             : 
     552                 :             :     // Get key metadata and figure out which keys don't have a seed
     553                 :             :     // Note that we do not ignore the seeds themselves because they are considered IsMine!
     554         [ +  + ]:         283 :     for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
     555                 :         254 :         const CKeyID& keyid = *keyid_it;
     556                 :         254 :         const auto& it = mapKeyMetadata.find(keyid);
     557         [ +  - ]:         254 :         if (it != mapKeyMetadata.end()) {
     558         [ +  + ]:         254 :             const CKeyMetadata& meta = it->second;
     559   [ +  +  +  + ]:         254 :             if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
     560                 :          28 :                 keyid_it++;
     561                 :          28 :                 continue;
     562                 :             :             }
     563   [ +  +  +  +  :         226 :             if (!meta.hd_seed_id.IsNull() && (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.count(meta.hd_seed_id) > 0)) {
             +  -  +  - ]
     564                 :         222 :                 keyid_it = keyids.erase(keyid_it);
     565                 :         222 :                 continue;
     566                 :             :             }
     567                 :             :         }
     568                 :           4 :         keyid_it++;
     569                 :             :     }
     570                 :             : 
     571   [ +  -  +  - ]:          29 :     WalletBatch batch(m_storage.GetDatabase());
     572   [ +  -  -  + ]:          29 :     if (!batch.TxnBegin()) {
     573         [ #  # ]:           0 :         LogPrintf("Error generating descriptors for migration, cannot initialize db transaction\n");
     574                 :           0 :         return std::nullopt;
     575                 :             :     }
     576                 :             : 
     577                 :             :     // keyids is now all non-HD keys. Each key will have its own combo descriptor
     578         [ +  + ]:          61 :     for (const CKeyID& keyid : keyids) {
     579                 :          32 :         CKey key;
     580   [ +  -  -  + ]:          32 :         if (!GetKey(keyid, key)) {
     581                 :           0 :             assert(false);
     582                 :             :         }
     583                 :             : 
     584                 :             :         // Get birthdate from key meta
     585                 :          32 :         uint64_t creation_time = 0;
     586                 :          32 :         const auto& it = mapKeyMetadata.find(keyid);
     587         [ +  - ]:          32 :         if (it != mapKeyMetadata.end()) {
     588                 :          32 :             creation_time = it->second.nCreateTime;
     589                 :             :         }
     590                 :             : 
     591                 :             :         // Get the key origin
     592                 :             :         // Maybe this doesn't matter because floating keys here shouldn't have origins
     593         [ +  - ]:          32 :         KeyOriginInfo info;
     594         [ +  - ]:          32 :         bool has_info = GetKeyOrigin(keyid, info);
     595   [ +  -  +  -  :         160 :         std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
          +  -  +  -  +  
          -  +  -  -  -  
          +  -  +  -  +  
          -  -  -  -  -  
             -  -  -  - ]
     596                 :             : 
     597                 :             :         // Construct the combo descriptor
     598   [ +  -  +  -  :          64 :         std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
             +  -  +  - ]
     599                 :          32 :         FlatSigningProvider keys;
     600         [ +  - ]:          32 :         std::string error;
     601         [ +  - ]:          32 :         std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
     602         [ +  - ]:          32 :         CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
     603   [ +  -  +  -  :          32 :         WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
                   +  - ]
     604                 :             : 
     605                 :             :         // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
     606         [ +  - ]:          32 :         auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
     607   [ +  -  +  -  :          96 :         WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
                   +  - ]
     608         [ +  - ]:          32 :         desc_spk_man->TopUpWithDB(batch);
     609         [ +  - ]:          32 :         auto desc_spks = desc_spk_man->GetScriptPubKeys();
     610                 :             : 
     611                 :             :         // Remove the scriptPubKeys from our current set
     612   [ +  +  +  - ]:         158 :         for (const CScript& spk : desc_spks) {
     613         [ +  - ]:         126 :             size_t erased = spks.erase(spk);
     614         [ -  + ]:         126 :             assert(erased == 1);
     615   [ +  -  -  + ]:         126 :             assert(IsMine(spk) == ISMINE_SPENDABLE);
     616                 :             :         }
     617                 :             : 
     618         [ +  - ]:          32 :         out.desc_spkms.push_back(std::move(desc_spk_man));
     619                 :          32 :     }
     620                 :             : 
     621                 :             :     // Handle HD keys by using the CHDChains
     622                 :          29 :     std::vector<CHDChain> chains;
     623         [ +  - ]:          29 :     chains.push_back(m_hd_chain);
     624   [ +  +  +  - ]:          32 :     for (const auto& chain_pair : m_inactive_hd_chains) {
     625         [ +  - ]:           3 :         chains.push_back(chain_pair.second);
     626                 :             :     }
     627         [ +  + ]:          61 :     for (const CHDChain& chain : chains) {
     628         [ +  + ]:          96 :         for (int i = 0; i < 2; ++i) {
     629                 :             :             // Skip if doing internal chain and split chain is not supported
     630   [ +  +  +  +  :          64 :             if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
             +  -  -  + ]
     631                 :          10 :                 continue;
     632                 :             :             }
     633                 :             :             // Get the master xprv
     634                 :          54 :             CKey seed_key;
     635   [ +  -  -  + ]:          54 :             if (!GetKey(chain.seed_id, seed_key)) {
     636                 :           0 :                 assert(false);
     637                 :             :             }
     638         [ +  - ]:          54 :             CExtKey master_key;
     639   [ +  -  +  - ]:         108 :             master_key.SetSeed(seed_key);
     640                 :             : 
     641                 :             :             // Make the combo descriptor
     642   [ +  -  +  - ]:          54 :             std::string xpub = EncodeExtPubKey(master_key.Neuter());
     643   [ +  -  +  -  :         162 :             std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
                   +  - ]
     644                 :          54 :             FlatSigningProvider keys;
     645         [ +  - ]:          54 :             std::string error;
     646         [ +  - ]:          54 :             std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
     647         [ +  - ]:          54 :             CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
     648         [ +  + ]:          54 :             uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
     649   [ +  -  +  -  :          54 :             WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
                   +  - ]
     650                 :             : 
     651                 :             :             // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
     652         [ +  - ]:          54 :             auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
     653   [ +  -  +  -  :         162 :             WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey()));
                   +  - ]
     654         [ +  - ]:          54 :             desc_spk_man->TopUpWithDB(batch);
     655         [ +  - ]:          54 :             auto desc_spks = desc_spk_man->GetScriptPubKeys();
     656                 :             : 
     657                 :             :             // Remove the scriptPubKeys from our current set
     658   [ +  +  +  - ]:         942 :             for (const CScript& spk : desc_spks) {
     659         [ +  - ]:         888 :                 size_t erased = spks.erase(spk);
     660         [ -  + ]:         888 :                 assert(erased == 1);
     661   [ +  -  -  + ]:         888 :                 assert(IsMine(spk) == ISMINE_SPENDABLE);
     662                 :             :             }
     663                 :             : 
     664         [ +  - ]:          54 :             out.desc_spkms.push_back(std::move(desc_spk_man));
     665                 :          54 :         }
     666                 :             :     }
     667                 :             :     // Add the current master seed to the migration data
     668         [ +  + ]:          29 :     if (!m_hd_chain.seed_id.IsNull()) {
     669                 :          24 :         CKey seed_key;
     670   [ +  -  -  + ]:          24 :         if (!GetKey(m_hd_chain.seed_id, seed_key)) {
     671                 :           0 :             assert(false);
     672                 :             :         }
     673   [ +  -  +  - ]:          48 :         out.master_key.SetSeed(seed_key);
     674                 :          24 :     }
     675                 :             : 
     676                 :             :     // Handle the rest of the scriptPubKeys which must be imports and may not have all info
     677         [ +  + ]:          85 :     for (auto it = spks.begin(); it != spks.end();) {
     678         [ +  - ]:          56 :         const CScript& spk = *it;
     679                 :             : 
     680                 :             :         // Get birthdate from script meta
     681                 :          56 :         uint64_t creation_time = 0;
     682         [ +  - ]:          56 :         const auto& mit = m_script_metadata.find(CScriptID(spk));
     683         [ +  + ]:          56 :         if (mit != m_script_metadata.end()) {
     684                 :          39 :             creation_time = mit->second.nCreateTime;
     685                 :             :         }
     686                 :             : 
     687                 :             :         // InferDescriptor as that will get us all the solving info if it is there
     688   [ +  -  +  - ]:         112 :         std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
     689                 :             : 
     690                 :             :         // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
     691                 :             :         // Re-parse the descriptors to detect that, and skip any that do not parse.
     692                 :          56 :         {
     693         [ +  - ]:          56 :             std::string desc_str = desc->ToString();
     694                 :          56 :             FlatSigningProvider parsed_keys;
     695         [ +  - ]:          56 :             std::string parse_error;
     696         [ +  - ]:          56 :             std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
     697         [ -  + ]:          56 :             if (parsed_descs.empty()) {
     698                 :             :                 // Remove this scriptPubKey from the set
     699                 :           0 :                 it = spks.erase(it);
     700                 :           0 :                 continue;
     701                 :             :             }
     702                 :          56 :         }
     703                 :             : 
     704                 :             :         // Get the private keys for this descriptor
     705                 :          56 :         std::vector<CScript> scripts;
     706                 :          56 :         FlatSigningProvider keys;
     707   [ +  -  -  + ]:          56 :         if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
     708                 :           0 :             assert(false);
     709                 :             :         }
     710                 :          56 :         std::set<CKeyID> privkeyids;
     711         [ +  + ]:         108 :         for (const auto& key_orig_pair : keys.origins) {
     712         [ +  - ]:          52 :             privkeyids.insert(key_orig_pair.first);
     713                 :             :         }
     714                 :             : 
     715                 :          56 :         std::vector<CScript> desc_spks;
     716                 :             : 
     717                 :             :         // Make the descriptor string with private keys
     718         [ +  - ]:          56 :         std::string desc_str;
     719         [ +  - ]:          56 :         bool watchonly = !desc->ToPrivateString(*this, desc_str);
     720   [ +  +  +  -  :          56 :         if (watchonly && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
                   +  + ]
     721   [ +  -  +  - ]:          35 :             out.watch_descs.emplace_back(desc->ToString(), creation_time);
     722                 :             : 
     723                 :             :             // Get the scriptPubKeys without writing this to the wallet
     724                 :          35 :             FlatSigningProvider provider;
     725         [ +  - ]:          35 :             desc->Expand(0, provider, desc_spks, provider);
     726                 :          35 :         } else {
     727                 :             :             // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
     728   [ +  -  +  - ]:          21 :             WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
     729         [ +  - ]:          21 :             auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
     730         [ +  + ]:          48 :             for (const auto& keyid : privkeyids) {
     731                 :          27 :                 CKey key;
     732   [ +  -  +  + ]:          27 :                 if (!GetKey(keyid, key)) {
     733                 :           9 :                     continue;
     734                 :             :                 }
     735   [ +  -  +  -  :          54 :                 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
                   +  - ]
     736                 :          27 :             }
     737         [ +  - ]:          21 :             desc_spk_man->TopUpWithDB(batch);
     738         [ +  - ]:          21 :             auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
     739         [ +  - ]:          21 :             desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
     740                 :             : 
     741         [ +  - ]:          21 :             out.desc_spkms.push_back(std::move(desc_spk_man));
     742                 :          21 :         }
     743                 :             : 
     744                 :             :         // Remove the scriptPubKeys from our current set
     745         [ +  + ]:         112 :         for (const CScript& desc_spk : desc_spks) {
     746         [ +  - ]:          56 :             auto del_it = spks.find(desc_spk);
     747         [ +  - ]:          56 :             assert(del_it != spks.end());
     748   [ +  -  -  + ]:          56 :             assert(IsMine(desc_spk) != ISMINE_NO);
     749                 :          56 :             it = spks.erase(del_it);
     750                 :             :         }
     751                 :          56 :     }
     752                 :             : 
     753                 :             :     // Make sure that we have accounted for all scriptPubKeys
     754         [ -  + ]:          29 :     if (!Assume(spks.empty())) {
     755   [ #  #  #  # ]:           0 :         LogPrintf("%s\n", STR_INTERNAL_BUG("Error: Some output scripts were not migrated.\n"));
     756                 :           0 :         return std::nullopt;
     757                 :             :     }
     758                 :             : 
     759                 :             :     // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
     760                 :             :     // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
     761                 :             :     // be put into the separate "solvables" wallet.
     762                 :             :     // These can be detected by going through the entire candidate output scripts, finding the ISMINE_NO scripts,
     763                 :             :     // and checking CanProvide() which will dummy sign.
     764   [ +  -  +  +  :        1767 :     for (const CScript& script : GetCandidateScriptPubKeys()) {
                   +  - ]
     765                 :             :         // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
     766   [ +  +  +  -  :        1738 :         if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
             +  +  +  - ]
     767                 :         800 :             continue;
     768                 :             :         }
     769   [ +  -  +  + ]:         938 :         if (IsMine(script) != ISMINE_NO) {
     770                 :         281 :             continue;
     771                 :             :         }
     772                 :         657 :         SignatureData dummy_sigdata;
     773   [ +  -  +  + ]:         657 :         if (!CanProvide(script, dummy_sigdata)) {
     774                 :         632 :             continue;
     775                 :             :         }
     776                 :             : 
     777                 :             :         // Get birthdate from script meta
     778                 :          25 :         uint64_t creation_time = 0;
     779         [ +  - ]:          25 :         const auto& it = m_script_metadata.find(CScriptID(script));
     780         [ +  + ]:          25 :         if (it != m_script_metadata.end()) {
     781                 :           4 :             creation_time = it->second.nCreateTime;
     782                 :             :         }
     783                 :             : 
     784                 :             :         // InferDescriptor as that will get us all the solving info if it is there
     785   [ +  -  +  - ]:          25 :         std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
     786   [ +  -  +  + ]:          25 :         if (!desc->IsSolvable()) {
     787                 :             :             // The wallet was able to provide some information, but not enough to make a descriptor that actually
     788                 :             :             // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
     789                 :          10 :             continue;
     790                 :             :         }
     791                 :             : 
     792                 :             :         // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
     793                 :             :         // Re-parse the descriptors to detect that, and skip any that do not parse.
     794                 :          15 :         {
     795         [ +  - ]:          15 :             std::string desc_str = desc->ToString();
     796                 :          15 :             FlatSigningProvider parsed_keys;
     797         [ +  - ]:          15 :             std::string parse_error;
     798         [ +  - ]:          15 :             std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
     799         [ -  + ]:          15 :             if (parsed_descs.empty()) {
     800                 :           0 :                 continue;
     801                 :             :             }
     802                 :          15 :         }
     803                 :             : 
     804   [ +  -  +  - ]:          15 :         out.solvable_descs.emplace_back(desc->ToString(), creation_time);
     805                 :         657 :     }
     806                 :             : 
     807                 :             :     // Finalize transaction
     808   [ +  -  -  + ]:          29 :     if (!batch.TxnCommit()) {
     809         [ #  # ]:           0 :         LogPrintf("Error generating descriptors for migration, cannot commit db transaction\n");
     810                 :           0 :         return std::nullopt;
     811                 :             :     }
     812                 :             : 
     813                 :          29 :     return out;
     814                 :          87 : }
     815                 :             : 
     816                 :          28 : bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
     817                 :             : {
     818                 :          28 :     LOCK(cs_KeyStore);
     819   [ +  -  +  - ]:          28 :     return batch.EraseRecords(DBKeys::LEGACY_TYPES);
     820                 :          28 : }
     821                 :             : 
     822                 :       18186 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
     823                 :             : {
     824                 :             :     // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
     825         [ -  + ]:       18186 :     if (!CanGetAddresses()) {
     826                 :           0 :         return util::Error{_("No addresses available")};
     827                 :             :     }
     828                 :       18186 :     {
     829                 :       18186 :         LOCK(cs_desc_man);
     830   [ +  -  -  + ]:       18186 :         assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
     831         [ +  - ]:       18186 :         std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
     832         [ -  + ]:       18186 :         assert(desc_addr_type);
     833         [ -  + ]:       18186 :         if (type != *desc_addr_type) {
     834   [ #  #  #  # ]:           0 :             throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
     835                 :             :         }
     836                 :             : 
     837         [ +  - ]:       18186 :         TopUp();
     838                 :             : 
     839                 :             :         // Get the scriptPubKey from the descriptor
     840                 :       18186 :         FlatSigningProvider out_keys;
     841                 :       18186 :         std::vector<CScript> scripts_temp;
     842   [ -  +  -  -  :       18186 :         if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
                   -  - ]
     843                 :             :             // We can't generate anymore keys
     844         [ #  # ]:           0 :             return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
     845                 :             :         }
     846   [ +  -  +  + ]:       18186 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
     847                 :             :             // We can't generate anymore keys
     848         [ +  - ]:          24 :             return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
     849                 :             :         }
     850                 :             : 
     851                 :       18178 :         CTxDestination dest;
     852   [ +  -  -  + ]:       18178 :         if (!ExtractDestination(scripts_temp[0], dest)) {
     853         [ #  # ]:           0 :             return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
     854                 :             :         }
     855                 :       18178 :         m_wallet_descriptor.next_index++;
     856   [ +  -  +  -  :       18178 :         WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
             +  -  +  - ]
     857                 :       18178 :         return dest;
     858         [ +  - ]:       36372 :     }
     859                 :             : }
     860                 :             : 
     861                 :      776566 : isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
     862                 :             : {
     863                 :      776566 :     LOCK(cs_desc_man);
     864         [ +  + ]:      776566 :     if (m_map_script_pub_keys.count(script) > 0) {
     865                 :      776540 :         return ISMINE_SPENDABLE;
     866                 :             :     }
     867                 :             :     return ISMINE_NO;
     868                 :      776566 : }
     869                 :             : 
     870                 :         874 : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
     871                 :             : {
     872                 :         874 :     LOCK(cs_desc_man);
     873         [ +  - ]:         874 :     if (!m_map_keys.empty()) {
     874                 :             :         return false;
     875                 :             :     }
     876                 :             : 
     877                 :         874 :     bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
     878                 :         874 :     bool keyFail = false;
     879         [ +  + ]:        1089 :     for (const auto& mi : m_map_crypted_keys) {
     880                 :         736 :         const CPubKey &pubkey = mi.second.first;
     881                 :         736 :         const std::vector<unsigned char> &crypted_secret = mi.second.second;
     882                 :         736 :         CKey key;
     883   [ +  -  +  - ]:         736 :         if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
     884                 :             :             keyFail = true;
     885                 :             :             break;
     886                 :             :         }
     887                 :         736 :         keyPass = true;
     888         [ +  + ]:         736 :         if (m_decryption_thoroughly_checked)
     889                 :             :             break;
     890                 :         736 :     }
     891         [ -  + ]:         874 :     if (keyPass && keyFail) {
     892         [ #  # ]:           0 :         LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
     893         [ #  # ]:           0 :         throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
     894                 :             :     }
     895         [ +  - ]:         874 :     if (keyFail || !keyPass) {
     896                 :             :         return false;
     897                 :             :     }
     898                 :         874 :     m_decryption_thoroughly_checked = true;
     899                 :         874 :     return true;
     900                 :         874 : }
     901                 :             : 
     902                 :         103 : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
     903                 :             : {
     904                 :         103 :     LOCK(cs_desc_man);
     905         [ +  - ]:         103 :     if (!m_map_crypted_keys.empty()) {
     906                 :             :         return false;
     907                 :             :     }
     908                 :             : 
     909         [ +  + ]:         206 :     for (const KeyMap::value_type& key_in : m_map_keys)
     910                 :             :     {
     911                 :         103 :         const CKey &key = key_in.second;
     912         [ +  - ]:         103 :         CPubKey pubkey = key.GetPubKey();
     913   [ +  -  +  -  :         309 :         CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
                   +  - ]
     914                 :         103 :         std::vector<unsigned char> crypted_secret;
     915   [ +  -  +  -  :         103 :         if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
                   -  + ]
     916                 :           0 :             return false;
     917                 :             :         }
     918   [ +  -  +  -  :         206 :         m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
                   +  - ]
     919   [ +  -  +  - ]:         103 :         batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
     920                 :         103 :     }
     921                 :         103 :     m_map_keys.clear();
     922                 :         103 :     return true;
     923                 :         103 : }
     924                 :             : 
     925                 :        1930 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index)
     926                 :             : {
     927                 :        1930 :     LOCK(cs_desc_man);
     928         [ +  - ]:        1930 :     auto op_dest = GetNewDestination(type);
     929                 :        1930 :     index = m_wallet_descriptor.next_index - 1;
     930         [ +  - ]:        1930 :     return op_dest;
     931                 :        1930 : }
     932                 :             : 
     933                 :          83 : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
     934                 :             : {
     935                 :          83 :     LOCK(cs_desc_man);
     936                 :             :     // Only return when the index was the most recent
     937         [ +  - ]:          83 :     if (m_wallet_descriptor.next_index - 1 == index) {
     938                 :          83 :         m_wallet_descriptor.next_index--;
     939                 :             :     }
     940   [ +  -  +  -  :          83 :     WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
             +  -  +  - ]
     941         [ +  - ]:          83 :     NotifyCanGetAddressesChanged();
     942                 :          83 : }
     943                 :             : 
     944                 :       85331 : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
     945                 :             : {
     946                 :       85331 :     AssertLockHeld(cs_desc_man);
     947   [ +  +  +  + ]:       85331 :     if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
     948                 :        2286 :         KeyMap keys;
     949         [ +  + ]:        4572 :         for (const auto& key_pair : m_map_crypted_keys) {
     950                 :        2286 :             const CPubKey& pubkey = key_pair.second.first;
     951                 :        2286 :             const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
     952                 :        2286 :             CKey key;
     953   [ +  -  +  - ]:        2286 :             m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
     954                 :        2286 :                 return DecryptKey(encryption_key, crypted_secret, pubkey, key);
     955                 :             :             });
     956   [ +  -  +  -  :        2286 :             keys[pubkey.GetID()] = key;
                   +  - ]
     957                 :        2286 :         }
     958                 :             :         return keys;
     959                 :           0 :     }
     960                 :       83045 :     return m_map_keys;
     961                 :             : }
     962                 :             : 
     963                 :         225 : bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
     964                 :             : {
     965                 :         225 :     AssertLockHeld(cs_desc_man);
     966   [ +  +  +  + ]:         225 :     return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
     967                 :             : }
     968                 :             : 
     969                 :          72 : std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
     970                 :             : {
     971                 :          72 :     AssertLockHeld(cs_desc_man);
     972   [ +  +  +  - ]:          72 :     if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
     973                 :           9 :         const auto& it = m_map_crypted_keys.find(keyid);
     974         [ -  + ]:           9 :         if (it == m_map_crypted_keys.end()) {
     975                 :           0 :             return std::nullopt;
     976                 :             :         }
     977         [ +  - ]:           9 :         const std::vector<unsigned char>& crypted_secret = it->second.second;
     978                 :           9 :         CKey key;
     979   [ +  -  +  -  :          18 :         if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
                   -  + ]
     980                 :             :             return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
     981                 :             :         }))) {
     982                 :           0 :             return std::nullopt;
     983                 :             :         }
     984                 :           9 :         return key;
     985                 :           9 :     }
     986                 :          63 :     const auto& it = m_map_keys.find(keyid);
     987         [ +  + ]:          63 :     if (it == m_map_keys.end()) {
     988                 :           1 :         return std::nullopt;
     989                 :             :     }
     990                 :          62 :     return it->second;
     991                 :             : }
     992                 :             : 
     993                 :       69709 : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
     994                 :             : {
     995                 :       69709 :     WalletBatch batch(m_storage.GetDatabase());
     996   [ +  -  +  - ]:       69709 :     if (!batch.TxnBegin()) return false;
     997         [ +  - ]:       69709 :     bool res = TopUpWithDB(batch, size);
     998   [ +  -  -  +  :       69709 :     if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
          -  -  -  -  -  
                      - ]
     999                 :             :     return res;
    1000                 :       69709 : }
    1001                 :             : 
    1002                 :       72842 : bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
    1003                 :             : {
    1004                 :       72842 :     LOCK(cs_desc_man);
    1005         [ +  + ]:       72842 :     std::set<CScript> new_spks;
    1006                 :       72842 :     unsigned int target_size;
    1007         [ +  + ]:       72842 :     if (size > 0) {
    1008                 :             :         target_size = size;
    1009                 :             :     } else {
    1010                 :       72770 :         target_size = m_keypool_size;
    1011                 :             :     }
    1012                 :             : 
    1013                 :             :     // Calculate the new range_end
    1014         [ +  + ]:       72842 :     int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
    1015                 :             : 
    1016                 :             :     // If the descriptor is not ranged, we actually just want to fill the first cache item
    1017   [ +  -  +  + ]:       72842 :     if (!m_wallet_descriptor.descriptor->IsRange()) {
    1018                 :       12730 :         new_range_end = 1;
    1019                 :       12730 :         m_wallet_descriptor.range_end = 1;
    1020                 :       12730 :         m_wallet_descriptor.range_start = 0;
    1021                 :             :     }
    1022                 :             : 
    1023                 :       72842 :     FlatSigningProvider provider;
    1024         [ +  - ]:      145684 :     provider.keys = GetKeys();
    1025                 :             : 
    1026         [ +  - ]:       72842 :     uint256 id = GetID();
    1027         [ +  + ]:      495480 :     for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
    1028                 :      422745 :         FlatSigningProvider out_keys;
    1029                 :      422745 :         std::vector<CScript> scripts_temp;
    1030                 :      422745 :         DescriptorCache temp_cache;
    1031                 :             :         // Maybe we have a cached xpub and we can expand from the cache first
    1032   [ +  -  +  + ]:      422745 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
    1033   [ +  -  +  + ]:       13564 :             if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
    1034                 :             :         }
    1035                 :             :         // Add all of the scriptPubKeys to the scriptPubKey set
    1036         [ +  - ]:      422638 :         new_spks.insert(scripts_temp.begin(), scripts_temp.end());
    1037         [ +  + ]:      846579 :         for (const CScript& script : scripts_temp) {
    1038         [ +  - ]:      423941 :             m_map_script_pub_keys[script] = i;
    1039                 :             :         }
    1040         [ +  + ]:      892503 :         for (const auto& pk_pair : out_keys.pubkeys) {
    1041                 :      469865 :             const CPubKey& pubkey = pk_pair.second;
    1042         [ +  + ]:      469865 :             if (m_map_pubkeys.count(pubkey) != 0) {
    1043                 :             :                 // We don't need to give an error here.
    1044                 :             :                 // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and its private key
    1045                 :       10268 :                 continue;
    1046                 :             :             }
    1047         [ +  - ]:      459597 :             m_map_pubkeys[pubkey] = i;
    1048                 :             :         }
    1049                 :             :         // Merge and write the cache
    1050         [ +  - ]:      422638 :         DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
    1051   [ +  -  -  + ]:      422638 :         if (!batch.WriteDescriptorCacheItems(id, new_items)) {
    1052   [ #  #  #  # ]:           0 :             throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
    1053                 :             :         }
    1054                 :      422638 :         m_max_cached_index++;
    1055                 :      422745 :     }
    1056                 :       72735 :     m_wallet_descriptor.range_end = new_range_end;
    1057   [ +  -  +  - ]:       72735 :     batch.WriteDescriptor(GetID(), m_wallet_descriptor);
    1058                 :             : 
    1059                 :             :     // By this point, the cache size should be the size of the entire range
    1060         [ -  + ]:       72735 :     assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
    1061                 :             : 
    1062         [ +  - ]:       72735 :     m_storage.TopUpCallback(new_spks, this);
    1063         [ +  - ]:       72735 :     NotifyCanGetAddressesChanged();
    1064                 :             :     return true;
    1065         [ +  - ]:      145684 : }
    1066                 :             : 
    1067                 :       46046 : std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
    1068                 :             : {
    1069                 :       46046 :     LOCK(cs_desc_man);
    1070                 :       46046 :     std::vector<WalletDestination> result;
    1071   [ +  -  +  - ]:       46046 :     if (IsMine(script)) {
    1072         [ +  - ]:       46046 :         int32_t index = m_map_script_pub_keys[script];
    1073         [ +  + ]:       46046 :         if (index >= m_wallet_descriptor.next_index) {
    1074         [ +  - ]:         502 :             WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
    1075         [ +  - ]:         502 :             auto out_keys = std::make_unique<FlatSigningProvider>();
    1076                 :         502 :             std::vector<CScript> scripts_temp;
    1077         [ +  + ]:       28894 :             while (index >= m_wallet_descriptor.next_index) {
    1078   [ +  -  -  + ]:       28392 :                 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
    1079   [ #  #  #  # ]:           0 :                     throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
    1080                 :             :                 }
    1081                 :       28392 :                 CTxDestination dest;
    1082         [ +  - ]:       28392 :                 ExtractDestination(scripts_temp[0], dest);
    1083                 :       28392 :                 result.push_back({dest, std::nullopt});
    1084                 :       28392 :                 m_wallet_descriptor.next_index++;
    1085                 :       28392 :             }
    1086         [ +  - ]:        1004 :         }
    1087   [ +  -  -  + ]:       46046 :         if (!TopUp()) {
    1088         [ #  # ]:           0 :             WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
    1089                 :             :         }
    1090                 :             :     }
    1091                 :             : 
    1092         [ +  - ]:       46046 :     return result;
    1093   [ +  -  +  - ]:      102830 : }
    1094                 :             : 
    1095                 :         508 : void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
    1096                 :             : {
    1097                 :         508 :     LOCK(cs_desc_man);
    1098   [ +  -  +  - ]:         508 :     WalletBatch batch(m_storage.GetDatabase());
    1099   [ +  -  -  + ]:         508 :     if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
    1100   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
    1101                 :             :     }
    1102         [ +  - ]:        1016 : }
    1103                 :             : 
    1104                 :        3622 : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
    1105                 :             : {
    1106                 :        3622 :     AssertLockHeld(cs_desc_man);
    1107         [ -  + ]:        3622 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
    1108                 :             : 
    1109                 :             :     // Check if provided key already exists
    1110   [ +  +  -  + ]:        7236 :     if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
    1111         [ -  + ]:        3614 :         m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
    1112                 :           8 :         return true;
    1113                 :             :     }
    1114                 :             : 
    1115         [ +  + ]:        3614 :     if (m_storage.HasEncryptionKeys()) {
    1116         [ +  - ]:         162 :         if (m_storage.IsLocked()) {
    1117                 :             :             return false;
    1118                 :             :         }
    1119                 :             : 
    1120                 :         162 :         std::vector<unsigned char> crypted_secret;
    1121   [ +  -  +  -  :         486 :         CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
                   +  - ]
    1122   [ +  -  +  -  :         162 :         if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
                   +  - ]
    1123                 :         162 :                 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
    1124                 :             :             })) {
    1125                 :             :             return false;
    1126                 :             :         }
    1127                 :             : 
    1128   [ +  -  +  -  :         324 :         m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
                   +  - ]
    1129   [ +  -  +  - ]:         162 :         return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
    1130                 :         162 :     } else {
    1131                 :        3452 :         m_map_keys[pubkey.GetID()] = key;
    1132   [ +  -  +  - ]:        3452 :         return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
    1133                 :             :     }
    1134                 :             : }
    1135                 :             : 
    1136                 :        3010 : bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
    1137                 :             : {
    1138                 :        3010 :     LOCK(cs_desc_man);
    1139   [ +  -  -  + ]:        3010 :     assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    1140                 :             : 
    1141                 :             :     // Ignore when there is already a descriptor
    1142         [ +  - ]:        3010 :     if (m_wallet_descriptor.descriptor) {
    1143                 :             :         return false;
    1144                 :             :     }
    1145                 :             : 
    1146   [ +  -  +  - ]:        3010 :     m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
    1147                 :             : 
    1148                 :             :     // Store the master private key, and descriptor
    1149   [ +  -  +  -  :        3010 :     if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
                   -  + ]
    1150   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
    1151                 :             :     }
    1152   [ +  -  +  -  :        3010 :     if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
                   -  + ]
    1153   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
    1154                 :             :     }
    1155                 :             : 
    1156                 :             :     // TopUp
    1157         [ +  - ]:        3010 :     TopUpWithDB(batch);
    1158                 :             : 
    1159         [ +  - ]:        3010 :     m_storage.UnsetBlankWalletFlag(batch);
    1160                 :             :     return true;
    1161                 :        3010 : }
    1162                 :             : 
    1163                 :          77 : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
    1164                 :             : {
    1165                 :          77 :     LOCK(cs_desc_man);
    1166   [ +  -  +  - ]:          77 :     return m_wallet_descriptor.descriptor->IsRange();
    1167                 :          77 : }
    1168                 :             : 
    1169                 :       28521 : bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
    1170                 :             : {
    1171                 :             :     // We can only give out addresses from descriptors that are single type (not combo), ranged,
    1172                 :             :     // and either have cached keys or can generate more keys (ignoring encryption)
    1173                 :       28521 :     LOCK(cs_desc_man);
    1174   [ +  -  +  - ]:       57042 :     return m_wallet_descriptor.descriptor->IsSingleType() &&
    1175   [ +  -  +  -  :       57042 :            m_wallet_descriptor.descriptor->IsRange() &&
                   +  + ]
    1176   [ +  -  -  +  :       57042 :            (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
                   +  - ]
    1177                 :       28521 : }
    1178                 :             : 
    1179                 :      325209 : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
    1180                 :             : {
    1181                 :      325209 :     LOCK(cs_desc_man);
    1182   [ +  +  +  +  :      354138 :     return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
                   +  - ]
    1183                 :      325209 : }
    1184                 :             : 
    1185                 :           0 : bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
    1186                 :             : {
    1187                 :           0 :     LOCK(cs_desc_man);
    1188         [ #  # ]:           0 :     return !m_map_crypted_keys.empty();
    1189                 :           0 : }
    1190                 :             : 
    1191                 :        8460 : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
    1192                 :             : {
    1193                 :        8460 :     LOCK(cs_desc_man);
    1194         [ +  - ]:        8460 :     return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
    1195                 :        8460 : }
    1196                 :             : 
    1197                 :       11006 : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
    1198                 :             : {
    1199                 :       11006 :     LOCK(cs_desc_man);
    1200         [ +  - ]:       11006 :     return m_wallet_descriptor.creation_time;
    1201                 :       11006 : }
    1202                 :             : 
    1203                 :      404884 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
    1204                 :             : {
    1205                 :      404884 :     LOCK(cs_desc_man);
    1206                 :             : 
    1207                 :             :     // Find the index of the script
    1208                 :      404884 :     auto it = m_map_script_pub_keys.find(script);
    1209         [ +  + ]:      404884 :     if (it == m_map_script_pub_keys.end()) {
    1210                 :      108810 :         return nullptr;
    1211                 :             :     }
    1212         [ +  - ]:      296074 :     int32_t index = it->second;
    1213                 :             : 
    1214         [ +  - ]:      296074 :     return GetSigningProvider(index, include_private);
    1215                 :      404884 : }
    1216                 :             : 
    1217                 :       17506 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
    1218                 :             : {
    1219                 :       17506 :     LOCK(cs_desc_man);
    1220                 :             : 
    1221                 :             :     // Find index of the pubkey
    1222                 :       17506 :     auto it = m_map_pubkeys.find(pubkey);
    1223         [ +  + ]:       17506 :     if (it == m_map_pubkeys.end()) {
    1224                 :       16906 :         return nullptr;
    1225                 :             :     }
    1226         [ +  - ]:         600 :     int32_t index = it->second;
    1227                 :             : 
    1228                 :             :     // Always try to get the signing provider with private keys. This function should only be called during signing anyways
    1229         [ +  - ]:         600 :     std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
    1230   [ +  -  +  -  :         600 :     if (!out->HaveKey(pubkey.GetID())) {
                   +  + ]
    1231                 :         299 :         return nullptr;
    1232                 :             :     }
    1233                 :         301 :     return out;
    1234                 :       18106 : }
    1235                 :             : 
    1236                 :      296674 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
    1237                 :             : {
    1238                 :      296674 :     AssertLockHeld(cs_desc_man);
    1239                 :             : 
    1240                 :      296674 :     std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
    1241                 :             : 
    1242                 :             :     // Fetch SigningProvider from cache to avoid re-deriving
    1243                 :      296674 :     auto it = m_map_signing_providers.find(index);
    1244         [ +  + ]:      296674 :     if (it != m_map_signing_providers.end()) {
    1245   [ +  -  +  - ]:      280653 :         out_keys->Merge(FlatSigningProvider{it->second});
    1246                 :             :     } else {
    1247                 :             :         // Get the scripts, keys, and key origins for this script
    1248                 :       16021 :         std::vector<CScript> scripts_temp;
    1249   [ +  -  -  + ]:       16021 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
    1250                 :             : 
    1251                 :             :         // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
    1252   [ +  -  +  - ]:       16021 :         m_map_signing_providers[index] = *out_keys;
    1253                 :       16021 :     }
    1254                 :             : 
    1255   [ +  -  +  +  :      296674 :     if (HavePrivateKeys() && include_private) {
                   +  + ]
    1256                 :       11181 :         FlatSigningProvider master_provider;
    1257         [ +  - ]:       22362 :         master_provider.keys = GetKeys();
    1258         [ +  - ]:       11181 :         m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
    1259                 :       11181 :     }
    1260                 :             : 
    1261                 :      296674 :     return out_keys;
    1262                 :      296674 : }
    1263                 :             : 
    1264                 :      347495 : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
    1265                 :             : {
    1266         [ -  + ]:      347495 :     return GetSigningProvider(script, false);
    1267                 :             : }
    1268                 :             : 
    1269                 :      364803 : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
    1270                 :             : {
    1271                 :      364803 :     return IsMine(script);
    1272                 :             : }
    1273                 :             : 
    1274                 :       16416 : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
    1275                 :             : {
    1276                 :       16416 :     std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
    1277         [ +  + ]:       55501 :     for (const auto& coin_pair : coins) {
    1278         [ +  - ]:       39085 :         std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
    1279         [ +  + ]:       39085 :         if (!coin_keys) {
    1280                 :       29788 :             continue;
    1281                 :             :         }
    1282         [ +  - ]:        9297 :         keys->Merge(std::move(*coin_keys));
    1283                 :       39085 :     }
    1284                 :             : 
    1285   [ +  -  +  - ]:       16416 :     return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
    1286                 :       16416 : }
    1287                 :             : 
    1288                 :           9 : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
    1289                 :             : {
    1290   [ +  -  +  - ]:          18 :     std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
    1291         [ +  - ]:           9 :     if (!keys) {
    1292                 :             :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
    1293                 :             :     }
    1294                 :             : 
    1295                 :           9 :     CKey key;
    1296   [ +  -  +  -  :           9 :     if (!keys->GetKey(ToKeyID(pkhash), key)) {
                   +  - ]
    1297                 :             :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
    1298                 :             :     }
    1299                 :             : 
    1300   [ +  -  -  + ]:           9 :     if (!MessageSign(key, message, str_sig)) {
    1301                 :           0 :         return SigningResult::SIGNING_FAILED;
    1302                 :             :     }
    1303                 :             :     return SigningResult::OK;
    1304                 :          18 : }
    1305                 :             : 
    1306                 :        5815 : std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, std::optional<int> sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
    1307                 :             : {
    1308         [ +  - ]:        5815 :     if (n_signed) {
    1309                 :        5815 :         *n_signed = 0;
    1310                 :             :     }
    1311         [ +  + ]:       30045 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
    1312                 :       24238 :         const CTxIn& txin = psbtx.tx->vin[i];
    1313                 :       24238 :         PSBTInput& input = psbtx.inputs.at(i);
    1314                 :             : 
    1315         [ +  + ]:       24238 :         if (PSBTInputSigned(input)) {
    1316                 :        6402 :             continue;
    1317                 :             :         }
    1318                 :             : 
    1319                 :             :         // Get the scriptPubKey to know which SigningProvider to use
    1320                 :       17836 :         CScript script;
    1321         [ +  + ]:       17836 :         if (!input.witness_utxo.IsNull()) {
    1322                 :       12547 :             script = input.witness_utxo.scriptPubKey;
    1323         [ +  + ]:        5289 :         } else if (input.non_witness_utxo) {
    1324         [ +  + ]:        5092 :             if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
    1325                 :           1 :                 return PSBTError::MISSING_INPUTS;
    1326                 :             :             }
    1327                 :        5091 :             script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
    1328                 :             :         } else {
    1329                 :             :             // There's no UTXO so we can just skip this now
    1330                 :         197 :             continue;
    1331                 :             :         }
    1332                 :             : 
    1333         [ +  - ]:       17638 :         std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
    1334         [ +  - ]:       17638 :         std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
    1335         [ +  + ]:       17638 :         if (script_keys) {
    1336         [ +  - ]:        2792 :             keys->Merge(std::move(*script_keys));
    1337                 :             :         } else {
    1338                 :             :             // Maybe there are pubkeys listed that we can sign for
    1339                 :       14846 :             std::vector<CPubKey> pubkeys;
    1340         [ +  - ]:       14846 :             pubkeys.reserve(input.hd_keypaths.size() + 2);
    1341                 :             : 
    1342                 :             :             // ECDSA Pubkeys
    1343   [ +  -  +  + ]:       25600 :             for (const auto& [pk, _] : input.hd_keypaths) {
    1344         [ +  - ]:       10754 :                 pubkeys.push_back(pk);
    1345                 :             :             }
    1346                 :             : 
    1347                 :             :             // Taproot output pubkey
    1348                 :       14846 :             std::vector<std::vector<unsigned char>> sols;
    1349   [ +  -  +  + ]:       14846 :             if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
    1350         [ +  - ]:        1046 :                 sols[0].insert(sols[0].begin(), 0x02);
    1351         [ +  - ]:        1046 :                 pubkeys.emplace_back(sols[0]);
    1352         [ +  - ]:        1046 :                 sols[0][0] = 0x03;
    1353         [ +  - ]:        1046 :                 pubkeys.emplace_back(sols[0]);
    1354                 :             :             }
    1355                 :             : 
    1356                 :             :             // Taproot pubkeys
    1357         [ +  + ]:       17175 :             for (const auto& pk_pair : input.m_tap_bip32_paths) {
    1358                 :        2329 :                 const XOnlyPubKey& pubkey = pk_pair.first;
    1359         [ +  + ]:        6987 :                 for (unsigned char prefix : {0x02, 0x03}) {
    1360                 :        4658 :                     unsigned char b[33] = {prefix};
    1361                 :        4658 :                     std::copy(pubkey.begin(), pubkey.end(), b + 1);
    1362                 :        4658 :                     CPubKey fullpubkey;
    1363                 :        4658 :                     fullpubkey.Set(b, b + 33);
    1364         [ +  - ]:        4658 :                     pubkeys.push_back(fullpubkey);
    1365                 :             :                 }
    1366                 :             :             }
    1367                 :             : 
    1368         [ +  + ]:       32350 :             for (const auto& pubkey : pubkeys) {
    1369         [ +  - ]:       17504 :                 std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
    1370         [ +  + ]:       17504 :                 if (pk_keys) {
    1371         [ +  - ]:         300 :                     keys->Merge(std::move(*pk_keys));
    1372                 :             :                 }
    1373                 :       17504 :             }
    1374                 :       14846 :         }
    1375                 :             : 
    1376   [ +  -  +  + ]:       17638 :         PSBTError res = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
    1377         [ +  + ]:       17638 :         if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
    1378         [ -  + ]:           7 :             return res;
    1379                 :             :         }
    1380                 :             : 
    1381         [ +  - ]:       17631 :         bool signed_one = PSBTInputSigned(input);
    1382   [ +  -  +  + ]:       17631 :         if (n_signed && (signed_one || !sign)) {
    1383                 :             :             // If sign is false, we assume that we _could_ sign if we get here. This
    1384                 :             :             // will never have false negatives; it is hard to tell under what i
    1385                 :             :             // circumstances it could have false positives.
    1386                 :       12916 :             (*n_signed)++;
    1387                 :             :         }
    1388   [ +  -  +  - ]:       35481 :     }
    1389                 :             : 
    1390                 :             :     // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
    1391         [ +  + ]:       70817 :     for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
    1392                 :       65844 :         std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
    1393         [ +  + ]:       65010 :         if (!keys) {
    1394                 :       64176 :             continue;
    1395                 :             :         }
    1396         [ +  - ]:         834 :         UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
    1397                 :       65010 :     }
    1398                 :             : 
    1399                 :        5807 :     return {};
    1400                 :             : }
    1401                 :             : 
    1402                 :         657 : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
    1403                 :             : {
    1404         [ +  - ]:         657 :     std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
    1405         [ +  - ]:         657 :     if (provider) {
    1406         [ +  - ]:         657 :         KeyOriginInfo orig;
    1407         [ +  - ]:         657 :         CKeyID key_id = GetKeyForDestination(*provider, dest);
    1408   [ +  -  +  + ]:         657 :         if (provider->GetKeyOrigin(key_id, orig)) {
    1409         [ +  - ]:         571 :             LOCK(cs_desc_man);
    1410         [ +  - ]:         571 :             std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
    1411         [ +  - ]:         571 :             meta->key_origin = orig;
    1412         [ +  - ]:         571 :             meta->has_key_origin = true;
    1413                 :         571 :             meta->nCreateTime = m_wallet_descriptor.creation_time;
    1414         [ +  - ]:         571 :             return meta;
    1415                 :         571 :         }
    1416                 :         657 :     }
    1417                 :          86 :     return nullptr;
    1418                 :         657 : }
    1419                 :             : 
    1420                 :      178293 : uint256 DescriptorScriptPubKeyMan::GetID() const
    1421                 :             : {
    1422                 :      178293 :     LOCK(cs_desc_man);
    1423         [ +  - ]:      178293 :     return m_wallet_descriptor.id;
    1424                 :      178293 : }
    1425                 :             : 
    1426                 :        2388 : void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
    1427                 :             : {
    1428                 :        2388 :     LOCK(cs_desc_man);
    1429         [ +  - ]:        2388 :     std::set<CScript> new_spks;
    1430         [ +  - ]:        2388 :     m_wallet_descriptor.cache = cache;
    1431         [ +  + ]:       59728 :     for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
    1432                 :       57340 :         FlatSigningProvider out_keys;
    1433                 :       57340 :         std::vector<CScript> scripts_temp;
    1434   [ +  -  -  + ]:       57340 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
    1435         [ #  # ]:           0 :             throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
    1436                 :             :         }
    1437                 :             :         // Add all of the scriptPubKeys to the scriptPubKey set
    1438         [ +  - ]:       57340 :         new_spks.insert(scripts_temp.begin(), scripts_temp.end());
    1439         [ +  + ]:      115815 :         for (const CScript& script : scripts_temp) {
    1440         [ -  + ]:       58475 :             if (m_map_script_pub_keys.count(script) != 0) {
    1441   [ #  #  #  #  :           0 :                 throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
                   #  # ]
    1442                 :             :             }
    1443         [ +  - ]:       58475 :             m_map_script_pub_keys[script] = i;
    1444                 :             :         }
    1445         [ +  + ]:      118693 :         for (const auto& pk_pair : out_keys.pubkeys) {
    1446                 :       61353 :             const CPubKey& pubkey = pk_pair.second;
    1447         [ -  + ]:       61353 :             if (m_map_pubkeys.count(pubkey) != 0) {
    1448                 :             :                 // We don't need to give an error here.
    1449                 :             :                 // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and its private key
    1450                 :           0 :                 continue;
    1451                 :             :             }
    1452         [ +  - ]:       61353 :             m_map_pubkeys[pubkey] = i;
    1453                 :             :         }
    1454                 :       57340 :         m_max_cached_index++;
    1455                 :       57340 :     }
    1456                 :             :     // Make sure the wallet knows about our new spks
    1457         [ +  - ]:        2388 :     m_storage.TopUpCallback(new_spks, this);
    1458         [ +  - ]:        4776 : }
    1459                 :             : 
    1460                 :        2064 : bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
    1461                 :             : {
    1462                 :        2064 :     LOCK(cs_desc_man);
    1463   [ +  -  +  - ]:        2064 :     m_map_keys[key_id] = key;
    1464         [ +  - ]:        2064 :     return true;
    1465                 :        2064 : }
    1466                 :             : 
    1467                 :         231 : bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
    1468                 :             : {
    1469                 :         231 :     LOCK(cs_desc_man);
    1470         [ +  - ]:         231 :     if (!m_map_keys.empty()) {
    1471                 :             :         return false;
    1472                 :             :     }
    1473                 :             : 
    1474   [ +  -  +  - ]:         462 :     m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
    1475                 :         231 :     return true;
    1476                 :         231 : }
    1477                 :             : 
    1478                 :          40 : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
    1479                 :             : {
    1480                 :          40 :     LOCK(cs_desc_man);
    1481   [ +  -  +  -  :          40 :     return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
             -  +  +  - ]
    1482                 :          40 : }
    1483                 :             : 
    1484                 :         694 : void DescriptorScriptPubKeyMan::WriteDescriptor()
    1485                 :             : {
    1486                 :         694 :     LOCK(cs_desc_man);
    1487   [ +  -  +  - ]:         694 :     WalletBatch batch(m_storage.GetDatabase());
    1488   [ +  -  +  -  :         694 :     if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
                   -  + ]
    1489   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
    1490                 :             :     }
    1491         [ +  - ]:        1388 : }
    1492                 :             : 
    1493                 :       55009 : WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
    1494                 :             : {
    1495                 :       55009 :     return m_wallet_descriptor;
    1496                 :             : }
    1497                 :             : 
    1498                 :         426 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
    1499                 :             : {
    1500                 :         426 :     return GetScriptPubKeys(0);
    1501                 :             : }
    1502                 :             : 
    1503                 :         551 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
    1504                 :             : {
    1505                 :         551 :     LOCK(cs_desc_man);
    1506         [ +  - ]:         551 :     std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
    1507         [ +  - ]:         551 :     script_pub_keys.reserve(m_map_script_pub_keys.size());
    1508                 :             : 
    1509   [ +  +  +  + ]:       37664 :     for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
    1510   [ +  +  +  - ]:       37113 :         if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
    1511                 :             :     }
    1512         [ +  - ]:         551 :     return script_pub_keys;
    1513                 :         551 : }
    1514                 :             : 
    1515                 :        4968 : int32_t DescriptorScriptPubKeyMan::GetEndRange() const
    1516                 :             : {
    1517                 :        4968 :     return m_max_cached_index + 1;
    1518                 :             : }
    1519                 :             : 
    1520                 :        1204 : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
    1521                 :             : {
    1522                 :        1204 :     LOCK(cs_desc_man);
    1523                 :             : 
    1524                 :        1204 :     FlatSigningProvider provider;
    1525         [ +  - ]:        2408 :     provider.keys = GetKeys();
    1526                 :             : 
    1527         [ +  + ]:        1204 :     if (priv) {
    1528                 :             :         // For the private version, always return the master key to avoid
    1529                 :             :         // exposing child private keys. The risk implications of exposing child
    1530                 :             :         // private keys together with the parent xpub may be non-obvious for users.
    1531         [ +  - ]:          64 :         return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
    1532                 :             :     }
    1533                 :             : 
    1534         [ +  - ]:        1140 :     return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
    1535         [ +  - ]:        2408 : }
    1536                 :             : 
    1537                 :         326 : void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
    1538                 :             : {
    1539                 :         326 :     LOCK(cs_desc_man);
    1540   [ +  -  +  -  :         326 :     if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
             +  -  -  + ]
    1541                 :           0 :         return;
    1542                 :             :     }
    1543                 :             : 
    1544                 :             :     // Skip if we have the last hardened xpub cache
    1545   [ +  -  +  + ]:         326 :     if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
    1546                 :             :         return;
    1547                 :             :     }
    1548                 :             : 
    1549                 :             :     // Expand the descriptor
    1550                 :         104 :     FlatSigningProvider provider;
    1551         [ +  - ]:         208 :     provider.keys = GetKeys();
    1552                 :         104 :     FlatSigningProvider out_keys;
    1553                 :         104 :     std::vector<CScript> scripts_temp;
    1554                 :         104 :     DescriptorCache temp_cache;
    1555   [ +  -  -  + ]:         104 :     if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
    1556         [ #  # ]:           0 :         throw std::runtime_error("Unable to expand descriptor");
    1557                 :             :     }
    1558                 :             : 
    1559                 :             :     // Cache the last hardened xpubs
    1560         [ +  - ]:         104 :     DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
    1561   [ +  -  +  -  :         208 :     if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
          +  -  +  -  -  
                      + ]
    1562   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
    1563                 :             :     }
    1564         [ +  - ]:         430 : }
    1565                 :             : 
    1566                 :          20 : util::Result<void> DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
    1567                 :             : {
    1568                 :          20 :     LOCK(cs_desc_man);
    1569         [ +  - ]:          20 :     std::string error;
    1570   [ +  -  +  + ]:          20 :     if (!CanUpdateToWalletDescriptor(descriptor, error)) {
    1571         [ +  - ]:           9 :         return util::Error{Untranslated(std::move(error))};
    1572                 :             :     }
    1573                 :             : 
    1574                 :          17 :     m_map_pubkeys.clear();
    1575                 :          17 :     m_map_script_pub_keys.clear();
    1576                 :          17 :     m_max_cached_index = -1;
    1577         [ +  - ]:          17 :     m_wallet_descriptor = descriptor;
    1578                 :             : 
    1579         [ +  - ]:          17 :     NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
    1580                 :          17 :     return {};
    1581         [ +  - ]:          40 : }
    1582                 :             : 
    1583                 :          20 : bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
    1584                 :             : {
    1585                 :          20 :     LOCK(cs_desc_man);
    1586   [ +  -  -  + ]:          20 :     if (!HasWalletDescriptor(descriptor)) {
    1587   [ -  -  +  - ]:          20 :         error = "can only update matching descriptor";
    1588                 :             :         return false;
    1589                 :             :     }
    1590                 :             : 
    1591   [ +  -  +  + ]:          20 :     if (!descriptor.descriptor->IsRange()) {
    1592                 :             :         // Skip range check for non-range descriptors
    1593                 :             :         return true;
    1594                 :             :     }
    1595                 :             : 
    1596         [ +  + ]:          15 :     if (descriptor.range_start > m_wallet_descriptor.range_start ||
    1597         [ +  + ]:          13 :         descriptor.range_end < m_wallet_descriptor.range_end) {
    1598                 :             :         // Use inclusive range for error
    1599                 :           6 :         error = strprintf("new range must include current range = [%d,%d]",
    1600                 :           3 :                           m_wallet_descriptor.range_start,
    1601         [ +  - ]:           3 :                           m_wallet_descriptor.range_end - 1);
    1602                 :           3 :         return false;
    1603                 :             :     }
    1604                 :             : 
    1605                 :             :     return true;
    1606                 :          20 : }
    1607                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1