LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 70.2 % 961 675
Test Date: 2026-10-13 06:24:39 Functions: 73.3 % 86 63
Branches: 40.9 % 1577 645

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

Generated by: LCOV version 2.5.0-full