LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 93.9 % 967 908
Test Date: 2026-08-25 06:30:02 Functions: 97.7 % 87 85
Branches: 57.6 % 1579 910

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

Generated by: LCOV version 2.0-1