LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 32.9 % 947 312
Test Date: 2026-06-19 07:35:23 Functions: 40.5 % 84 34
Branches: 16.5 % 1559 257

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

Generated by: LCOV version 2.0-1