LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 16.2 % 1818 294
Test Date: 2024-07-04 04:02:30 Functions: 25.0 % 140 35
Branches: 6.9 % 3106 214

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2019-2022 The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <hash.h>
       6                 :             : #include <key_io.h>
       7                 :             : #include <logging.h>
       8                 :             : #include <node/types.h>
       9                 :             : #include <outputtype.h>
      10                 :             : #include <script/descriptor.h>
      11                 :             : #include <script/script.h>
      12                 :             : #include <script/sign.h>
      13                 :             : #include <script/solver.h>
      14                 :             : #include <util/bip32.h>
      15                 :             : #include <util/check.h>
      16                 :             : #include <util/strencodings.h>
      17                 :             : #include <util/string.h>
      18                 :             : #include <util/time.h>
      19                 :             : #include <util/translation.h>
      20                 :             : #include <wallet/scriptpubkeyman.h>
      21                 :             : 
      22                 :             : #include <optional>
      23                 :             : 
      24                 :             : using common::PSBTError;
      25                 :             : using util::ToString;
      26                 :             : 
      27                 :             : namespace wallet {
      28                 :             : //! Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value. See BIP 32 for more details.
      29                 :             : const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
      30                 :             : 
      31                 :           0 : util::Result<CTxDestination> LegacyScriptPubKeyMan::GetNewDestination(const OutputType type)
      32                 :             : {
      33         [ #  # ]:           0 :     if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
      34         [ #  # ]:           0 :         return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
      35                 :             :     }
      36         [ #  # ]:           0 :     assert(type != OutputType::BECH32M);
      37                 :             : 
      38                 :             :     // Fill-up keypool if needed
      39                 :           0 :     TopUp();
      40                 :             : 
      41                 :           0 :     LOCK(cs_KeyStore);
      42                 :             : 
      43                 :             :     // Generate a new key that is added to wallet
      44         [ #  # ]:           0 :     CPubKey new_key;
      45   [ #  #  #  # ]:           0 :     if (!GetKeyFromPool(new_key, type)) {
      46   [ #  #  #  # ]:           0 :         return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
      47                 :             :     }
      48         [ #  # ]:           0 :     LearnRelatedScripts(new_key, type);
      49   [ #  #  #  # ]:           0 :     return GetDestinationForKey(new_key, type);
      50                 :           0 : }
      51                 :             : 
      52                 :             : typedef std::vector<unsigned char> valtype;
      53                 :             : 
      54                 :             : namespace {
      55                 :             : 
      56                 :             : /**
      57                 :             :  * This is an enum that tracks the execution context of a script, similar to
      58                 :             :  * SigVersion in script/interpreter. It is separate however because we want to
      59                 :             :  * distinguish between top-level scriptPubKey execution and P2SH redeemScript
      60                 :             :  * execution (a distinction that has no impact on consensus rules).
      61                 :             :  */
      62                 :             : enum class IsMineSigVersion
      63                 :             : {
      64                 :             :     TOP = 0,        //!< scriptPubKey execution
      65                 :             :     P2SH = 1,       //!< P2SH redeemScript
      66                 :             :     WITNESS_V0 = 2, //!< P2WSH witness script execution
      67                 :             : };
      68                 :             : 
      69                 :             : /**
      70                 :             :  * This is an internal representation of isminetype + invalidity.
      71                 :             :  * Its order is significant, as we return the max of all explored
      72                 :             :  * possibilities.
      73                 :             :  */
      74                 :             : enum class IsMineResult
      75                 :             : {
      76                 :             :     NO = 0,         //!< Not ours
      77                 :             :     WATCH_ONLY = 1, //!< Included in watch-only balance
      78                 :             :     SPENDABLE = 2,  //!< Included in all balances
      79                 :             :     INVALID = 3,    //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
      80                 :             : };
      81                 :             : 
      82                 :           0 : bool PermitsUncompressed(IsMineSigVersion sigversion)
      83                 :             : {
      84         [ #  # ]:           0 :     return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
      85                 :             : }
      86                 :             : 
      87                 :           0 : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyScriptPubKeyMan& keystore)
      88                 :             : {
      89   [ #  #  #  #  :           0 :     for (const valtype& pubkey : pubkeys) {
                      # ]
      90                 :           0 :         CKeyID keyID = CPubKey(pubkey).GetID();
      91         [ #  # ]:           0 :         if (!keystore.HaveKey(keyID)) return false;
      92   [ #  #  #  # ]:           0 :     }
      93                 :           0 :     return true;
      94                 :           0 : }
      95                 :             : 
      96                 :             : //! Recursively solve script and return spendable/watchonly/invalid status.
      97                 :             : //!
      98                 :             : //! @param keystore            legacy key and script store
      99                 :             : //! @param scriptPubKey        script to solve
     100                 :             : //! @param sigversion          script type (top-level / redeemscript / witnessscript)
     101                 :             : //! @param recurse_scripthash  whether to recurse into nested p2sh and p2wsh
     102                 :             : //!                            scripts or simply treat any script that has been
     103                 :             : //!                            stored in the keystore as spendable
     104                 :             : // NOLINTNEXTLINE(misc-no-recursion)
     105                 :           0 : IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
     106                 :             : {
     107                 :           0 :     IsMineResult ret = IsMineResult::NO;
     108                 :             : 
     109                 :           0 :     std::vector<valtype> vSolutions;
     110         [ #  # ]:           0 :     TxoutType whichType = Solver(scriptPubKey, vSolutions);
     111                 :             : 
     112         [ #  # ]:           0 :     CKeyID keyID;
     113   [ #  #  #  #  :           0 :     switch (whichType) {
             #  #  #  # ]
     114                 :             :     case TxoutType::NONSTANDARD:
     115                 :             :     case TxoutType::NULL_DATA:
     116                 :             :     case TxoutType::WITNESS_UNKNOWN:
     117                 :             :     case TxoutType::WITNESS_V1_TAPROOT:
     118                 :           0 :         break;
     119                 :             :     case TxoutType::PUBKEY:
     120   [ #  #  #  #  :           0 :         keyID = CPubKey(vSolutions[0]).GetID();
                   #  # ]
     121   [ #  #  #  #  :           0 :         if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
                   #  # ]
     122                 :           0 :             return IsMineResult::INVALID;
     123                 :             :         }
     124   [ #  #  #  # ]:           0 :         if (keystore.HaveKey(keyID)) {
     125         [ #  # ]:           0 :             ret = std::max(ret, IsMineResult::SPENDABLE);
     126                 :           0 :         }
     127                 :           0 :         break;
     128                 :             :     case TxoutType::WITNESS_V0_KEYHASH:
     129                 :             :     {
     130         [ #  # ]:           0 :         if (sigversion == IsMineSigVersion::WITNESS_V0) {
     131                 :             :             // P2WPKH inside P2WSH is invalid.
     132                 :           0 :             return IsMineResult::INVALID;
     133                 :             :         }
     134   [ #  #  #  #  :           0 :         if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                #  #  # ]
     135                 :             :             // We do not support bare witness outputs unless the P2SH version of it would be
     136                 :             :             // acceptable as well. This protects against matching before segwit activates.
     137                 :             :             // This also applies to the P2WSH case.
     138                 :           0 :             break;
     139                 :             :         }
     140   [ #  #  #  #  :           0 :         ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
          #  #  #  #  #  
                #  #  # ]
     141                 :           0 :         break;
     142                 :             :     }
     143                 :             :     case TxoutType::PUBKEYHASH:
     144   [ #  #  #  #  :           0 :         keyID = CKeyID(uint160(vSolutions[0]));
                   #  # ]
     145   [ #  #  #  # ]:           0 :         if (!PermitsUncompressed(sigversion)) {
     146         [ #  # ]:           0 :             CPubKey pubkey;
     147   [ #  #  #  #  :           0 :             if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
             #  #  #  # ]
     148                 :           0 :                 return IsMineResult::INVALID;
     149                 :             :             }
     150         [ #  # ]:           0 :         }
     151   [ #  #  #  # ]:           0 :         if (keystore.HaveKey(keyID)) {
     152         [ #  # ]:           0 :             ret = std::max(ret, IsMineResult::SPENDABLE);
     153                 :           0 :         }
     154                 :           0 :         break;
     155                 :             :     case TxoutType::SCRIPTHASH:
     156                 :             :     {
     157         [ #  # ]:           0 :         if (sigversion != IsMineSigVersion::TOP) {
     158                 :             :             // P2SH inside P2WSH or P2SH is invalid.
     159                 :           0 :             return IsMineResult::INVALID;
     160                 :             :         }
     161   [ #  #  #  #  :           0 :         CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
                   #  # ]
     162         [ #  # ]:           0 :         CScript subscript;
     163   [ #  #  #  # ]:           0 :         if (keystore.GetCScript(scriptID, subscript)) {
     164   [ #  #  #  #  :           0 :             ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
                   #  # ]
     165                 :           0 :         }
     166                 :             :         break;
     167                 :           0 :     }
     168                 :             :     case TxoutType::WITNESS_V0_SCRIPTHASH:
     169                 :             :     {
     170         [ #  # ]:           0 :         if (sigversion == IsMineSigVersion::WITNESS_V0) {
     171                 :             :             // P2WSH inside P2WSH is invalid.
     172                 :           0 :             return IsMineResult::INVALID;
     173                 :             :         }
     174   [ #  #  #  #  :           0 :         if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                #  #  # ]
     175                 :           0 :             break;
     176                 :             :         }
     177   [ #  #  #  #  :           0 :         CScriptID scriptID{RIPEMD160(vSolutions[0])};
                   #  # ]
     178         [ #  # ]:           0 :         CScript subscript;
     179   [ #  #  #  # ]:           0 :         if (keystore.GetCScript(scriptID, subscript)) {
     180   [ #  #  #  #  :           0 :             ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
                   #  # ]
     181                 :           0 :         }
     182                 :             :         break;
     183                 :           0 :     }
     184                 :             : 
     185                 :             :     case TxoutType::MULTISIG:
     186                 :             :     {
     187                 :             :         // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
     188         [ #  # ]:           0 :         if (sigversion == IsMineSigVersion::TOP) {
     189                 :           0 :             break;
     190                 :             :         }
     191                 :             : 
     192                 :             :         // Only consider transactions "mine" if we own ALL the
     193                 :             :         // keys involved. Multi-signature transactions that are
     194                 :             :         // partially owned (somebody else has a key that can spend
     195                 :             :         // them) enable spend-out-from-under-you attacks, especially
     196                 :             :         // in shared-wallet situations.
     197         [ #  # ]:           0 :         std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
     198   [ #  #  #  # ]:           0 :         if (!PermitsUncompressed(sigversion)) {
     199   [ #  #  #  # ]:           0 :             for (size_t i = 0; i < keys.size(); i++) {
     200         [ #  # ]:           0 :                 if (keys[i].size() != 33) {
     201                 :           0 :                     return IsMineResult::INVALID;
     202                 :             :                 }
     203                 :           0 :             }
     204                 :           0 :         }
     205   [ #  #  #  # ]:           0 :         if (HaveKeys(keys, keystore)) {
     206         [ #  # ]:           0 :             ret = std::max(ret, IsMineResult::SPENDABLE);
     207                 :           0 :         }
     208                 :           0 :         break;
     209         [ #  # ]:           0 :     }
     210                 :             :     } // no default case, so the compiler can warn about missing cases
     211                 :             : 
     212   [ #  #  #  #  :           0 :     if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
                   #  # ]
     213         [ #  # ]:           0 :         ret = std::max(ret, IsMineResult::WATCH_ONLY);
     214                 :           0 :     }
     215                 :           0 :     return ret;
     216                 :           0 : }
     217                 :             : 
     218                 :             : } // namespace
     219                 :             : 
     220                 :           0 : isminetype LegacyScriptPubKeyMan::IsMine(const CScript& script) const
     221                 :             : {
     222   [ #  #  #  # ]:           0 :     switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
     223                 :             :     case IsMineResult::INVALID:
     224                 :             :     case IsMineResult::NO:
     225                 :           0 :         return ISMINE_NO;
     226                 :             :     case IsMineResult::WATCH_ONLY:
     227                 :           0 :         return ISMINE_WATCH_ONLY;
     228                 :             :     case IsMineResult::SPENDABLE:
     229                 :           0 :         return ISMINE_SPENDABLE;
     230                 :             :     }
     231                 :           0 :     assert(false);
     232                 :           0 : }
     233                 :             : 
     234                 :           0 : bool LegacyScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
     235                 :             : {
     236                 :             :     {
     237                 :           0 :         LOCK(cs_KeyStore);
     238         [ #  # ]:           0 :         assert(mapKeys.empty());
     239                 :             : 
     240                 :           0 :         bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
     241                 :           0 :         bool keyFail = false;
     242                 :           0 :         CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
     243   [ #  #  #  # ]:           0 :         WalletBatch batch(m_storage.GetDatabase());
     244         [ #  # ]:           0 :         for (; mi != mapCryptedKeys.end(); ++mi)
     245                 :             :         {
     246                 :           0 :             const CPubKey &vchPubKey = (*mi).second.first;
     247                 :           0 :             const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
     248                 :           0 :             CKey key;
     249   [ #  #  #  # ]:           0 :             if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
     250                 :             :             {
     251                 :           0 :                 keyFail = true;
     252                 :           0 :                 break;
     253                 :             :             }
     254                 :           0 :             keyPass = true;
     255         [ #  # ]:           0 :             if (fDecryptionThoroughlyChecked)
     256                 :           0 :                 break;
     257                 :             :             else {
     258                 :             :                 // Rewrite these encrypted keys with checksums
     259   [ #  #  #  #  :           0 :                 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
                   #  # ]
     260                 :             :             }
     261         [ #  # ]:           0 :         }
     262   [ #  #  #  # ]:           0 :         if (keyPass && keyFail)
     263                 :             :         {
     264   [ #  #  #  #  :           0 :             LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
                   #  # ]
     265         [ #  # ]:           0 :             throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
     266                 :             :         }
     267   [ #  #  #  # ]:           0 :         if (keyFail || !keyPass)
     268                 :           0 :             return false;
     269                 :           0 :         fDecryptionThoroughlyChecked = true;
     270         [ #  # ]:           0 :     }
     271                 :           0 :     return true;
     272                 :           0 : }
     273                 :             : 
     274                 :           0 : bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
     275                 :             : {
     276                 :           0 :     LOCK(cs_KeyStore);
     277                 :           0 :     encrypted_batch = batch;
     278         [ #  # ]:           0 :     if (!mapCryptedKeys.empty()) {
     279                 :           0 :         encrypted_batch = nullptr;
     280                 :           0 :         return false;
     281                 :             :     }
     282                 :             : 
     283                 :           0 :     KeyMap keys_to_encrypt;
     284                 :           0 :     keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
     285   [ #  #  #  # ]:           0 :     for (const KeyMap::value_type& mKey : keys_to_encrypt)
     286                 :             :     {
     287                 :           0 :         const CKey &key = mKey.second;
     288         [ #  # ]:           0 :         CPubKey vchPubKey = key.GetPubKey();
     289   [ #  #  #  #  :           0 :         CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
          #  #  #  #  #  
                      # ]
     290                 :           0 :         std::vector<unsigned char> vchCryptedSecret;
     291   [ #  #  #  #  :           0 :         if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
                   #  # ]
     292                 :           0 :             encrypted_batch = nullptr;
     293                 :           0 :             return false;
     294                 :             :         }
     295   [ #  #  #  # ]:           0 :         if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
     296                 :           0 :             encrypted_batch = nullptr;
     297                 :           0 :             return false;
     298                 :             :         }
     299   [ #  #  #  # ]:           0 :     }
     300                 :           0 :     encrypted_batch = nullptr;
     301                 :           0 :     return true;
     302                 :           0 : }
     303                 :             : 
     304                 :           0 : util::Result<CTxDestination> LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
     305                 :             : {
     306         [ #  # ]:           0 :     if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
     307         [ #  # ]:           0 :         return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
     308                 :             :     }
     309         [ #  # ]:           0 :     assert(type != OutputType::BECH32M);
     310                 :             : 
     311                 :           0 :     LOCK(cs_KeyStore);
     312   [ #  #  #  # ]:           0 :     if (!CanGetAddresses(internal)) {
     313   [ #  #  #  # ]:           0 :         return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
     314                 :             :     }
     315                 :             : 
     316                 :             :     // Fill-up keypool if needed
     317         [ #  # ]:           0 :     TopUp();
     318                 :             : 
     319   [ #  #  #  # ]:           0 :     if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
     320   [ #  #  #  # ]:           0 :         return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
     321                 :             :     }
     322   [ #  #  #  # ]:           0 :     return GetDestinationForKey(keypool.vchPubKey, type);
     323                 :           0 : }
     324                 :             : 
     325                 :           0 : bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
     326                 :             : {
     327                 :           0 :     LOCK(cs_KeyStore);
     328                 :             : 
     329         [ #  # ]:           0 :     auto it = m_inactive_hd_chains.find(seed_id);
     330         [ #  # ]:           0 :     if (it == m_inactive_hd_chains.end()) {
     331                 :           0 :         return false;
     332                 :             :     }
     333                 :             : 
     334                 :           0 :     CHDChain& chain = it->second;
     335                 :             : 
     336         [ #  # ]:           0 :     if (internal) {
     337         [ #  # ]:           0 :         chain.m_next_internal_index = std::max(chain.m_next_internal_index, index + 1);
     338                 :           0 :     } else {
     339         [ #  # ]:           0 :         chain.m_next_external_index = std::max(chain.m_next_external_index, index + 1);
     340                 :             :     }
     341                 :             : 
     342   [ #  #  #  # ]:           0 :     WalletBatch batch(m_storage.GetDatabase());
     343         [ #  # ]:           0 :     TopUpChain(batch, chain, 0);
     344                 :             : 
     345                 :           0 :     return true;
     346                 :           0 : }
     347                 :             : 
     348                 :           0 : std::vector<WalletDestination> LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
     349                 :             : {
     350                 :           0 :     LOCK(cs_KeyStore);
     351                 :           0 :     std::vector<WalletDestination> result;
     352                 :             :     // extract addresses and check if they match with an unused keypool key
     353   [ #  #  #  # ]:           0 :     for (const auto& keyid : GetAffectedKeys(script, *this)) {
     354         [ #  # ]:           0 :         std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
     355         [ #  # ]:           0 :         if (mi != m_pool_key_to_index.end()) {
     356         [ #  # ]:           0 :             WalletLogPrintf("%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
     357   [ #  #  #  # ]:           0 :             for (const auto& keypool : MarkReserveKeysAsUsed(mi->second)) {
     358                 :             :                 // derive all possible destinations as any of them could have been used
     359         [ #  # ]:           0 :                 for (const auto& type : LEGACY_OUTPUT_TYPES) {
     360         [ #  # ]:           0 :                     const auto& dest = GetDestinationForKey(keypool.vchPubKey, type);
     361   [ #  #  #  # ]:           0 :                     result.push_back({dest, keypool.fInternal});
     362                 :           0 :                 }
     363                 :           0 :             }
     364                 :             : 
     365   [ #  #  #  # ]:           0 :             if (!TopUp()) {
     366         [ #  # ]:           0 :                 WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
     367                 :           0 :             }
     368                 :           0 :         }
     369                 :             : 
     370                 :             :         // Find the key's metadata and check if it's seed id (if it has one) is inactive, i.e. it is not the current m_hd_chain seed id.
     371                 :             :         // If so, TopUp the inactive hd chain
     372         [ #  # ]:           0 :         auto it = mapKeyMetadata.find(keyid);
     373         [ #  # ]:           0 :         if (it != mapKeyMetadata.end()){
     374         [ #  # ]:           0 :             CKeyMetadata meta = it->second;
     375   [ #  #  #  #  :           0 :             if (!meta.hd_seed_id.IsNull() && meta.hd_seed_id != m_hd_chain.seed_id) {
             #  #  #  # ]
     376                 :           0 :                 std::vector<uint32_t> path;
     377         [ #  # ]:           0 :                 if (meta.has_key_origin) {
     378         [ #  # ]:           0 :                     path = meta.key_origin.path;
     379   [ #  #  #  # ]:           0 :                 } else if (!ParseHDKeypath(meta.hdKeypath, path)) {
     380         [ #  # ]:           0 :                     WalletLogPrintf("%s: Adding inactive seed keys failed, invalid hdKeypath: %s\n",
     381                 :             :                                     __func__,
     382         [ #  # ]:           0 :                                     meta.hdKeypath);
     383                 :           0 :                 }
     384         [ #  # ]:           0 :                 if (path.size() != 3) {
     385         [ #  # ]:           0 :                     WalletLogPrintf("%s: Adding inactive seed keys failed, invalid path size: %d, has_key_origin: %s\n",
     386                 :             :                                     __func__,
     387                 :           0 :                                     path.size(),
     388                 :           0 :                                     meta.has_key_origin);
     389                 :           0 :                 } else {
     390                 :           0 :                     bool internal = (path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
     391                 :           0 :                     int64_t index = path[2] & ~BIP32_HARDENED_KEY_LIMIT;
     392                 :             : 
     393   [ #  #  #  # ]:           0 :                     if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
     394         [ #  # ]:           0 :                         WalletLogPrintf("%s: Adding inactive seed keys failed\n", __func__);
     395                 :           0 :                     }
     396                 :           0 :                 }
     397                 :           0 :             }
     398                 :           0 :         }
     399                 :           0 :     }
     400                 :             : 
     401                 :           0 :     return result;
     402         [ #  # ]:           0 : }
     403                 :             : 
     404                 :           0 : void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
     405                 :             : {
     406                 :           0 :     LOCK(cs_KeyStore);
     407   [ #  #  #  #  :           0 :     if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
             #  #  #  # ]
     408                 :           0 :         return;
     409                 :             :     }
     410                 :             : 
     411   [ #  #  #  # ]:           0 :     std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
     412         [ #  # ]:           0 :     for (auto& meta_pair : mapKeyMetadata) {
     413                 :           0 :         CKeyMetadata& meta = meta_pair.second;
     414   [ #  #  #  #  :           0 :         if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin && meta.hdKeypath != "s") { // If the hdKeypath is "s", that's the seed and it doesn't have a key origin
          #  #  #  #  #  
                      # ]
     415                 :           0 :             CKey key;
     416         [ #  # ]:           0 :             GetKey(meta.hd_seed_id, key);
     417         [ #  # ]:           0 :             CExtKey masterKey;
     418   [ #  #  #  # ]:           0 :             masterKey.SetSeed(key);
     419                 :             :             // Add to map
     420   [ #  #  #  # ]:           0 :             CKeyID master_id = masterKey.key.GetPubKey().GetID();
     421   [ #  #  #  #  :           0 :             std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
                   #  # ]
     422   [ #  #  #  # ]:           0 :             if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
     423         [ #  # ]:           0 :                 throw std::runtime_error("Invalid stored hdKeypath");
     424                 :             :             }
     425                 :           0 :             meta.has_key_origin = true;
     426         [ #  # ]:           0 :             if (meta.nVersion < CKeyMetadata::VERSION_WITH_KEY_ORIGIN) {
     427                 :           0 :                 meta.nVersion = CKeyMetadata::VERSION_WITH_KEY_ORIGIN;
     428                 :           0 :             }
     429                 :             : 
     430                 :             :             // Write meta to wallet
     431         [ #  # ]:           0 :             CPubKey pubkey;
     432   [ #  #  #  # ]:           0 :             if (GetPubKey(meta_pair.first, pubkey)) {
     433         [ #  # ]:           0 :                 batch->WriteKeyMetadata(meta, pubkey, true);
     434                 :           0 :             }
     435                 :           0 :         }
     436                 :           0 :     }
     437                 :           0 : }
     438                 :             : 
     439                 :           0 : bool LegacyScriptPubKeyMan::SetupGeneration(bool force)
     440                 :             : {
     441   [ #  #  #  # ]:           0 :     if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
     442                 :           0 :         return false;
     443                 :             :     }
     444                 :             : 
     445                 :           0 :     SetHDSeed(GenerateNewSeed());
     446         [ #  # ]:           0 :     if (!NewKeyPool()) {
     447                 :           0 :         return false;
     448                 :             :     }
     449                 :           0 :     return true;
     450                 :           0 : }
     451                 :             : 
     452                 :           0 : bool LegacyScriptPubKeyMan::IsHDEnabled() const
     453                 :             : {
     454                 :           0 :     return !m_hd_chain.seed_id.IsNull();
     455                 :             : }
     456                 :             : 
     457                 :           0 : bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
     458                 :             : {
     459                 :           0 :     LOCK(cs_KeyStore);
     460                 :             :     // Check if the keypool has keys
     461                 :           0 :     bool keypool_has_keys;
     462   [ #  #  #  #  :           0 :     if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
                   #  # ]
     463                 :           0 :         keypool_has_keys = setInternalKeyPool.size() > 0;
     464                 :           0 :     } else {
     465         [ #  # ]:           0 :         keypool_has_keys = KeypoolCountExternalKeys() > 0;
     466                 :             :     }
     467                 :             :     // If the keypool doesn't have keys, check if we can generate them
     468         [ #  # ]:           0 :     if (!keypool_has_keys) {
     469         [ #  # ]:           0 :         return CanGenerateKeys();
     470                 :             :     }
     471                 :           0 :     return keypool_has_keys;
     472                 :           0 : }
     473                 :             : 
     474                 :           0 : bool LegacyScriptPubKeyMan::Upgrade(int prev_version, int new_version, bilingual_str& error)
     475                 :             : {
     476                 :           0 :     LOCK(cs_KeyStore);
     477                 :             : 
     478   [ #  #  #  # ]:           0 :     if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     479                 :             :         // Nothing to do here if private keys are not enabled
     480                 :           0 :         return true;
     481                 :             :     }
     482                 :             : 
     483                 :           0 :     bool hd_upgrade = false;
     484                 :           0 :     bool split_upgrade = false;
     485   [ #  #  #  #  :           0 :     if (IsFeatureSupported(new_version, FEATURE_HD) && !IsHDEnabled()) {
             #  #  #  # ]
     486         [ #  # ]:           0 :         WalletLogPrintf("Upgrading wallet to HD\n");
     487         [ #  # ]:           0 :         m_storage.SetMinVersion(FEATURE_HD);
     488                 :             : 
     489                 :             :         // generate a new master key
     490         [ #  # ]:           0 :         CPubKey masterPubKey = GenerateNewSeed();
     491         [ #  # ]:           0 :         SetHDSeed(masterPubKey);
     492                 :           0 :         hd_upgrade = true;
     493                 :           0 :     }
     494                 :             :     // Upgrade to HD chain split if necessary
     495   [ #  #  #  #  :           0 :     if (!IsFeatureSupported(prev_version, FEATURE_HD_SPLIT) && IsFeatureSupported(new_version, FEATURE_HD_SPLIT)) {
             #  #  #  # ]
     496         [ #  # ]:           0 :         WalletLogPrintf("Upgrading wallet to use HD chain split\n");
     497         [ #  # ]:           0 :         m_storage.SetMinVersion(FEATURE_PRE_SPLIT_KEYPOOL);
     498                 :           0 :         split_upgrade = FEATURE_HD_SPLIT > prev_version;
     499                 :             :         // Upgrade the HDChain
     500         [ #  # ]:           0 :         if (m_hd_chain.nVersion < CHDChain::VERSION_HD_CHAIN_SPLIT) {
     501                 :           0 :             m_hd_chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
     502   [ #  #  #  #  :           0 :             if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(m_hd_chain)) {
             #  #  #  # ]
     503   [ #  #  #  #  :           0 :                 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
          #  #  #  #  #  
                      # ]
     504                 :             :             }
     505                 :           0 :         }
     506                 :           0 :     }
     507                 :             :     // Mark all keys currently in the keypool as pre-split
     508         [ #  # ]:           0 :     if (split_upgrade) {
     509         [ #  # ]:           0 :         MarkPreSplitKeys();
     510                 :           0 :     }
     511                 :             :     // Regenerate the keypool if upgraded to HD
     512         [ #  # ]:           0 :     if (hd_upgrade) {
     513   [ #  #  #  # ]:           0 :         if (!NewKeyPool()) {
     514         [ #  # ]:           0 :             error = _("Unable to generate keys");
     515                 :           0 :             return false;
     516                 :             :         }
     517                 :           0 :     }
     518                 :           0 :     return true;
     519                 :           0 : }
     520                 :             : 
     521                 :           0 : bool LegacyScriptPubKeyMan::HavePrivateKeys() const
     522                 :             : {
     523                 :           0 :     LOCK(cs_KeyStore);
     524         [ #  # ]:           0 :     return !mapKeys.empty() || !mapCryptedKeys.empty();
     525                 :           0 : }
     526                 :             : 
     527                 :           0 : void LegacyScriptPubKeyMan::RewriteDB()
     528                 :             : {
     529                 :           0 :     LOCK(cs_KeyStore);
     530                 :           0 :     setInternalKeyPool.clear();
     531                 :           0 :     setExternalKeyPool.clear();
     532                 :           0 :     m_pool_key_to_index.clear();
     533                 :             :     // Note: can't top-up keypool here, because wallet is locked.
     534                 :             :     // User will be prompted to unlock wallet the next operation
     535                 :             :     // that requires a new key.
     536                 :           0 : }
     537                 :             : 
     538                 :           0 : static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
     539         [ #  # ]:           0 :     if (setKeyPool.empty()) {
     540                 :           0 :         return GetTime();
     541                 :             :     }
     542                 :             : 
     543                 :           0 :     CKeyPool keypool;
     544                 :           0 :     int64_t nIndex = *(setKeyPool.begin());
     545         [ #  # ]:           0 :     if (!batch.ReadPool(nIndex, keypool)) {
     546   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
          #  #  #  #  #  
                      # ]
     547                 :             :     }
     548         [ #  # ]:           0 :     assert(keypool.vchPubKey.IsValid());
     549                 :           0 :     return keypool.nTime;
     550                 :           0 : }
     551                 :             : 
     552                 :           0 : std::optional<int64_t> LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
     553                 :             : {
     554                 :           0 :     LOCK(cs_KeyStore);
     555                 :             : 
     556   [ #  #  #  # ]:           0 :     WalletBatch batch(m_storage.GetDatabase());
     557                 :             : 
     558                 :             :     // load oldest key from keypool, get time and return
     559         [ #  # ]:           0 :     int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
     560   [ #  #  #  #  :           0 :     if (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
             #  #  #  # ]
     561   [ #  #  #  # ]:           0 :         oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
     562         [ #  # ]:           0 :         if (!set_pre_split_keypool.empty()) {
     563   [ #  #  #  # ]:           0 :             oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
     564                 :           0 :         }
     565                 :           0 :     }
     566                 :             : 
     567                 :           0 :     return oldestKey;
     568                 :           0 : }
     569                 :             : 
     570                 :           0 : size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
     571                 :             : {
     572                 :           0 :     LOCK(cs_KeyStore);
     573                 :           0 :     return setExternalKeyPool.size() + set_pre_split_keypool.size();
     574                 :           0 : }
     575                 :             : 
     576                 :           0 : unsigned int LegacyScriptPubKeyMan::GetKeyPoolSize() const
     577                 :             : {
     578                 :           0 :     LOCK(cs_KeyStore);
     579                 :           0 :     return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
     580                 :           0 : }
     581                 :             : 
     582                 :           0 : int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
     583                 :             : {
     584                 :           0 :     LOCK(cs_KeyStore);
     585                 :           0 :     return nTimeFirstKey;
     586                 :           0 : }
     587                 :             : 
     588                 :           0 : std::unique_ptr<SigningProvider> LegacyScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
     589                 :             : {
     590                 :           0 :     return std::make_unique<LegacySigningProvider>(*this);
     591                 :             : }
     592                 :             : 
     593                 :           0 : bool LegacyScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
     594                 :             : {
     595                 :           0 :     IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
     596   [ #  #  #  # ]:           0 :     if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
     597                 :             :         // If ismine, it means we recognize keys or script ids in the script, or
     598                 :             :         // are watching the script itself, and we can at least provide metadata
     599                 :             :         // or solving information, even if not able to sign fully.
     600                 :           0 :         return true;
     601                 :             :     } else {
     602                 :             :         // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
     603                 :           0 :         ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
     604         [ #  # ]:           0 :         if (!sigdata.signatures.empty()) {
     605                 :             :             // If we could make signatures, make sure we have a private key to actually make a signature
     606                 :           0 :             bool has_privkeys = false;
     607         [ #  # ]:           0 :             for (const auto& key_sig_pair : sigdata.signatures) {
     608                 :           0 :                 has_privkeys |= HaveKey(key_sig_pair.first);
     609                 :           0 :             }
     610                 :           0 :             return has_privkeys;
     611                 :           0 :         }
     612                 :           0 :         return false;
     613                 :             :     }
     614                 :           0 : }
     615                 :             : 
     616                 :           0 : bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
     617                 :             : {
     618                 :           0 :     return ::SignTransaction(tx, this, coins, sighash, input_errors);
     619                 :             : }
     620                 :             : 
     621                 :           0 : SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
     622                 :             : {
     623                 :           0 :     CKey key;
     624   [ #  #  #  #  :           0 :     if (!GetKey(ToKeyID(pkhash), key)) {
                   #  # ]
     625                 :           0 :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
     626                 :             :     }
     627                 :             : 
     628   [ #  #  #  # ]:           0 :     if (MessageSign(key, message, str_sig)) {
     629                 :           0 :         return SigningResult::OK;
     630                 :             :     }
     631                 :           0 :     return SigningResult::SIGNING_FAILED;
     632                 :           0 : }
     633                 :             : 
     634                 :           0 : std::optional<PSBTError> LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
     635                 :             : {
     636         [ #  # ]:           0 :     if (n_signed) {
     637                 :           0 :         *n_signed = 0;
     638                 :           0 :     }
     639   [ #  #  #  #  :           0 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
                      # ]
     640                 :           0 :         const CTxIn& txin = psbtx.tx->vin[i];
     641                 :           0 :         PSBTInput& input = psbtx.inputs.at(i);
     642                 :             : 
     643         [ #  # ]:           0 :         if (PSBTInputSigned(input)) {
     644                 :           0 :             continue;
     645                 :             :         }
     646                 :             : 
     647                 :             :         // Get the Sighash type
     648   [ #  #  #  #  :           0 :         if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
                   #  # ]
     649                 :           0 :             return PSBTError::SIGHASH_MISMATCH;
     650                 :             :         }
     651                 :             : 
     652                 :             :         // Check non_witness_utxo has specified prevout
     653         [ #  # ]:           0 :         if (input.non_witness_utxo) {
     654         [ #  # ]:           0 :             if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
     655                 :           0 :                 return PSBTError::MISSING_INPUTS;
     656                 :             :             }
     657         [ #  # ]:           0 :         } else if (input.witness_utxo.IsNull()) {
     658                 :             :             // There's no UTXO so we can just skip this now
     659                 :           0 :             continue;
     660                 :             :         }
     661         [ #  # ]:           0 :         SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
     662                 :             : 
     663                 :           0 :         bool signed_one = PSBTInputSigned(input);
     664   [ #  #  #  #  :           0 :         if (n_signed && (signed_one || !sign)) {
                   #  # ]
     665                 :             :             // If sign is false, we assume that we _could_ sign if we get here. This
     666                 :             :             // will never have false negatives; it is hard to tell under what i
     667                 :             :             // circumstances it could have false positives.
     668                 :           0 :             (*n_signed)++;
     669                 :           0 :         }
     670      [ #  #  # ]:           0 :     }
     671                 :             : 
     672                 :             :     // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
     673         [ #  # ]:           0 :     for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
     674         [ #  # ]:           0 :         UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
     675                 :           0 :     }
     676                 :             : 
     677                 :           0 :     return {};
     678                 :           0 : }
     679                 :             : 
     680                 :           0 : std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
     681                 :             : {
     682                 :           0 :     LOCK(cs_KeyStore);
     683                 :             : 
     684         [ #  # ]:           0 :     CKeyID key_id = GetKeyForDestination(*this, dest);
     685   [ #  #  #  # ]:           0 :     if (!key_id.IsNull()) {
     686         [ #  # ]:           0 :         auto it = mapKeyMetadata.find(key_id);
     687         [ #  # ]:           0 :         if (it != mapKeyMetadata.end()) {
     688         [ #  # ]:           0 :             return std::make_unique<CKeyMetadata>(it->second);
     689                 :             :         }
     690         [ #  # ]:           0 :     }
     691                 :             : 
     692         [ #  # ]:           0 :     CScript scriptPubKey = GetScriptForDestination(dest);
     693   [ #  #  #  # ]:           0 :     auto it = m_script_metadata.find(CScriptID(scriptPubKey));
     694         [ #  # ]:           0 :     if (it != m_script_metadata.end()) {
     695         [ #  # ]:           0 :         return std::make_unique<CKeyMetadata>(it->second);
     696                 :             :     }
     697                 :             : 
     698                 :           0 :     return nullptr;
     699                 :           0 : }
     700                 :             : 
     701                 :           0 : uint256 LegacyScriptPubKeyMan::GetID() const
     702                 :             : {
     703                 :           0 :     return uint256::ONE;
     704                 :             : }
     705                 :             : 
     706                 :             : /**
     707                 :             :  * Update wallet first key creation time. This should be called whenever keys
     708                 :             :  * are added to the wallet, with the oldest key creation time.
     709                 :             :  */
     710                 :           0 : void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
     711                 :             : {
     712                 :           0 :     AssertLockHeld(cs_KeyStore);
     713         [ #  # ]:           0 :     if (nCreateTime <= 1) {
     714                 :             :         // Cannot determine birthday information, so set the wallet birthday to
     715                 :             :         // the beginning of time.
     716                 :           0 :         nTimeFirstKey = 1;
     717   [ #  #  #  # ]:           0 :     } else if (nTimeFirstKey == UNKNOWN_TIME || nCreateTime < nTimeFirstKey) {
     718                 :           0 :         nTimeFirstKey = nCreateTime;
     719                 :           0 :     }
     720                 :             : 
     721                 :           0 :     NotifyFirstKeyTimeChanged(this, nTimeFirstKey);
     722                 :           0 : }
     723                 :             : 
     724                 :           0 : bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
     725                 :             : {
     726                 :           0 :     return AddKeyPubKeyInner(key, pubkey);
     727                 :             : }
     728                 :             : 
     729                 :           0 : bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
     730                 :             : {
     731                 :           0 :     LOCK(cs_KeyStore);
     732   [ #  #  #  # ]:           0 :     WalletBatch batch(m_storage.GetDatabase());
     733         [ #  # ]:           0 :     return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
     734                 :           0 : }
     735                 :             : 
     736                 :           0 : bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
     737                 :             : {
     738                 :           0 :     AssertLockHeld(cs_KeyStore);
     739                 :             : 
     740                 :             :     // Make sure we aren't adding private keys to private key disabled wallets
     741         [ #  # ]:           0 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
     742                 :             : 
     743                 :             :     // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
     744                 :             :     // which is overridden below.  To avoid flushes, the database handle is
     745                 :             :     // tunneled through to it.
     746                 :           0 :     bool needsDB = !encrypted_batch;
     747         [ #  # ]:           0 :     if (needsDB) {
     748                 :           0 :         encrypted_batch = &batch;
     749                 :           0 :     }
     750         [ #  # ]:           0 :     if (!AddKeyPubKeyInner(secret, pubkey)) {
     751         [ #  # ]:           0 :         if (needsDB) encrypted_batch = nullptr;
     752                 :           0 :         return false;
     753                 :             :     }
     754         [ #  # ]:           0 :     if (needsDB) encrypted_batch = nullptr;
     755                 :             : 
     756                 :             :     // check if we need to remove from watch-only
     757                 :           0 :     CScript script;
     758   [ #  #  #  # ]:           0 :     script = GetScriptForDestination(PKHash(pubkey));
     759   [ #  #  #  # ]:           0 :     if (HaveWatchOnly(script)) {
     760         [ #  # ]:           0 :         RemoveWatchOnly(script);
     761                 :           0 :     }
     762         [ #  # ]:           0 :     script = GetScriptForRawPubKey(pubkey);
     763   [ #  #  #  # ]:           0 :     if (HaveWatchOnly(script)) {
     764         [ #  # ]:           0 :         RemoveWatchOnly(script);
     765                 :           0 :     }
     766                 :             : 
     767         [ #  # ]:           0 :     m_storage.UnsetBlankWalletFlag(batch);
     768   [ #  #  #  # ]:           0 :     if (!m_storage.HasEncryptionKeys()) {
     769         [ #  # ]:           0 :         return batch.WriteKey(pubkey,
     770         [ #  # ]:           0 :                                                  secret.GetPrivKey(),
     771   [ #  #  #  # ]:           0 :                                                  mapKeyMetadata[pubkey.GetID()]);
     772                 :             :     }
     773                 :           0 :     return true;
     774                 :           0 : }
     775                 :             : 
     776                 :           0 : bool LegacyScriptPubKeyMan::LoadCScript(const CScript& redeemScript)
     777                 :             : {
     778                 :             :     /* A sanity check was added in pull #3843 to avoid adding redeemScripts
     779                 :             :      * that never can be redeemed. However, old wallets may still contain
     780                 :             :      * these. Do not add them to the wallet and warn. */
     781         [ #  # ]:           0 :     if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
     782                 :             :     {
     783         [ #  # ]:           0 :         std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
     784   [ #  #  #  #  :           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);
                   #  # ]
     785                 :           0 :         return true;
     786                 :           0 :     }
     787                 :             : 
     788                 :           0 :     return FillableSigningProvider::AddCScript(redeemScript);
     789                 :           0 : }
     790                 :             : 
     791                 :           0 : void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
     792                 :             : {
     793                 :           0 :     LOCK(cs_KeyStore);
     794         [ #  # ]:           0 :     UpdateTimeFirstKey(meta.nCreateTime);
     795   [ #  #  #  # ]:           0 :     mapKeyMetadata[keyID] = meta;
     796                 :           0 : }
     797                 :             : 
     798                 :           0 : void LegacyScriptPubKeyMan::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
     799                 :             : {
     800                 :           0 :     LOCK(cs_KeyStore);
     801         [ #  # ]:           0 :     UpdateTimeFirstKey(meta.nCreateTime);
     802   [ #  #  #  # ]:           0 :     m_script_metadata[script_id] = meta;
     803                 :           0 : }
     804                 :             : 
     805                 :           0 : bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
     806                 :             : {
     807                 :           0 :     LOCK(cs_KeyStore);
     808   [ #  #  #  # ]:           0 :     if (!m_storage.HasEncryptionKeys()) {
     809         [ #  # ]:           0 :         return FillableSigningProvider::AddKeyPubKey(key, pubkey);
     810                 :             :     }
     811                 :             : 
     812   [ #  #  #  # ]:           0 :     if (m_storage.IsLocked()) {
     813                 :           0 :         return false;
     814                 :             :     }
     815                 :             : 
     816                 :           0 :     std::vector<unsigned char> vchCryptedSecret;
     817   [ #  #  #  #  :           0 :     CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
          #  #  #  #  #  
                      # ]
     818   [ #  #  #  #  :           0 :     if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
                   #  # ]
     819                 :           0 :             return EncryptSecret(encryption_key, vchSecret, pubkey.GetHash(), vchCryptedSecret);
     820                 :             :         })) {
     821                 :           0 :         return false;
     822                 :             :     }
     823                 :             : 
     824   [ #  #  #  # ]:           0 :     if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
     825                 :           0 :         return false;
     826                 :             :     }
     827                 :           0 :     return true;
     828                 :           0 : }
     829                 :             : 
     830                 :           0 : bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
     831                 :             : {
     832                 :             :     // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
     833         [ #  # ]:           0 :     if (!checksum_valid) {
     834                 :           0 :         fDecryptionThoroughlyChecked = false;
     835                 :           0 :     }
     836                 :             : 
     837                 :           0 :     return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
     838                 :             : }
     839                 :             : 
     840                 :           0 : bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
     841                 :             : {
     842                 :           0 :     LOCK(cs_KeyStore);
     843         [ #  # ]:           0 :     assert(mapKeys.empty());
     844                 :             : 
     845   [ #  #  #  #  :           0 :     mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
                   #  # ]
     846         [ #  # ]:           0 :     ImplicitlyLearnRelatedKeyScripts(vchPubKey);
     847                 :             :     return true;
     848                 :           0 : }
     849                 :             : 
     850                 :           0 : bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
     851                 :             :                             const std::vector<unsigned char> &vchCryptedSecret)
     852                 :             : {
     853         [ #  # ]:           0 :     if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
     854                 :           0 :         return false;
     855                 :             :     {
     856                 :           0 :         LOCK(cs_KeyStore);
     857         [ #  # ]:           0 :         if (encrypted_batch)
     858         [ #  # ]:           0 :             return encrypted_batch->WriteCryptedKey(vchPubKey,
     859                 :           0 :                                                         vchCryptedSecret,
     860   [ #  #  #  # ]:           0 :                                                         mapKeyMetadata[vchPubKey.GetID()]);
     861                 :             :         else
     862   [ #  #  #  #  :           0 :             return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
                   #  # ]
     863                 :           0 :                                                             vchCryptedSecret,
     864   [ #  #  #  # ]:           0 :                                                             mapKeyMetadata[vchPubKey.GetID()]);
     865                 :           0 :     }
     866                 :           0 : }
     867                 :             : 
     868                 :           0 : bool LegacyScriptPubKeyMan::HaveWatchOnly(const CScript &dest) const
     869                 :             : {
     870                 :           0 :     LOCK(cs_KeyStore);
     871         [ #  # ]:           0 :     return setWatchOnly.count(dest) > 0;
     872                 :           0 : }
     873                 :             : 
     874                 :           0 : bool LegacyScriptPubKeyMan::HaveWatchOnly() const
     875                 :             : {
     876                 :           0 :     LOCK(cs_KeyStore);
     877                 :           0 :     return (!setWatchOnly.empty());
     878                 :           0 : }
     879                 :             : 
     880                 :           0 : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
     881                 :             : {
     882                 :           0 :     std::vector<std::vector<unsigned char>> solutions;
     883   [ #  #  #  # ]:           0 :     return Solver(dest, solutions) == TxoutType::PUBKEY &&
     884   [ #  #  #  #  :           0 :         (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
                   #  # ]
     885                 :           0 : }
     886                 :             : 
     887                 :           0 : bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest)
     888                 :             : {
     889                 :             :     {
     890                 :           0 :         LOCK(cs_KeyStore);
     891         [ #  # ]:           0 :         setWatchOnly.erase(dest);
     892         [ #  # ]:           0 :         CPubKey pubKey;
     893   [ #  #  #  # ]:           0 :         if (ExtractPubKey(dest, pubKey)) {
     894   [ #  #  #  # ]:           0 :             mapWatchKeys.erase(pubKey.GetID());
     895                 :           0 :         }
     896                 :             :         // Related CScripts are not removed; having superfluous scripts around is
     897                 :             :         // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
     898                 :           0 :     }
     899                 :             : 
     900         [ #  # ]:           0 :     if (!HaveWatchOnly())
     901                 :           0 :         NotifyWatchonlyChanged(false);
     902   [ #  #  #  # ]:           0 :     if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
     903                 :           0 :         return false;
     904                 :             : 
     905                 :           0 :     return true;
     906                 :           0 : }
     907                 :             : 
     908                 :           0 : bool LegacyScriptPubKeyMan::LoadWatchOnly(const CScript &dest)
     909                 :             : {
     910                 :           0 :     return AddWatchOnlyInMem(dest);
     911                 :             : }
     912                 :             : 
     913                 :           0 : bool LegacyScriptPubKeyMan::AddWatchOnlyInMem(const CScript &dest)
     914                 :             : {
     915                 :           0 :     LOCK(cs_KeyStore);
     916         [ #  # ]:           0 :     setWatchOnly.insert(dest);
     917         [ #  # ]:           0 :     CPubKey pubKey;
     918   [ #  #  #  # ]:           0 :     if (ExtractPubKey(dest, pubKey)) {
     919   [ #  #  #  # ]:           0 :         mapWatchKeys[pubKey.GetID()] = pubKey;
     920         [ #  # ]:           0 :         ImplicitlyLearnRelatedKeyScripts(pubKey);
     921                 :           0 :     }
     922                 :             :     return true;
     923                 :           0 : }
     924                 :             : 
     925                 :           0 : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest)
     926                 :             : {
     927         [ #  # ]:           0 :     if (!AddWatchOnlyInMem(dest))
     928                 :           0 :         return false;
     929                 :           0 :     const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
     930                 :           0 :     UpdateTimeFirstKey(meta.nCreateTime);
     931                 :           0 :     NotifyWatchonlyChanged(true);
     932         [ #  # ]:           0 :     if (batch.WriteWatchOnly(dest, meta)) {
     933                 :           0 :         m_storage.UnsetBlankWalletFlag(batch);
     934                 :           0 :         return true;
     935                 :             :     }
     936                 :           0 :     return false;
     937                 :           0 : }
     938                 :             : 
     939                 :           0 : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
     940                 :             : {
     941                 :           0 :     m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
     942                 :           0 :     return AddWatchOnlyWithDB(batch, dest);
     943                 :             : }
     944                 :             : 
     945                 :           0 : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest)
     946                 :             : {
     947                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
     948         [ #  # ]:           0 :     return AddWatchOnlyWithDB(batch, dest);
     949                 :           0 : }
     950                 :             : 
     951                 :           0 : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
     952                 :             : {
     953                 :           0 :     m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
     954                 :           0 :     return AddWatchOnly(dest);
     955                 :             : }
     956                 :             : 
     957                 :           0 : void LegacyScriptPubKeyMan::LoadHDChain(const CHDChain& chain)
     958                 :             : {
     959                 :           0 :     LOCK(cs_KeyStore);
     960                 :           0 :     m_hd_chain = chain;
     961                 :           0 : }
     962                 :             : 
     963                 :           0 : void LegacyScriptPubKeyMan::AddHDChain(const CHDChain& chain)
     964                 :             : {
     965                 :           0 :     LOCK(cs_KeyStore);
     966                 :             :     // Store the new chain
     967   [ #  #  #  #  :           0 :     if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
             #  #  #  # ]
     968   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing chain failed");
          #  #  #  #  #  
                      # ]
     969                 :             :     }
     970                 :             :     // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
     971   [ #  #  #  # ]:           0 :     if (!m_hd_chain.seed_id.IsNull()) {
     972         [ #  # ]:           0 :         AddInactiveHDChain(m_hd_chain);
     973                 :           0 :     }
     974                 :             : 
     975                 :           0 :     m_hd_chain = chain;
     976                 :           0 : }
     977                 :             : 
     978                 :           0 : void LegacyScriptPubKeyMan::AddInactiveHDChain(const CHDChain& chain)
     979                 :             : {
     980                 :           0 :     LOCK(cs_KeyStore);
     981   [ #  #  #  # ]:           0 :     assert(!chain.seed_id.IsNull());
     982         [ #  # ]:           0 :     m_inactive_hd_chains[chain.seed_id] = chain;
     983                 :           0 : }
     984                 :             : 
     985                 :           0 : bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const
     986                 :             : {
     987                 :           0 :     LOCK(cs_KeyStore);
     988   [ #  #  #  # ]:           0 :     if (!m_storage.HasEncryptionKeys()) {
     989         [ #  # ]:           0 :         return FillableSigningProvider::HaveKey(address);
     990                 :             :     }
     991         [ #  # ]:           0 :     return mapCryptedKeys.count(address) > 0;
     992                 :           0 : }
     993                 :             : 
     994                 :           0 : bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey& keyOut) const
     995                 :             : {
     996                 :           0 :     LOCK(cs_KeyStore);
     997   [ #  #  #  # ]:           0 :     if (!m_storage.HasEncryptionKeys()) {
     998         [ #  # ]:           0 :         return FillableSigningProvider::GetKey(address, keyOut);
     999                 :             :     }
    1000                 :             : 
    1001         [ #  # ]:           0 :     CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
    1002         [ #  # ]:           0 :     if (mi != mapCryptedKeys.end())
    1003                 :             :     {
    1004                 :           0 :         const CPubKey &vchPubKey = (*mi).second.first;
    1005                 :           0 :         const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
    1006   [ #  #  #  # ]:           0 :         return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
    1007                 :           0 :             return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
    1008                 :             :         });
    1009                 :           0 :     }
    1010                 :           0 :     return false;
    1011                 :           0 : }
    1012                 :             : 
    1013                 :           0 : bool LegacyScriptPubKeyMan::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
    1014                 :             : {
    1015                 :           0 :     CKeyMetadata meta;
    1016                 :             :     {
    1017   [ #  #  #  # ]:           0 :         LOCK(cs_KeyStore);
    1018         [ #  # ]:           0 :         auto it = mapKeyMetadata.find(keyID);
    1019         [ #  # ]:           0 :         if (it == mapKeyMetadata.end()) {
    1020                 :           0 :             return false;
    1021                 :             :         }
    1022         [ #  # ]:           0 :         meta = it->second;
    1023         [ #  # ]:           0 :     }
    1024         [ #  # ]:           0 :     if (meta.has_key_origin) {
    1025         [ #  # ]:           0 :         std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
    1026         [ #  # ]:           0 :         info.path = meta.key_origin.path;
    1027                 :           0 :     } else { // Single pubkeys get the master fingerprint of themselves
    1028   [ #  #  #  #  :           0 :         std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
                   #  # ]
    1029                 :             :     }
    1030                 :           0 :     return true;
    1031                 :           0 : }
    1032                 :             : 
    1033                 :           0 : bool LegacyScriptPubKeyMan::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
    1034                 :             : {
    1035                 :           0 :     LOCK(cs_KeyStore);
    1036         [ #  # ]:           0 :     WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
    1037         [ #  # ]:           0 :     if (it != mapWatchKeys.end()) {
    1038                 :           0 :         pubkey_out = it->second;
    1039                 :           0 :         return true;
    1040                 :             :     }
    1041                 :           0 :     return false;
    1042                 :           0 : }
    1043                 :             : 
    1044                 :           0 : bool LegacyScriptPubKeyMan::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
    1045                 :             : {
    1046                 :           0 :     LOCK(cs_KeyStore);
    1047   [ #  #  #  # ]:           0 :     if (!m_storage.HasEncryptionKeys()) {
    1048   [ #  #  #  # ]:           0 :         if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
    1049         [ #  # ]:           0 :             return GetWatchPubKey(address, vchPubKeyOut);
    1050                 :             :         }
    1051                 :           0 :         return true;
    1052                 :             :     }
    1053                 :             : 
    1054         [ #  # ]:           0 :     CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
    1055         [ #  # ]:           0 :     if (mi != mapCryptedKeys.end())
    1056                 :             :     {
    1057                 :           0 :         vchPubKeyOut = (*mi).second.first;
    1058                 :           0 :         return true;
    1059                 :             :     }
    1060                 :             :     // Check for watch-only pubkeys
    1061         [ #  # ]:           0 :     return GetWatchPubKey(address, vchPubKeyOut);
    1062                 :           0 : }
    1063                 :             : 
    1064                 :           0 : CPubKey LegacyScriptPubKeyMan::GenerateNewKey(WalletBatch &batch, CHDChain& hd_chain, bool internal)
    1065                 :             : {
    1066         [ #  # ]:           0 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
    1067         [ #  # ]:           0 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
    1068                 :           0 :     AssertLockHeld(cs_KeyStore);
    1069                 :           0 :     bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
    1070                 :             : 
    1071                 :           0 :     CKey secret;
    1072                 :             : 
    1073                 :             :     // Create new metadata
    1074         [ #  # ]:           0 :     int64_t nCreationTime = GetTime();
    1075         [ #  # ]:           0 :     CKeyMetadata metadata(nCreationTime);
    1076                 :             : 
    1077                 :             :     // use HD key derivation if HD was enabled during wallet creation and a seed is present
    1078   [ #  #  #  # ]:           0 :     if (IsHDEnabled()) {
    1079   [ #  #  #  #  :           0 :         DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
                   #  # ]
    1080                 :           0 :     } else {
    1081         [ #  # ]:           0 :         secret.MakeNewKey(fCompressed);
    1082                 :             :     }
    1083                 :             : 
    1084                 :             :     // Compressed public keys were introduced in version 0.6.0
    1085         [ #  # ]:           0 :     if (fCompressed) {
    1086         [ #  # ]:           0 :         m_storage.SetMinVersion(FEATURE_COMPRPUBKEY);
    1087                 :           0 :     }
    1088                 :             : 
    1089         [ #  # ]:           0 :     CPubKey pubkey = secret.GetPubKey();
    1090   [ #  #  #  # ]:           0 :     assert(secret.VerifyPubKey(pubkey));
    1091                 :             : 
    1092   [ #  #  #  #  :           0 :     mapKeyMetadata[pubkey.GetID()] = metadata;
                   #  # ]
    1093         [ #  # ]:           0 :     UpdateTimeFirstKey(nCreationTime);
    1094                 :             : 
    1095   [ #  #  #  # ]:           0 :     if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
    1096   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": AddKey failed");
          #  #  #  #  #  
                      # ]
    1097                 :             :     }
    1098                 :             :     return pubkey;
    1099                 :           0 : }
    1100                 :             : 
    1101                 :             : //! Try to derive an extended key, throw if it fails.
    1102                 :           0 : static void DeriveExtKey(CExtKey& key_in, unsigned int index, CExtKey& key_out) {
    1103         [ #  # ]:           0 :     if (!key_in.Derive(key_out, index)) {
    1104         [ #  # ]:           0 :         throw std::runtime_error("Could not derive extended key");
    1105                 :             :     }
    1106                 :           0 : }
    1107                 :             : 
    1108                 :           0 : void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
    1109                 :             : {
    1110                 :             :     // for now we use a fixed keypath scheme of m/0'/0'/k
    1111                 :           0 :     CKey seed;                     //seed (256bit)
    1112         [ #  # ]:           0 :     CExtKey masterKey;             //hd master key
    1113         [ #  # ]:           0 :     CExtKey accountKey;            //key at m/0'
    1114         [ #  # ]:           0 :     CExtKey chainChildKey;         //key at m/0'/0' (external) or m/0'/1' (internal)
    1115         [ #  # ]:           0 :     CExtKey childKey;              //key at m/0'/0'/<n>'
    1116                 :             : 
    1117                 :             :     // try to get the seed
    1118   [ #  #  #  # ]:           0 :     if (!GetKey(hd_chain.seed_id, seed))
    1119   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": seed not found");
          #  #  #  #  #  
                      # ]
    1120                 :             : 
    1121   [ #  #  #  # ]:           0 :     masterKey.SetSeed(seed);
    1122                 :             : 
    1123                 :             :     // derive m/0'
    1124                 :             :     // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
    1125         [ #  # ]:           0 :     DeriveExtKey(masterKey, BIP32_HARDENED_KEY_LIMIT, accountKey);
    1126                 :             : 
    1127                 :             :     // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
    1128   [ #  #  #  #  :           0 :     assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
                   #  # ]
    1129         [ #  # ]:           0 :     DeriveExtKey(accountKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0), chainChildKey);
    1130                 :             : 
    1131                 :             :     // derive child key at next index, skip keys already known to the wallet
    1132                 :           0 :     do {
    1133                 :             :         // always derive hardened keys
    1134                 :             :         // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
    1135                 :             :         // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
    1136         [ #  # ]:           0 :         if (internal) {
    1137         [ #  # ]:           0 :             DeriveExtKey(chainChildKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
    1138   [ #  #  #  #  :           0 :             metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
                   #  # ]
    1139         [ #  # ]:           0 :             metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
    1140         [ #  # ]:           0 :             metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
    1141         [ #  # ]:           0 :             metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
    1142                 :           0 :             hd_chain.nInternalChainCounter++;
    1143                 :           0 :         }
    1144                 :             :         else {
    1145         [ #  # ]:           0 :             DeriveExtKey(chainChildKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
    1146   [ #  #  #  #  :           0 :             metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
                   #  # ]
    1147         [ #  # ]:           0 :             metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
    1148         [ #  # ]:           0 :             metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
    1149         [ #  # ]:           0 :             metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
    1150                 :           0 :             hd_chain.nExternalChainCounter++;
    1151                 :             :         }
    1152   [ #  #  #  #  :           0 :     } while (HaveKey(childKey.key.GetPubKey().GetID()));
             #  #  #  # ]
    1153         [ #  # ]:           0 :     secret = childKey.key;
    1154                 :           0 :     metadata.hd_seed_id = hd_chain.seed_id;
    1155   [ #  #  #  # ]:           0 :     CKeyID master_id = masterKey.key.GetPubKey().GetID();
    1156   [ #  #  #  #  :           0 :     std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
                   #  # ]
    1157                 :           0 :     metadata.has_key_origin = true;
    1158                 :             :     // update the chain model in the database
    1159   [ #  #  #  #  :           0 :     if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
             #  #  #  # ]
    1160   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
             #  #  #  # ]
    1161                 :           0 : }
    1162                 :             : 
    1163                 :           0 : void LegacyScriptPubKeyMan::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
    1164                 :             : {
    1165                 :           0 :     LOCK(cs_KeyStore);
    1166         [ #  # ]:           0 :     if (keypool.m_pre_split) {
    1167         [ #  # ]:           0 :         set_pre_split_keypool.insert(nIndex);
    1168         [ #  # ]:           0 :     } else if (keypool.fInternal) {
    1169         [ #  # ]:           0 :         setInternalKeyPool.insert(nIndex);
    1170                 :           0 :     } else {
    1171         [ #  # ]:           0 :         setExternalKeyPool.insert(nIndex);
    1172                 :             :     }
    1173         [ #  # ]:           0 :     m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
    1174   [ #  #  #  # ]:           0 :     m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
    1175                 :             : 
    1176                 :             :     // If no metadata exists yet, create a default with the pool key's
    1177                 :             :     // creation time. Note that this may be overwritten by actually
    1178                 :             :     // stored metadata for that key later, which is fine.
    1179         [ #  # ]:           0 :     CKeyID keyid = keypool.vchPubKey.GetID();
    1180   [ #  #  #  # ]:           0 :     if (mapKeyMetadata.count(keyid) == 0)
    1181   [ #  #  #  # ]:           0 :         mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
    1182                 :           0 : }
    1183                 :             : 
    1184                 :           0 : bool LegacyScriptPubKeyMan::CanGenerateKeys() const
    1185                 :             : {
    1186                 :             :     // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
    1187                 :           0 :     LOCK(cs_KeyStore);
    1188   [ #  #  #  #  :           0 :     return IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD);
                   #  # ]
    1189                 :           0 : }
    1190                 :             : 
    1191                 :           0 : CPubKey LegacyScriptPubKeyMan::GenerateNewSeed()
    1192                 :             : {
    1193         [ #  # ]:           0 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
    1194                 :           0 :     CKey key = GenerateRandomKey();
    1195         [ #  # ]:           0 :     return DeriveNewSeed(key);
    1196                 :           0 : }
    1197                 :             : 
    1198                 :           0 : CPubKey LegacyScriptPubKeyMan::DeriveNewSeed(const CKey& key)
    1199                 :             : {
    1200                 :           0 :     int64_t nCreationTime = GetTime();
    1201                 :           0 :     CKeyMetadata metadata(nCreationTime);
    1202                 :             : 
    1203                 :             :     // calculate the seed
    1204         [ #  # ]:           0 :     CPubKey seed = key.GetPubKey();
    1205   [ #  #  #  # ]:           0 :     assert(key.VerifyPubKey(seed));
    1206                 :             : 
    1207                 :             :     // set the hd keypath to "s" -> Seed, refers the seed to itself
    1208         [ #  # ]:           0 :     metadata.hdKeypath     = "s";
    1209                 :           0 :     metadata.has_key_origin = false;
    1210         [ #  # ]:           0 :     metadata.hd_seed_id = seed.GetID();
    1211                 :             : 
    1212                 :             :     {
    1213   [ #  #  #  # ]:           0 :         LOCK(cs_KeyStore);
    1214                 :             : 
    1215                 :             :         // mem store the metadata
    1216   [ #  #  #  #  :           0 :         mapKeyMetadata[seed.GetID()] = metadata;
                   #  # ]
    1217                 :             : 
    1218                 :             :         // write the key&metadata to the database
    1219   [ #  #  #  # ]:           0 :         if (!AddKeyPubKey(key, seed))
    1220   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
          #  #  #  #  #  
                      # ]
    1221                 :           0 :     }
    1222                 :             : 
    1223                 :             :     return seed;
    1224                 :           0 : }
    1225                 :             : 
    1226                 :           0 : void LegacyScriptPubKeyMan::SetHDSeed(const CPubKey& seed)
    1227                 :             : {
    1228                 :           0 :     LOCK(cs_KeyStore);
    1229                 :             :     // store the keyid (hash160) together with
    1230                 :             :     // the child index counter in the database
    1231                 :             :     // as a hdchain object
    1232         [ #  # ]:           0 :     CHDChain newHdChain;
    1233         [ #  # ]:           0 :     newHdChain.nVersion = m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
    1234         [ #  # ]:           0 :     newHdChain.seed_id = seed.GetID();
    1235         [ #  # ]:           0 :     AddHDChain(newHdChain);
    1236         [ #  # ]:           0 :     NotifyCanGetAddressesChanged();
    1237   [ #  #  #  # ]:           0 :     WalletBatch batch(m_storage.GetDatabase());
    1238         [ #  # ]:           0 :     m_storage.UnsetBlankWalletFlag(batch);
    1239                 :           0 : }
    1240                 :             : 
    1241                 :             : /**
    1242                 :             :  * Mark old keypool keys as used,
    1243                 :             :  * and generate all new keys
    1244                 :             :  */
    1245                 :           0 : bool LegacyScriptPubKeyMan::NewKeyPool()
    1246                 :             : {
    1247         [ #  # ]:           0 :     if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
    1248                 :           0 :         return false;
    1249                 :             :     }
    1250                 :             :     {
    1251                 :           0 :         LOCK(cs_KeyStore);
    1252   [ #  #  #  # ]:           0 :         WalletBatch batch(m_storage.GetDatabase());
    1253                 :             : 
    1254         [ #  # ]:           0 :         for (const int64_t nIndex : setInternalKeyPool) {
    1255         [ #  # ]:           0 :             batch.ErasePool(nIndex);
    1256                 :           0 :         }
    1257                 :           0 :         setInternalKeyPool.clear();
    1258                 :             : 
    1259         [ #  # ]:           0 :         for (const int64_t nIndex : setExternalKeyPool) {
    1260         [ #  # ]:           0 :             batch.ErasePool(nIndex);
    1261                 :           0 :         }
    1262                 :           0 :         setExternalKeyPool.clear();
    1263                 :             : 
    1264         [ #  # ]:           0 :         for (const int64_t nIndex : set_pre_split_keypool) {
    1265         [ #  # ]:           0 :             batch.ErasePool(nIndex);
    1266                 :           0 :         }
    1267                 :           0 :         set_pre_split_keypool.clear();
    1268                 :             : 
    1269                 :           0 :         m_pool_key_to_index.clear();
    1270                 :             : 
    1271   [ #  #  #  # ]:           0 :         if (!TopUp()) {
    1272                 :           0 :             return false;
    1273                 :             :         }
    1274         [ #  # ]:           0 :         WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
    1275      [ #  #  # ]:           0 :     }
    1276                 :           0 :     return true;
    1277                 :           0 : }
    1278                 :             : 
    1279                 :           0 : bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
    1280                 :             : {
    1281         [ #  # ]:           0 :     if (!CanGenerateKeys()) {
    1282                 :           0 :         return false;
    1283                 :             :     }
    1284                 :             : 
    1285                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1286   [ #  #  #  # ]:           0 :     if (!batch.TxnBegin()) return false;
    1287   [ #  #  #  # ]:           0 :     if (!TopUpChain(batch, m_hd_chain, kpSize)) {
    1288                 :           0 :         return false;
    1289                 :             :     }
    1290   [ #  #  #  # ]:           0 :     for (auto& [chain_id, chain] : m_inactive_hd_chains) {
    1291   [ #  #  #  # ]:           0 :         if (!TopUpChain(batch, chain, kpSize)) {
    1292                 :           0 :             return false;
    1293                 :             :         }
    1294         [ #  # ]:           0 :     }
    1295   [ #  #  #  #  :           0 :     if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1296         [ #  # ]:           0 :     NotifyCanGetAddressesChanged();
    1297                 :             :     // Note: Unlike with DescriptorSPKM, LegacySPKM does not need to call
    1298                 :             :     // m_storage.TopUpCallback() as we do not know what new scripts the LegacySPKM is
    1299                 :             :     // watching for. CWallet's scriptPubKey cache is not used for LegacySPKMs.
    1300                 :           0 :     return true;
    1301                 :           0 : }
    1302                 :             : 
    1303                 :           0 : bool LegacyScriptPubKeyMan::TopUpChain(WalletBatch& batch, CHDChain& chain, unsigned int kpSize)
    1304                 :             : {
    1305                 :           0 :     LOCK(cs_KeyStore);
    1306                 :             : 
    1307   [ #  #  #  # ]:           0 :     if (m_storage.IsLocked()) return false;
    1308                 :             : 
    1309                 :             :     // Top up key pool
    1310                 :           0 :     unsigned int nTargetSize;
    1311         [ #  # ]:           0 :     if (kpSize > 0) {
    1312                 :           0 :         nTargetSize = kpSize;
    1313                 :           0 :     } else {
    1314                 :           0 :         nTargetSize = m_keypool_size;
    1315                 :             :     }
    1316         [ #  # ]:           0 :     int64_t target = std::max((int64_t) nTargetSize, int64_t{1});
    1317                 :             : 
    1318                 :             :     // count amount of available keys (internal, external)
    1319                 :             :     // make sure the keypool of external and internal keys fits the user selected target (-keypool)
    1320                 :           0 :     int64_t missingExternal;
    1321                 :           0 :     int64_t missingInternal;
    1322   [ #  #  #  # ]:           0 :     if (chain == m_hd_chain) {
    1323         [ #  # ]:           0 :         missingExternal = std::max(target - (int64_t)setExternalKeyPool.size(), int64_t{0});
    1324         [ #  # ]:           0 :         missingInternal = std::max(target - (int64_t)setInternalKeyPool.size(), int64_t{0});
    1325                 :           0 :     } else {
    1326         [ #  # ]:           0 :         missingExternal = std::max(target - (chain.nExternalChainCounter - chain.m_next_external_index), int64_t{0});
    1327         [ #  # ]:           0 :         missingInternal = std::max(target - (chain.nInternalChainCounter - chain.m_next_internal_index), int64_t{0});
    1328                 :             :     }
    1329                 :             : 
    1330   [ #  #  #  #  :           0 :     if (!IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
             #  #  #  # ]
    1331                 :             :         // don't create extra internal keys
    1332                 :           0 :         missingInternal = 0;
    1333                 :           0 :     }
    1334                 :           0 :     bool internal = false;
    1335         [ #  # ]:           0 :     for (int64_t i = missingInternal + missingExternal; i--;) {
    1336         [ #  # ]:           0 :         if (i < missingInternal) {
    1337                 :           0 :             internal = true;
    1338                 :           0 :         }
    1339                 :             : 
    1340         [ #  # ]:           0 :         CPubKey pubkey(GenerateNewKey(batch, chain, internal));
    1341   [ #  #  #  # ]:           0 :         if (chain == m_hd_chain) {
    1342         [ #  # ]:           0 :             AddKeypoolPubkeyWithDB(pubkey, internal, batch);
    1343                 :           0 :         }
    1344                 :           0 :     }
    1345         [ #  # ]:           0 :     if (missingInternal + missingExternal > 0) {
    1346   [ #  #  #  # ]:           0 :         if (chain == m_hd_chain) {
    1347         [ #  # ]:           0 :             WalletLogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size(), setInternalKeyPool.size());
    1348                 :           0 :         } else {
    1349   [ #  #  #  #  :           0 :             WalletLogPrintf("inactive seed with id %s added %d external keys, %d internal keys\n", HexStr(chain.seed_id), missingExternal, missingInternal);
                   #  # ]
    1350                 :             :         }
    1351                 :           0 :     }
    1352                 :           0 :     return true;
    1353                 :           0 : }
    1354                 :             : 
    1355                 :           0 : void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
    1356                 :             : {
    1357                 :           0 :     LOCK(cs_KeyStore);
    1358         [ #  # ]:           0 :     assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
    1359                 :           0 :     int64_t index = ++m_max_keypool_index;
    1360   [ #  #  #  #  :           0 :     if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
                   #  # ]
    1361   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
          #  #  #  #  #  
                      # ]
    1362                 :             :     }
    1363         [ #  # ]:           0 :     if (internal) {
    1364         [ #  # ]:           0 :         setInternalKeyPool.insert(index);
    1365                 :           0 :     } else {
    1366         [ #  # ]:           0 :         setExternalKeyPool.insert(index);
    1367                 :             :     }
    1368   [ #  #  #  # ]:           0 :     m_pool_key_to_index[pubkey.GetID()] = index;
    1369                 :           0 : }
    1370                 :             : 
    1371                 :           0 : void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
    1372                 :             : {
    1373         [ #  # ]:           0 :     assert(type != OutputType::BECH32M);
    1374                 :             :     // Remove from key pool
    1375                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1376         [ #  # ]:           0 :     batch.ErasePool(nIndex);
    1377         [ #  # ]:           0 :     CPubKey pubkey;
    1378   [ #  #  #  # ]:           0 :     bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
    1379         [ #  # ]:           0 :     assert(have_pk);
    1380         [ #  # ]:           0 :     LearnRelatedScripts(pubkey, type);
    1381         [ #  # ]:           0 :     m_index_to_reserved_key.erase(nIndex);
    1382         [ #  # ]:           0 :     WalletLogPrintf("keypool keep %d\n", nIndex);
    1383                 :           0 : }
    1384                 :             : 
    1385                 :           0 : void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
    1386                 :             : {
    1387                 :             :     // Return to key pool
    1388                 :             :     {
    1389                 :           0 :         LOCK(cs_KeyStore);
    1390         [ #  # ]:           0 :         if (fInternal) {
    1391         [ #  # ]:           0 :             setInternalKeyPool.insert(nIndex);
    1392         [ #  # ]:           0 :         } else if (!set_pre_split_keypool.empty()) {
    1393         [ #  # ]:           0 :             set_pre_split_keypool.insert(nIndex);
    1394                 :           0 :         } else {
    1395         [ #  # ]:           0 :             setExternalKeyPool.insert(nIndex);
    1396                 :             :         }
    1397         [ #  # ]:           0 :         CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
    1398         [ #  # ]:           0 :         m_pool_key_to_index[pubkey_id] = nIndex;
    1399         [ #  # ]:           0 :         m_index_to_reserved_key.erase(nIndex);
    1400         [ #  # ]:           0 :         NotifyCanGetAddressesChanged();
    1401                 :           0 :     }
    1402                 :           0 :     WalletLogPrintf("keypool return %d\n", nIndex);
    1403                 :           0 : }
    1404                 :             : 
    1405                 :           0 : bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type)
    1406                 :             : {
    1407         [ #  # ]:           0 :     assert(type != OutputType::BECH32M);
    1408         [ #  # ]:           0 :     if (!CanGetAddresses(/*internal=*/ false)) {
    1409                 :           0 :         return false;
    1410                 :             :     }
    1411                 :             : 
    1412                 :           0 :     CKeyPool keypool;
    1413                 :             :     {
    1414                 :           0 :         LOCK(cs_KeyStore);
    1415                 :           0 :         int64_t nIndex;
    1416   [ #  #  #  #  :           0 :         if (!ReserveKeyFromKeyPool(nIndex, keypool, /*fRequestedInternal=*/ false) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
             #  #  #  # ]
    1417   [ #  #  #  # ]:           0 :             if (m_storage.IsLocked()) return false;
    1418   [ #  #  #  # ]:           0 :             WalletBatch batch(m_storage.GetDatabase());
    1419         [ #  # ]:           0 :             result = GenerateNewKey(batch, m_hd_chain, /*internal=*/ false);
    1420                 :           0 :             return true;
    1421                 :           0 :         }
    1422         [ #  # ]:           0 :         KeepDestination(nIndex, type);
    1423                 :           0 :         result = keypool.vchPubKey;
    1424         [ #  # ]:           0 :     }
    1425                 :           0 :     return true;
    1426                 :           0 : }
    1427                 :             : 
    1428                 :           0 : bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
    1429                 :             : {
    1430                 :           0 :     nIndex = -1;
    1431                 :           0 :     keypool.vchPubKey = CPubKey();
    1432                 :             :     {
    1433                 :           0 :         LOCK(cs_KeyStore);
    1434                 :             : 
    1435                 :           0 :         bool fReturningInternal = fRequestedInternal;
    1436   [ #  #  #  #  :           0 :         fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
          #  #  #  #  #  
                      # ]
    1437                 :           0 :         bool use_split_keypool = set_pre_split_keypool.empty();
    1438   [ #  #  #  # ]:           0 :         std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
    1439                 :             : 
    1440                 :             :         // Get the oldest key
    1441         [ #  # ]:           0 :         if (setKeyPool.empty()) {
    1442                 :           0 :             return false;
    1443                 :             :         }
    1444                 :             : 
    1445   [ #  #  #  # ]:           0 :         WalletBatch batch(m_storage.GetDatabase());
    1446                 :             : 
    1447                 :           0 :         auto it = setKeyPool.begin();
    1448                 :           0 :         nIndex = *it;
    1449         [ #  # ]:           0 :         setKeyPool.erase(it);
    1450   [ #  #  #  # ]:           0 :         if (!batch.ReadPool(nIndex, keypool)) {
    1451   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": read failed");
             #  #  #  # ]
    1452                 :             :         }
    1453         [ #  # ]:           0 :         CPubKey pk;
    1454   [ #  #  #  #  :           0 :         if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
                   #  # ]
    1455   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
             #  #  #  # ]
    1456                 :             :         }
    1457                 :             :         // If the key was pre-split keypool, we don't care about what type it is
    1458   [ #  #  #  # ]:           0 :         if (use_split_keypool && keypool.fInternal != fReturningInternal) {
    1459   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
             #  #  #  # ]
    1460                 :             :         }
    1461   [ #  #  #  # ]:           0 :         if (!keypool.vchPubKey.IsValid()) {
    1462   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
             #  #  #  # ]
    1463                 :             :         }
    1464                 :             : 
    1465   [ #  #  #  # ]:           0 :         assert(m_index_to_reserved_key.count(nIndex) == 0);
    1466   [ #  #  #  # ]:           0 :         m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
    1467   [ #  #  #  # ]:           0 :         m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
    1468         [ #  # ]:           0 :         WalletLogPrintf("keypool reserve %d\n", nIndex);
    1469         [ #  # ]:           0 :     }
    1470                 :           0 :     NotifyCanGetAddressesChanged();
    1471                 :           0 :     return true;
    1472                 :           0 : }
    1473                 :             : 
    1474                 :           0 : void LegacyScriptPubKeyMan::LearnRelatedScripts(const CPubKey& key, OutputType type)
    1475                 :             : {
    1476         [ #  # ]:           0 :     assert(type != OutputType::BECH32M);
    1477   [ #  #  #  #  :           0 :     if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
                   #  # ]
    1478                 :           0 :         CTxDestination witdest = WitnessV0KeyHash(key.GetID());
    1479         [ #  # ]:           0 :         CScript witprog = GetScriptForDestination(witdest);
    1480                 :             :         // Make sure the resulting program is solvable.
    1481         [ #  # ]:           0 :         const auto desc = InferDescriptor(witprog, *this);
    1482   [ #  #  #  #  :           0 :         assert(desc && desc->IsSolvable());
                   #  # ]
    1483         [ #  # ]:           0 :         AddCScript(witprog);
    1484                 :           0 :     }
    1485                 :           0 : }
    1486                 :             : 
    1487                 :           0 : void LegacyScriptPubKeyMan::LearnAllRelatedScripts(const CPubKey& key)
    1488                 :             : {
    1489                 :             :     // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
    1490                 :           0 :     LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
    1491                 :           0 : }
    1492                 :             : 
    1493                 :           0 : std::vector<CKeyPool> LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
    1494                 :             : {
    1495                 :           0 :     AssertLockHeld(cs_KeyStore);
    1496                 :           0 :     bool internal = setInternalKeyPool.count(keypool_id);
    1497   [ #  #  #  #  :           0 :     if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
                   #  # ]
    1498   [ #  #  #  # ]:           0 :     std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
    1499                 :           0 :     auto it = setKeyPool->begin();
    1500                 :             : 
    1501                 :           0 :     std::vector<CKeyPool> result;
    1502   [ #  #  #  # ]:           0 :     WalletBatch batch(m_storage.GetDatabase());
    1503   [ #  #  #  # ]:           0 :     while (it != std::end(*setKeyPool)) {
    1504                 :           0 :         const int64_t& index = *(it);
    1505         [ #  # ]:           0 :         if (index > keypool_id) break; // set*KeyPool is ordered
    1506                 :             : 
    1507         [ #  # ]:           0 :         CKeyPool keypool;
    1508   [ #  #  #  # ]:           0 :         if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
    1509   [ #  #  #  # ]:           0 :             m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
    1510                 :           0 :         }
    1511         [ #  # ]:           0 :         LearnAllRelatedScripts(keypool.vchPubKey);
    1512         [ #  # ]:           0 :         batch.ErasePool(index);
    1513         [ #  # ]:           0 :         WalletLogPrintf("keypool index %d removed\n", index);
    1514         [ #  # ]:           0 :         it = setKeyPool->erase(it);
    1515         [ #  # ]:           0 :         result.push_back(std::move(keypool));
    1516      [ #  #  # ]:           0 :     }
    1517                 :             : 
    1518                 :           0 :     return result;
    1519         [ #  # ]:           0 : }
    1520                 :             : 
    1521                 :           0 : std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
    1522                 :             : {
    1523                 :           0 :     std::vector<CScript> dummy;
    1524                 :           0 :     FlatSigningProvider out;
    1525   [ #  #  #  # ]:           0 :     InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
    1526                 :           0 :     std::vector<CKeyID> ret;
    1527         [ #  # ]:           0 :     ret.reserve(out.pubkeys.size());
    1528         [ #  # ]:           0 :     for (const auto& entry : out.pubkeys) {
    1529         [ #  # ]:           0 :         ret.push_back(entry.first);
    1530                 :           0 :     }
    1531                 :           0 :     return ret;
    1532         [ #  # ]:           0 : }
    1533                 :             : 
    1534                 :           0 : void LegacyScriptPubKeyMan::MarkPreSplitKeys()
    1535                 :             : {
    1536                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1537         [ #  # ]:           0 :     for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
    1538                 :           0 :         int64_t index = *it;
    1539         [ #  # ]:           0 :         CKeyPool keypool;
    1540   [ #  #  #  # ]:           0 :         if (!batch.ReadPool(index, keypool)) {
    1541   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
          #  #  #  #  #  
                      # ]
    1542                 :             :         }
    1543                 :           0 :         keypool.m_pre_split = true;
    1544   [ #  #  #  # ]:           0 :         if (!batch.WritePool(index, keypool)) {
    1545   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
             #  #  #  # ]
    1546                 :             :         }
    1547         [ #  # ]:           0 :         set_pre_split_keypool.insert(index);
    1548         [ #  # ]:           0 :         it = setExternalKeyPool.erase(it);
    1549                 :           0 :     }
    1550                 :           0 : }
    1551                 :             : 
    1552                 :           0 : bool LegacyScriptPubKeyMan::AddCScript(const CScript& redeemScript)
    1553                 :             : {
    1554                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1555         [ #  # ]:           0 :     return AddCScriptWithDB(batch, redeemScript);
    1556                 :           0 : }
    1557                 :             : 
    1558                 :           0 : bool LegacyScriptPubKeyMan::AddCScriptWithDB(WalletBatch& batch, const CScript& redeemScript)
    1559                 :             : {
    1560         [ #  # ]:           0 :     if (!FillableSigningProvider::AddCScript(redeemScript))
    1561                 :           0 :         return false;
    1562         [ #  # ]:           0 :     if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
    1563                 :           0 :         m_storage.UnsetBlankWalletFlag(batch);
    1564                 :           0 :         return true;
    1565                 :             :     }
    1566                 :           0 :     return false;
    1567                 :           0 : }
    1568                 :             : 
    1569                 :           0 : bool LegacyScriptPubKeyMan::AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info)
    1570                 :             : {
    1571                 :           0 :     LOCK(cs_KeyStore);
    1572   [ #  #  #  #  :           0 :     std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
                   #  # ]
    1573   [ #  #  #  #  :           0 :     mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
                   #  # ]
    1574   [ #  #  #  # ]:           0 :     mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
    1575   [ #  #  #  #  :           0 :     mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path, /*apostrophe=*/true);
                   #  # ]
    1576   [ #  #  #  #  :           0 :     return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
                   #  # ]
    1577                 :           0 : }
    1578                 :             : 
    1579                 :           0 : bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
    1580                 :             : {
    1581                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1582   [ #  #  #  # ]:           0 :     for (const auto& entry : scripts) {
    1583         [ #  # ]:           0 :         CScriptID id(entry);
    1584   [ #  #  #  # ]:           0 :         if (HaveCScript(id)) {
    1585   [ #  #  #  #  :           0 :             WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
                   #  # ]
    1586                 :           0 :             continue;
    1587                 :             :         }
    1588   [ #  #  #  # ]:           0 :         if (!AddCScriptWithDB(batch, entry)) {
    1589                 :           0 :             return false;
    1590                 :             :         }
    1591                 :             : 
    1592         [ #  # ]:           0 :         if (timestamp > 0) {
    1593   [ #  #  #  # ]:           0 :             m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
    1594                 :           0 :         }
    1595   [ #  #  #  #  :           0 :     }
                      # ]
    1596         [ #  # ]:           0 :     if (timestamp > 0) {
    1597         [ #  # ]:           0 :         UpdateTimeFirstKey(timestamp);
    1598                 :           0 :     }
    1599                 :             : 
    1600                 :           0 :     return true;
    1601                 :           0 : }
    1602                 :             : 
    1603                 :           0 : bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
    1604                 :             : {
    1605                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1606   [ #  #  #  # ]:           0 :     for (const auto& entry : privkey_map) {
    1607                 :           0 :         const CKey& key = entry.second;
    1608         [ #  # ]:           0 :         CPubKey pubkey = key.GetPubKey();
    1609                 :           0 :         const CKeyID& id = entry.first;
    1610   [ #  #  #  # ]:           0 :         assert(key.VerifyPubKey(pubkey));
    1611                 :             :         // Skip if we already have the key
    1612   [ #  #  #  # ]:           0 :         if (HaveKey(id)) {
    1613   [ #  #  #  #  :           0 :             WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
                   #  # ]
    1614                 :           0 :             continue;
    1615                 :             :         }
    1616         [ #  # ]:           0 :         mapKeyMetadata[id].nCreateTime = timestamp;
    1617                 :             :         // If the private key is not present in the wallet, insert it.
    1618   [ #  #  #  # ]:           0 :         if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
    1619                 :           0 :             return false;
    1620                 :             :         }
    1621         [ #  # ]:           0 :         UpdateTimeFirstKey(timestamp);
    1622   [ #  #  #  #  :           0 :     }
                      # ]
    1623                 :           0 :     return true;
    1624                 :           0 : }
    1625                 :             : 
    1626                 :           0 : bool LegacyScriptPubKeyMan::ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp)
    1627                 :             : {
    1628                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1629         [ #  # ]:           0 :     for (const auto& entry : key_origins) {
    1630         [ #  # ]:           0 :         AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
    1631                 :           0 :     }
    1632   [ #  #  #  # ]:           0 :     for (const CKeyID& id : ordered_pubkeys) {
    1633         [ #  # ]:           0 :         auto entry = pubkey_map.find(id);
    1634         [ #  # ]:           0 :         if (entry == pubkey_map.end()) {
    1635                 :           0 :             continue;
    1636                 :             :         }
    1637                 :           0 :         const CPubKey& pubkey = entry->second;
    1638         [ #  # ]:           0 :         CPubKey temp;
    1639   [ #  #  #  # ]:           0 :         if (GetPubKey(id, temp)) {
    1640                 :             :             // Already have pubkey, skipping
    1641   [ #  #  #  #  :           0 :             WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
                   #  # ]
    1642                 :           0 :             continue;
    1643                 :             :         }
    1644   [ #  #  #  #  :           0 :         if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
                   #  # ]
    1645                 :           0 :             return false;
    1646                 :             :         }
    1647         [ #  # ]:           0 :         mapKeyMetadata[id].nCreateTime = timestamp;
    1648                 :             : 
    1649                 :             :         // Add to keypool only works with pubkeys
    1650         [ #  # ]:           0 :         if (add_keypool) {
    1651         [ #  # ]:           0 :             AddKeypoolPubkeyWithDB(pubkey, internal, batch);
    1652         [ #  # ]:           0 :             NotifyCanGetAddressesChanged();
    1653                 :           0 :         }
    1654   [ #  #  #  #  :           0 :     }
                      # ]
    1655                 :           0 :     return true;
    1656                 :           0 : }
    1657                 :             : 
    1658                 :           0 : bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
    1659                 :             : {
    1660                 :           0 :     WalletBatch batch(m_storage.GetDatabase());
    1661   [ #  #  #  # ]:           0 :     for (const CScript& script : script_pub_keys) {
    1662   [ #  #  #  #  :           0 :         if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
                   #  # ]
    1663   [ #  #  #  # ]:           0 :             if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
    1664                 :           0 :                 return false;
    1665                 :             :             }
    1666                 :           0 :         }
    1667         [ #  # ]:           0 :     }
    1668                 :           0 :     return true;
    1669                 :           0 : }
    1670                 :             : 
    1671                 :           0 : std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
    1672                 :             : {
    1673                 :           0 :     LOCK(cs_KeyStore);
    1674   [ #  #  #  # ]:           0 :     if (!m_storage.HasEncryptionKeys()) {
    1675         [ #  # ]:           0 :         return FillableSigningProvider::GetKeys();
    1676                 :             :     }
    1677                 :           0 :     std::set<CKeyID> set_address;
    1678         [ #  # ]:           0 :     for (const auto& mi : mapCryptedKeys) {
    1679         [ #  # ]:           0 :         set_address.insert(mi.first);
    1680                 :           0 :     }
    1681                 :           0 :     return set_address;
    1682         [ #  # ]:           0 : }
    1683                 :             : 
    1684                 :           0 : std::unordered_set<CScript, SaltedSipHasher> LegacyScriptPubKeyMan::GetScriptPubKeys() const
    1685                 :             : {
    1686                 :           0 :     LOCK(cs_KeyStore);
    1687         [ #  # ]:           0 :     std::unordered_set<CScript, SaltedSipHasher> spks;
    1688                 :             : 
    1689                 :             :     // All keys have at least P2PK and P2PKH
    1690         [ #  # ]:           0 :     for (const auto& key_pair : mapKeys) {
    1691         [ #  # ]:           0 :         const CPubKey& pub = key_pair.second.GetPubKey();
    1692   [ #  #  #  # ]:           0 :         spks.insert(GetScriptForRawPubKey(pub));
    1693   [ #  #  #  #  :           0 :         spks.insert(GetScriptForDestination(PKHash(pub)));
                   #  # ]
    1694                 :           0 :     }
    1695         [ #  # ]:           0 :     for (const auto& key_pair : mapCryptedKeys) {
    1696                 :           0 :         const CPubKey& pub = key_pair.second.first;
    1697   [ #  #  #  # ]:           0 :         spks.insert(GetScriptForRawPubKey(pub));
    1698   [ #  #  #  #  :           0 :         spks.insert(GetScriptForDestination(PKHash(pub)));
                   #  # ]
    1699                 :           0 :     }
    1700                 :             : 
    1701                 :             :     // For every script in mapScript, only the ISMINE_SPENDABLE ones are being tracked.
    1702                 :             :     // The watchonly ones will be in setWatchOnly which we deal with later
    1703                 :             :     // For all keys, if they have segwit scripts, those scripts will end up in mapScripts
    1704         [ #  # ]:           0 :     for (const auto& script_pair : mapScripts) {
    1705                 :           0 :         const CScript& script = script_pair.second;
    1706   [ #  #  #  # ]:           0 :         if (IsMine(script) == ISMINE_SPENDABLE) {
    1707                 :             :             // Add ScriptHash for scripts that are not already P2SH
    1708   [ #  #  #  # ]:           0 :             if (!script.IsPayToScriptHash()) {
    1709   [ #  #  #  #  :           0 :                 spks.insert(GetScriptForDestination(ScriptHash(script)));
                   #  # ]
    1710                 :           0 :             }
    1711                 :             :             // For segwit scripts, we only consider them spendable if we have the segwit spk
    1712                 :           0 :             int wit_ver = -1;
    1713                 :           0 :             std::vector<unsigned char> witprog;
    1714   [ #  #  #  #  :           0 :             if (script.IsWitnessProgram(wit_ver, witprog) && wit_ver == 0) {
                   #  # ]
    1715         [ #  # ]:           0 :                 spks.insert(script);
    1716                 :           0 :             }
    1717                 :           0 :         } else {
    1718                 :             :             // Multisigs are special. They don't show up as ISMINE_SPENDABLE unless they are in a P2SH
    1719                 :             :             // So check the P2SH of a multisig to see if we should insert it
    1720                 :           0 :             std::vector<std::vector<unsigned char>> sols;
    1721         [ #  # ]:           0 :             TxoutType type = Solver(script, sols);
    1722         [ #  # ]:           0 :             if (type == TxoutType::MULTISIG) {
    1723   [ #  #  #  # ]:           0 :                 CScript ms_spk = GetScriptForDestination(ScriptHash(script));
    1724   [ #  #  #  # ]:           0 :                 if (IsMine(ms_spk) != ISMINE_NO) {
    1725         [ #  # ]:           0 :                     spks.insert(ms_spk);
    1726                 :           0 :                 }
    1727                 :           0 :             }
    1728                 :           0 :         }
    1729                 :           0 :     }
    1730                 :             : 
    1731                 :             :     // All watchonly scripts are raw
    1732         [ #  # ]:           0 :     for (const CScript& script : setWatchOnly) {
    1733                 :             :         // As the legacy wallet allowed to import any script, we need to verify the validity here.
    1734                 :             :         // LegacyScriptPubKeyMan::IsMine() return 'ISMINE_NO' for invalid or not watched scripts (IsMineResult::INVALID or IsMineResult::NO).
    1735                 :             :         // e.g. a "sh(sh(pkh()))" which legacy wallets allowed to import!.
    1736   [ #  #  #  #  :           0 :         if (IsMine(script) != ISMINE_NO) spks.insert(script);
                   #  # ]
    1737                 :           0 :     }
    1738                 :             : 
    1739                 :           0 :     return spks;
    1740         [ #  # ]:           0 : }
    1741                 :             : 
    1742                 :           0 : std::unordered_set<CScript, SaltedSipHasher> LegacyScriptPubKeyMan::GetNotMineScriptPubKeys() const
    1743                 :             : {
    1744                 :           0 :     LOCK(cs_KeyStore);
    1745         [ #  # ]:           0 :     std::unordered_set<CScript, SaltedSipHasher> spks;
    1746         [ #  # ]:           0 :     for (const CScript& script : setWatchOnly) {
    1747   [ #  #  #  #  :           0 :         if (IsMine(script) == ISMINE_NO) spks.insert(script);
                   #  # ]
    1748                 :           0 :     }
    1749                 :           0 :     return spks;
    1750         [ #  # ]:           0 : }
    1751                 :             : 
    1752                 :           0 : std::optional<MigrationData> LegacyScriptPubKeyMan::MigrateToDescriptor()
    1753                 :             : {
    1754                 :           0 :     LOCK(cs_KeyStore);
    1755   [ #  #  #  # ]:           0 :     if (m_storage.IsLocked()) {
    1756                 :           0 :         return std::nullopt;
    1757                 :             :     }
    1758                 :             : 
    1759         [ #  # ]:           0 :     MigrationData out;
    1760                 :             : 
    1761         [ #  # ]:           0 :     std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
    1762                 :             : 
    1763                 :             :     // Get all key ids
    1764                 :           0 :     std::set<CKeyID> keyids;
    1765         [ #  # ]:           0 :     for (const auto& key_pair : mapKeys) {
    1766         [ #  # ]:           0 :         keyids.insert(key_pair.first);
    1767                 :           0 :     }
    1768         [ #  # ]:           0 :     for (const auto& key_pair : mapCryptedKeys) {
    1769         [ #  # ]:           0 :         keyids.insert(key_pair.first);
    1770                 :           0 :     }
    1771                 :             : 
    1772                 :             :     // Get key metadata and figure out which keys don't have a seed
    1773                 :             :     // Note that we do not ignore the seeds themselves because they are considered IsMine!
    1774         [ #  # ]:           0 :     for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
    1775                 :           0 :         const CKeyID& keyid = *keyid_it;
    1776         [ #  # ]:           0 :         const auto& it = mapKeyMetadata.find(keyid);
    1777         [ #  # ]:           0 :         if (it != mapKeyMetadata.end()) {
    1778                 :           0 :             const CKeyMetadata& meta = it->second;
    1779   [ #  #  #  #  :           0 :             if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
             #  #  #  # ]
    1780                 :           0 :                 keyid_it++;
    1781                 :           0 :                 continue;
    1782                 :             :             }
    1783   [ #  #  #  #  :           0 :             if (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.count(meta.hd_seed_id) > 0) {
             #  #  #  # ]
    1784         [ #  # ]:           0 :                 keyid_it = keyids.erase(keyid_it);
    1785                 :           0 :                 continue;
    1786                 :             :             }
    1787         [ #  # ]:           0 :         }
    1788                 :           0 :         keyid_it++;
    1789         [ #  # ]:           0 :     }
    1790                 :             : 
    1791                 :             :     // keyids is now all non-HD keys. Each key will have its own combo descriptor
    1792         [ #  # ]:           0 :     for (const CKeyID& keyid : keyids) {
    1793                 :           0 :         CKey key;
    1794   [ #  #  #  # ]:           0 :         if (!GetKey(keyid, key)) {
    1795                 :           0 :             assert(false);
    1796                 :             :         }
    1797                 :             : 
    1798                 :             :         // Get birthdate from key meta
    1799                 :           0 :         uint64_t creation_time = 0;
    1800         [ #  # ]:           0 :         const auto& it = mapKeyMetadata.find(keyid);
    1801         [ #  # ]:           0 :         if (it != mapKeyMetadata.end()) {
    1802                 :           0 :             creation_time = it->second.nCreateTime;
    1803                 :           0 :         }
    1804                 :             : 
    1805                 :             :         // Get the key origin
    1806                 :             :         // Maybe this doesn't matter because floating keys here shouldn't have origins
    1807                 :           0 :         KeyOriginInfo info;
    1808         [ #  # ]:           0 :         bool has_info = GetKeyOrigin(keyid, info);
    1809   [ #  #  #  #  :           0 :         std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1810                 :             : 
    1811                 :             :         // Construct the combo descriptor
    1812   [ #  #  #  #  :           0 :         std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
          #  #  #  #  #  
                #  #  # ]
    1813                 :           0 :         FlatSigningProvider keys;
    1814                 :           0 :         std::string error;
    1815         [ #  # ]:           0 :         std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
    1816   [ #  #  #  # ]:           0 :         WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
    1817                 :             : 
    1818                 :             :         // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
    1819   [ #  #  #  # ]:           0 :         auto desc_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(m_storage, w_desc, m_keypool_size));
    1820   [ #  #  #  # ]:           0 :         desc_spk_man->AddDescriptorKey(key, key.GetPubKey());
    1821         [ #  # ]:           0 :         desc_spk_man->TopUp();
    1822         [ #  # ]:           0 :         auto desc_spks = desc_spk_man->GetScriptPubKeys();
    1823                 :             : 
    1824                 :             :         // Remove the scriptPubKeys from our current set
    1825         [ #  # ]:           0 :         for (const CScript& spk : desc_spks) {
    1826         [ #  # ]:           0 :             size_t erased = spks.erase(spk);
    1827         [ #  # ]:           0 :             assert(erased == 1);
    1828   [ #  #  #  # ]:           0 :             assert(IsMine(spk) == ISMINE_SPENDABLE);
    1829                 :           0 :         }
    1830                 :             : 
    1831         [ #  # ]:           0 :         out.desc_spkms.push_back(std::move(desc_spk_man));
    1832                 :           0 :     }
    1833                 :             : 
    1834                 :             :     // Handle HD keys by using the CHDChains
    1835                 :           0 :     std::vector<CHDChain> chains;
    1836         [ #  # ]:           0 :     chains.push_back(m_hd_chain);
    1837         [ #  # ]:           0 :     for (const auto& chain_pair : m_inactive_hd_chains) {
    1838         [ #  # ]:           0 :         chains.push_back(chain_pair.second);
    1839                 :           0 :     }
    1840         [ #  # ]:           0 :     for (const CHDChain& chain : chains) {
    1841         [ #  # ]:           0 :         for (int i = 0; i < 2; ++i) {
    1842                 :             :             // Skip if doing internal chain and split chain is not supported
    1843   [ #  #  #  #  :           0 :             if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
          #  #  #  #  #  
                      # ]
    1844                 :           0 :                 continue;
    1845                 :             :             }
    1846                 :             :             // Get the master xprv
    1847                 :           0 :             CKey seed_key;
    1848   [ #  #  #  # ]:           0 :             if (!GetKey(chain.seed_id, seed_key)) {
    1849                 :           0 :                 assert(false);
    1850                 :             :             }
    1851         [ #  # ]:           0 :             CExtKey master_key;
    1852   [ #  #  #  # ]:           0 :             master_key.SetSeed(seed_key);
    1853                 :             : 
    1854                 :             :             // Make the combo descriptor
    1855   [ #  #  #  # ]:           0 :             std::string xpub = EncodeExtPubKey(master_key.Neuter());
    1856   [ #  #  #  #  :           0 :             std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
          #  #  #  #  #  
                      # ]
    1857                 :           0 :             FlatSigningProvider keys;
    1858                 :           0 :             std::string error;
    1859         [ #  # ]:           0 :             std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
    1860   [ #  #  #  # ]:           0 :             uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
    1861   [ #  #  #  # ]:           0 :             WalletDescriptor w_desc(std::move(desc), 0, 0, chain_counter, 0);
    1862                 :             : 
    1863                 :             :             // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
    1864   [ #  #  #  # ]:           0 :             auto desc_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(m_storage, w_desc, m_keypool_size));
    1865   [ #  #  #  # ]:           0 :             desc_spk_man->AddDescriptorKey(master_key.key, master_key.key.GetPubKey());
    1866         [ #  # ]:           0 :             desc_spk_man->TopUp();
    1867         [ #  # ]:           0 :             auto desc_spks = desc_spk_man->GetScriptPubKeys();
    1868                 :             : 
    1869                 :             :             // Remove the scriptPubKeys from our current set
    1870         [ #  # ]:           0 :             for (const CScript& spk : desc_spks) {
    1871         [ #  # ]:           0 :                 size_t erased = spks.erase(spk);
    1872         [ #  # ]:           0 :                 assert(erased == 1);
    1873   [ #  #  #  # ]:           0 :                 assert(IsMine(spk) == ISMINE_SPENDABLE);
    1874                 :           0 :             }
    1875                 :             : 
    1876         [ #  # ]:           0 :             out.desc_spkms.push_back(std::move(desc_spk_man));
    1877                 :           0 :         }
    1878                 :           0 :     }
    1879                 :             :     // Add the current master seed to the migration data
    1880   [ #  #  #  # ]:           0 :     if (!m_hd_chain.seed_id.IsNull()) {
    1881                 :           0 :         CKey seed_key;
    1882   [ #  #  #  # ]:           0 :         if (!GetKey(m_hd_chain.seed_id, seed_key)) {
    1883                 :           0 :             assert(false);
    1884                 :             :         }
    1885   [ #  #  #  # ]:           0 :         out.master_key.SetSeed(seed_key);
    1886                 :           0 :     }
    1887                 :             : 
    1888                 :             :     // Handle the rest of the scriptPubKeys which must be imports and may not have all info
    1889         [ #  # ]:           0 :     for (auto it = spks.begin(); it != spks.end();) {
    1890                 :           0 :         const CScript& spk = *it;
    1891                 :             : 
    1892                 :             :         // Get birthdate from script meta
    1893                 :           0 :         uint64_t creation_time = 0;
    1894   [ #  #  #  # ]:           0 :         const auto& mit = m_script_metadata.find(CScriptID(spk));
    1895         [ #  # ]:           0 :         if (mit != m_script_metadata.end()) {
    1896                 :           0 :             creation_time = mit->second.nCreateTime;
    1897                 :           0 :         }
    1898                 :             : 
    1899                 :             :         // InferDescriptor as that will get us all the solving info if it is there
    1900   [ #  #  #  # ]:           0 :         std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
    1901                 :             :         // Get the private keys for this descriptor
    1902                 :           0 :         std::vector<CScript> scripts;
    1903                 :           0 :         FlatSigningProvider keys;
    1904   [ #  #  #  # ]:           0 :         if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
    1905                 :           0 :             assert(false);
    1906                 :             :         }
    1907                 :           0 :         std::set<CKeyID> privkeyids;
    1908         [ #  # ]:           0 :         for (const auto& key_orig_pair : keys.origins) {
    1909         [ #  # ]:           0 :             privkeyids.insert(key_orig_pair.first);
    1910                 :           0 :         }
    1911                 :             : 
    1912                 :           0 :         std::vector<CScript> desc_spks;
    1913                 :             : 
    1914                 :             :         // Make the descriptor string with private keys
    1915                 :           0 :         std::string desc_str;
    1916         [ #  # ]:           0 :         bool watchonly = !desc->ToPrivateString(*this, desc_str);
    1917   [ #  #  #  #  :           0 :         if (watchonly && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
                   #  # ]
    1918   [ #  #  #  # ]:           0 :             out.watch_descs.emplace_back(desc->ToString(), creation_time);
    1919                 :             : 
    1920                 :             :             // Get the scriptPubKeys without writing this to the wallet
    1921                 :           0 :             FlatSigningProvider provider;
    1922         [ #  # ]:           0 :             desc->Expand(0, provider, desc_spks, provider);
    1923                 :           0 :         } else {
    1924                 :             :             // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
    1925   [ #  #  #  # ]:           0 :             WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
    1926   [ #  #  #  # ]:           0 :             auto desc_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(m_storage, w_desc, m_keypool_size));
    1927         [ #  # ]:           0 :             for (const auto& keyid : privkeyids) {
    1928                 :           0 :                 CKey key;
    1929   [ #  #  #  # ]:           0 :                 if (!GetKey(keyid, key)) {
    1930                 :           0 :                     continue;
    1931                 :             :                 }
    1932   [ #  #  #  # ]:           0 :                 desc_spk_man->AddDescriptorKey(key, key.GetPubKey());
    1933   [ #  #  #  # ]:           0 :             }
    1934         [ #  # ]:           0 :             desc_spk_man->TopUp();
    1935         [ #  # ]:           0 :             auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
    1936         [ #  # ]:           0 :             desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
    1937                 :             : 
    1938         [ #  # ]:           0 :             out.desc_spkms.push_back(std::move(desc_spk_man));
    1939                 :           0 :         }
    1940                 :             : 
    1941                 :             :         // Remove the scriptPubKeys from our current set
    1942         [ #  # ]:           0 :         for (const CScript& desc_spk : desc_spks) {
    1943         [ #  # ]:           0 :             auto del_it = spks.find(desc_spk);
    1944         [ #  # ]:           0 :             assert(del_it != spks.end());
    1945   [ #  #  #  # ]:           0 :             assert(IsMine(desc_spk) != ISMINE_NO);
    1946         [ #  # ]:           0 :             it = spks.erase(del_it);
    1947                 :           0 :         }
    1948                 :           0 :     }
    1949                 :             : 
    1950                 :             :     // Multisigs are special. They don't show up as ISMINE_SPENDABLE unless they are in a P2SH
    1951                 :             :     // So we have to check if any of our scripts are a multisig and if so, add the P2SH
    1952         [ #  # ]:           0 :     for (const auto& script_pair : mapScripts) {
    1953         [ #  # ]:           0 :         const CScript script = script_pair.second;
    1954                 :             : 
    1955                 :             :         // Get birthdate from script meta
    1956                 :           0 :         uint64_t creation_time = 0;
    1957   [ #  #  #  # ]:           0 :         const auto& it = m_script_metadata.find(CScriptID(script));
    1958         [ #  # ]:           0 :         if (it != m_script_metadata.end()) {
    1959                 :           0 :             creation_time = it->second.nCreateTime;
    1960                 :           0 :         }
    1961                 :             : 
    1962                 :           0 :         std::vector<std::vector<unsigned char>> sols;
    1963         [ #  # ]:           0 :         TxoutType type = Solver(script, sols);
    1964         [ #  # ]:           0 :         if (type == TxoutType::MULTISIG) {
    1965   [ #  #  #  # ]:           0 :             CScript sh_spk = GetScriptForDestination(ScriptHash(script));
    1966         [ #  # ]:           0 :             CTxDestination witdest = WitnessV0ScriptHash(script);
    1967         [ #  # ]:           0 :             CScript witprog = GetScriptForDestination(witdest);
    1968   [ #  #  #  # ]:           0 :             CScript sh_wsh_spk = GetScriptForDestination(ScriptHash(witprog));
    1969                 :             : 
    1970                 :             :             // We only want the multisigs that we have not already seen, i.e. they are not watchonly and not spendable
    1971                 :             :             // For P2SH, a multisig is not ISMINE_NO when:
    1972                 :             :             // * All keys are in the wallet
    1973                 :             :             // * The multisig itself is watch only
    1974                 :             :             // * The P2SH is watch only
    1975                 :             :             // For P2SH-P2WSH, if the script is in the wallet, then it will have the same conditions as P2SH.
    1976                 :             :             // For P2WSH, a multisig is not ISMINE_NO when, other than the P2SH conditions:
    1977                 :             :             // * The P2WSH script is in the wallet and it is being watched
    1978         [ #  # ]:           0 :             std::vector<std::vector<unsigned char>> keys(sols.begin() + 1, sols.begin() + sols.size() - 1);
    1979   [ #  #  #  #  :           0 :             if (HaveWatchOnly(sh_spk) || HaveWatchOnly(script) || HaveKeys(keys, *this) || (HaveCScript(CScriptID(witprog)) && HaveWatchOnly(witprog))) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                #  #  # ]
    1980                 :             :                 // The above emulates IsMine for these 3 scriptPubKeys, so double check that by running IsMine
    1981   [ #  #  #  #  :           0 :                 assert(IsMine(sh_spk) != ISMINE_NO || IsMine(witprog) != ISMINE_NO || IsMine(sh_wsh_spk) != ISMINE_NO);
          #  #  #  #  #  
                #  #  # ]
    1982                 :           0 :                 continue;
    1983                 :             :             }
    1984   [ #  #  #  #  :           0 :             assert(IsMine(sh_spk) == ISMINE_NO && IsMine(witprog) == ISMINE_NO && IsMine(sh_wsh_spk) == ISMINE_NO);
          #  #  #  #  #  
                #  #  # ]
    1985                 :             : 
    1986   [ #  #  #  # ]:           0 :             std::unique_ptr<Descriptor> sh_desc = InferDescriptor(sh_spk, *GetSolvingProvider(sh_spk));
    1987   [ #  #  #  # ]:           0 :             out.solvable_descs.emplace_back(sh_desc->ToString(), creation_time);
    1988                 :             : 
    1989         [ #  # ]:           0 :             const auto desc = InferDescriptor(witprog, *this);
    1990   [ #  #  #  # ]:           0 :             if (desc->IsSolvable()) {
    1991   [ #  #  #  # ]:           0 :                 std::unique_ptr<Descriptor> wsh_desc = InferDescriptor(witprog, *GetSolvingProvider(witprog));
    1992   [ #  #  #  # ]:           0 :                 out.solvable_descs.emplace_back(wsh_desc->ToString(), creation_time);
    1993   [ #  #  #  # ]:           0 :                 std::unique_ptr<Descriptor> sh_wsh_desc = InferDescriptor(sh_wsh_spk, *GetSolvingProvider(sh_wsh_spk));
    1994   [ #  #  #  # ]:           0 :                 out.solvable_descs.emplace_back(sh_wsh_desc->ToString(), creation_time);
    1995                 :           0 :             }
    1996         [ #  # ]:           0 :         }
    1997   [ #  #  #  # ]:           0 :     }
    1998                 :             : 
    1999                 :             :     // Make sure that we have accounted for all scriptPubKeys
    2000         [ #  # ]:           0 :     assert(spks.size() == 0);
    2001                 :           0 :     return out;
    2002                 :           0 : }
    2003                 :             : 
    2004                 :           0 : bool LegacyScriptPubKeyMan::DeleteRecords()
    2005                 :             : {
    2006                 :           0 :     LOCK(cs_KeyStore);
    2007   [ #  #  #  # ]:           0 :     WalletBatch batch(m_storage.GetDatabase());
    2008         [ #  # ]:           0 :     return batch.EraseRecords(DBKeys::LEGACY_TYPES);
    2009                 :           0 : }
    2010                 :             : 
    2011                 :      548478 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
    2012                 :             : {
    2013                 :             :     // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
    2014         [ +  + ]:      548478 :     if (!CanGetAddresses()) {
    2015         [ +  - ]:         249 :         return util::Error{_("No addresses available")};
    2016                 :             :     }
    2017                 :             :     {
    2018                 :      548229 :         LOCK(cs_desc_man);
    2019   [ +  -  +  - ]:      548229 :         assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
    2020         [ +  - ]:      548229 :         std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
    2021         [ +  - ]:      548229 :         assert(desc_addr_type);
    2022         [ +  - ]:      548229 :         if (type != *desc_addr_type) {
    2023   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
          #  #  #  #  #  
                      # ]
    2024                 :             :         }
    2025                 :             : 
    2026         [ +  - ]:      548229 :         TopUp();
    2027                 :             : 
    2028                 :             :         // Get the scriptPubKey from the descriptor
    2029                 :      548229 :         FlatSigningProvider out_keys;
    2030                 :      548229 :         std::vector<CScript> scripts_temp;
    2031   [ -  +  #  #  :      548229 :         if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
                   #  # ]
    2032                 :             :             // We can't generate anymore keys
    2033   [ #  #  #  # ]:           0 :             return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
    2034                 :             :         }
    2035   [ +  -  +  + ]:      548229 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
    2036                 :             :             // We can't generate anymore keys
    2037   [ +  -  +  - ]:           2 :             return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
    2038                 :             :         }
    2039                 :             : 
    2040         [ +  - ]:      548227 :         CTxDestination dest;
    2041   [ +  -  -  + ]:      548227 :         if (!ExtractDestination(scripts_temp[0], dest)) {
    2042   [ #  #  #  # ]:           0 :             return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
    2043                 :             :         }
    2044                 :      548227 :         m_wallet_descriptor.next_index++;
    2045   [ +  -  +  -  :      548227 :         WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
             +  -  +  - ]
    2046         [ +  - ]:      548227 :         return dest;
    2047                 :      548229 :     }
    2048                 :      548478 : }
    2049                 :             : 
    2050                 :    11573927 : isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
    2051                 :             : {
    2052                 :    11573927 :     LOCK(cs_desc_man);
    2053   [ +  -  +  + ]:    11573927 :     if (m_map_script_pub_keys.count(script) > 0) {
    2054                 :    11571552 :         return ISMINE_SPENDABLE;
    2055                 :             :     }
    2056                 :        2375 :     return ISMINE_NO;
    2057                 :    11573927 : }
    2058                 :             : 
    2059                 :           0 : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
    2060                 :             : {
    2061                 :           0 :     LOCK(cs_desc_man);
    2062         [ #  # ]:           0 :     if (!m_map_keys.empty()) {
    2063                 :           0 :         return false;
    2064                 :             :     }
    2065                 :             : 
    2066                 :           0 :     bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
    2067                 :           0 :     bool keyFail = false;
    2068         [ #  # ]:           0 :     for (const auto& mi : m_map_crypted_keys) {
    2069                 :           0 :         const CPubKey &pubkey = mi.second.first;
    2070                 :           0 :         const std::vector<unsigned char> &crypted_secret = mi.second.second;
    2071                 :           0 :         CKey key;
    2072   [ #  #  #  # ]:           0 :         if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
    2073                 :           0 :             keyFail = true;
    2074                 :           0 :             break;
    2075                 :             :         }
    2076                 :           0 :         keyPass = true;
    2077         [ #  # ]:           0 :         if (m_decryption_thoroughly_checked)
    2078                 :           0 :             break;
    2079   [ #  #  #  # ]:           0 :     }
    2080   [ #  #  #  # ]:           0 :     if (keyPass && keyFail) {
    2081   [ #  #  #  #  :           0 :         LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
                   #  # ]
    2082   [ #  #  #  # ]:           0 :         throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
    2083                 :             :     }
    2084   [ #  #  #  # ]:           0 :     if (keyFail || !keyPass) {
    2085                 :           0 :         return false;
    2086                 :             :     }
    2087                 :           0 :     m_decryption_thoroughly_checked = true;
    2088                 :           0 :     return true;
    2089                 :           0 : }
    2090                 :             : 
    2091                 :           0 : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
    2092                 :             : {
    2093                 :           0 :     LOCK(cs_desc_man);
    2094         [ #  # ]:           0 :     if (!m_map_crypted_keys.empty()) {
    2095                 :           0 :         return false;
    2096                 :             :     }
    2097                 :             : 
    2098   [ #  #  #  # ]:           0 :     for (const KeyMap::value_type& key_in : m_map_keys)
    2099                 :             :     {
    2100                 :           0 :         const CKey &key = key_in.second;
    2101         [ #  # ]:           0 :         CPubKey pubkey = key.GetPubKey();
    2102   [ #  #  #  #  :           0 :         CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
          #  #  #  #  #  
                      # ]
    2103                 :           0 :         std::vector<unsigned char> crypted_secret;
    2104   [ #  #  #  #  :           0 :         if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
                   #  # ]
    2105                 :           0 :             return false;
    2106                 :             :         }
    2107   [ #  #  #  #  :           0 :         m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
                   #  # ]
    2108   [ #  #  #  # ]:           0 :         batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
    2109   [ #  #  #  # ]:           0 :     }
    2110                 :           0 :     m_map_keys.clear();
    2111                 :           0 :     return true;
    2112                 :           0 : }
    2113                 :             : 
    2114                 :      203863 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
    2115                 :             : {
    2116                 :      203863 :     LOCK(cs_desc_man);
    2117         [ +  - ]:      203863 :     auto op_dest = GetNewDestination(type);
    2118                 :      203863 :     index = m_wallet_descriptor.next_index - 1;
    2119                 :      203863 :     return op_dest;
    2120         [ +  - ]:      203863 : }
    2121                 :             : 
    2122                 :       14727 : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
    2123                 :             : {
    2124                 :       14727 :     LOCK(cs_desc_man);
    2125                 :             :     // Only return when the index was the most recent
    2126         [ -  + ]:       14727 :     if (m_wallet_descriptor.next_index - 1 == index) {
    2127                 :       14727 :         m_wallet_descriptor.next_index--;
    2128                 :       14727 :     }
    2129   [ +  -  +  -  :       14727 :     WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
             +  -  +  - ]
    2130         [ +  - ]:       14727 :     NotifyCanGetAddressesChanged();
    2131                 :       14727 : }
    2132                 :             : 
    2133                 :     1043614 : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
    2134                 :             : {
    2135                 :     1043614 :     AssertLockHeld(cs_desc_man);
    2136   [ -  +  #  # ]:     1043614 :     if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
    2137                 :           0 :         KeyMap keys;
    2138         [ #  # ]:           0 :         for (const auto& key_pair : m_map_crypted_keys) {
    2139                 :           0 :             const CPubKey& pubkey = key_pair.second.first;
    2140                 :           0 :             const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
    2141                 :           0 :             CKey key;
    2142   [ #  #  #  # ]:           0 :             m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
    2143                 :           0 :                 return DecryptKey(encryption_key, crypted_secret, pubkey, key);
    2144                 :             :             });
    2145   [ #  #  #  #  :           0 :             keys[pubkey.GetID()] = key;
                   #  # ]
    2146                 :           0 :         }
    2147                 :           0 :         return keys;
    2148         [ #  # ]:           0 :     }
    2149                 :     1043614 :     return m_map_keys;
    2150                 :     1043614 : }
    2151                 :             : 
    2152                 :        1885 : bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
    2153                 :             : {
    2154                 :        1885 :     AssertLockHeld(cs_desc_man);
    2155         [ +  - ]:        1885 :     return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
    2156                 :             : }
    2157                 :             : 
    2158                 :        1885 : std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
    2159                 :             : {
    2160                 :        1885 :     AssertLockHeld(cs_desc_man);
    2161   [ -  +  #  # ]:        1885 :     if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
    2162                 :           0 :         const auto& it = m_map_crypted_keys.find(keyid);
    2163         [ #  # ]:           0 :         if (it == m_map_crypted_keys.end()) {
    2164                 :           0 :             return std::nullopt;
    2165                 :             :         }
    2166                 :           0 :         const std::vector<unsigned char>& crypted_secret = it->second.second;
    2167                 :           0 :         CKey key;
    2168   [ #  #  #  #  :           0 :         if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
             #  #  #  # ]
    2169                 :             :             return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
    2170                 :             :         }))) {
    2171                 :           0 :             return std::nullopt;
    2172                 :             :         }
    2173                 :           0 :         return key;
    2174                 :           0 :     }
    2175                 :        1885 :     const auto& it = m_map_keys.find(keyid);
    2176         [ -  + ]:        1885 :     if (it == m_map_keys.end()) {
    2177                 :           0 :         return std::nullopt;
    2178                 :             :     }
    2179                 :        1885 :     return it->second;
    2180                 :        1885 : }
    2181                 :             : 
    2182                 :     1019740 : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
    2183                 :             : {
    2184                 :     1019740 :     WalletBatch batch(m_storage.GetDatabase());
    2185   [ +  -  +  - ]:     1019740 :     if (!batch.TxnBegin()) return false;
    2186         [ +  - ]:     1019740 :     bool res = TopUpWithDB(batch, size);
    2187   [ +  -  +  -  :     1019740 :     if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    2188                 :     1019740 :     return res;
    2189                 :     1019740 : }
    2190                 :             : 
    2191                 :     1019740 : bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
    2192                 :             : {
    2193                 :     1019740 :     LOCK(cs_desc_man);
    2194                 :     1019740 :     std::set<CScript> new_spks;
    2195                 :     1019740 :     unsigned int target_size;
    2196         [ -  + ]:     1019740 :     if (size > 0) {
    2197                 :           0 :         target_size = size;
    2198                 :           0 :     } else {
    2199                 :     1019740 :         target_size = m_keypool_size;
    2200                 :             :     }
    2201                 :             : 
    2202                 :             :     // Calculate the new range_end
    2203         [ +  - ]:     1019740 :     int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
    2204                 :             : 
    2205                 :             :     // If the descriptor is not ranged, we actually just want to fill the first cache item
    2206   [ +  -  +  + ]:     1019740 :     if (!m_wallet_descriptor.descriptor->IsRange()) {
    2207                 :        9838 :         new_range_end = 1;
    2208                 :        9838 :         m_wallet_descriptor.range_end = 1;
    2209                 :        9838 :         m_wallet_descriptor.range_start = 0;
    2210                 :        9838 :     }
    2211                 :             : 
    2212                 :     1019740 :     FlatSigningProvider provider;
    2213         [ +  - ]:     1019740 :     provider.keys = GetKeys();
    2214                 :             : 
    2215         [ +  - ]:     1019740 :     uint256 id = GetID();
    2216   [ +  +  +  + ]:     2776493 :     for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
    2217                 :     1756753 :         FlatSigningProvider out_keys;
    2218                 :     1756753 :         std::vector<CScript> scripts_temp;
    2219                 :     1756753 :         DescriptorCache temp_cache;
    2220                 :             :         // Maybe we have a cached xpub and we can expand from the cache first
    2221   [ +  -  +  + ]:     1756753 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
    2222   [ +  -  +  + ]:      565148 :             if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
    2223                 :      564996 :         }
    2224                 :             :         // Add all of the scriptPubKeys to the scriptPubKey set
    2225         [ +  - ]:     1756601 :         new_spks.insert(scripts_temp.begin(), scripts_temp.end());
    2226         [ +  + ]:     4138232 :         for (const CScript& script : scripts_temp) {
    2227         [ +  - ]:     2381631 :             m_map_script_pub_keys[script] = i;
    2228                 :     2381631 :         }
    2229         [ +  + ]:     3668277 :         for (const auto& pk_pair : out_keys.pubkeys) {
    2230                 :     1911676 :             const CPubKey& pubkey = pk_pair.second;
    2231   [ +  -  +  + ]:     1911676 :             if (m_map_pubkeys.count(pubkey) != 0) {
    2232                 :             :                 // We don't need to give an error here.
    2233                 :             :                 // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
    2234                 :      223019 :                 continue;
    2235                 :             :             }
    2236         [ +  - ]:     1688657 :             m_map_pubkeys[pubkey] = i;
    2237   [ +  +  +  + ]:     1911676 :         }
    2238                 :             :         // Merge and write the cache
    2239         [ +  - ]:     1756601 :         DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
    2240   [ +  -  +  - ]:     1756601 :         if (!batch.WriteDescriptorCacheItems(id, new_items)) {
    2241   [ #  #  #  #  :           0 :             throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
             #  #  #  # ]
    2242                 :             :         }
    2243                 :     1756601 :         m_max_cached_index++;
    2244         [ +  + ]:     1756753 :     }
    2245                 :     1019588 :     m_wallet_descriptor.range_end = new_range_end;
    2246   [ +  -  +  - ]:     1019588 :     batch.WriteDescriptor(GetID(), m_wallet_descriptor);
    2247                 :             : 
    2248                 :             :     // By this point, the cache size should be the size of the entire range
    2249         [ +  - ]:     1019588 :     assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
    2250                 :             : 
    2251         [ +  - ]:     1019588 :     m_storage.TopUpCallback(new_spks, this);
    2252         [ +  - ]:     1019588 :     NotifyCanGetAddressesChanged();
    2253                 :     1019588 :     return true;
    2254                 :     1019740 : }
    2255                 :             : 
    2256                 :      440567 : std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
    2257                 :             : {
    2258                 :      440567 :     LOCK(cs_desc_man);
    2259                 :      440567 :     std::vector<WalletDestination> result;
    2260   [ +  -  -  + ]:      440567 :     if (IsMine(script)) {
    2261         [ +  - ]:      440567 :         int32_t index = m_map_script_pub_keys[script];
    2262         [ +  + ]:      440567 :         if (index >= m_wallet_descriptor.next_index) {
    2263         [ +  - ]:         467 :             WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
    2264         [ +  - ]:         467 :             auto out_keys = std::make_unique<FlatSigningProvider>();
    2265                 :         467 :             std::vector<CScript> scripts_temp;
    2266         [ +  + ]:       81383 :             while (index >= m_wallet_descriptor.next_index) {
    2267   [ +  -  +  - ]:       80916 :                 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
    2268   [ #  #  #  #  :           0 :                     throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
          #  #  #  #  #  
                      # ]
    2269                 :             :                 }
    2270         [ -  + ]:       80916 :                 CTxDestination dest;
    2271         [ -  + ]:       80916 :                 ExtractDestination(scripts_temp[0], dest);
    2272   [ -  +  +  - ]:       80916 :                 result.push_back({dest, std::nullopt});
    2273                 :       80916 :                 m_wallet_descriptor.next_index++;
    2274                 :       80916 :             }
    2275                 :         467 :         }
    2276   [ +  -  -  + ]:      440567 :         if (!TopUp()) {
    2277         [ #  # ]:           0 :             WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
    2278                 :           0 :         }
    2279                 :      440567 :     }
    2280                 :             : 
    2281                 :      440567 :     return result;
    2282         [ +  - ]:      440567 : }
    2283                 :             : 
    2284                 :       25412 : void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
    2285                 :             : {
    2286                 :       25412 :     LOCK(cs_desc_man);
    2287   [ +  -  +  - ]:       25412 :     WalletBatch batch(m_storage.GetDatabase());
    2288   [ +  -  +  - ]:       25412 :     if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
    2289   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
          #  #  #  #  #  
                      # ]
    2290                 :             :     }
    2291                 :       25412 : }
    2292                 :             : 
    2293                 :       25412 : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
    2294                 :             : {
    2295                 :       25412 :     AssertLockHeld(cs_desc_man);
    2296         [ +  - ]:       25412 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
    2297                 :             : 
    2298                 :             :     // Check if provided key already exists
    2299   [ +  +  +  + ]:       25412 :     if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
    2300                 :       25382 :         m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
    2301                 :          30 :         return true;
    2302                 :             :     }
    2303                 :             : 
    2304         [ -  + ]:       25382 :     if (m_storage.HasEncryptionKeys()) {
    2305         [ #  # ]:           0 :         if (m_storage.IsLocked()) {
    2306                 :           0 :             return false;
    2307                 :             :         }
    2308                 :             : 
    2309                 :           0 :         std::vector<unsigned char> crypted_secret;
    2310   [ #  #  #  #  :           0 :         CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
          #  #  #  #  #  
                      # ]
    2311   [ #  #  #  #  :           0 :         if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
                   #  # ]
    2312                 :           0 :                 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
    2313                 :             :             })) {
    2314                 :           0 :             return false;
    2315                 :             :         }
    2316                 :             : 
    2317   [ #  #  #  #  :           0 :         m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
                   #  # ]
    2318   [ #  #  #  # ]:           0 :         return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
    2319                 :           0 :     } else {
    2320                 :       25382 :         m_map_keys[pubkey.GetID()] = key;
    2321         [ +  - ]:       25382 :         return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
    2322                 :             :     }
    2323                 :       25412 : }
    2324                 :             : 
    2325                 :           0 : bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
    2326                 :             : {
    2327                 :           0 :     LOCK(cs_desc_man);
    2328   [ #  #  #  # ]:           0 :     assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    2329                 :             : 
    2330                 :             :     // Ignore when there is already a descriptor
    2331         [ #  # ]:           0 :     if (m_wallet_descriptor.descriptor) {
    2332                 :           0 :         return false;
    2333                 :             :     }
    2334                 :             : 
    2335   [ #  #  #  # ]:           0 :     m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
    2336                 :             : 
    2337                 :             :     // Store the master private key, and descriptor
    2338   [ #  #  #  #  :           0 :     if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
                   #  # ]
    2339   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
          #  #  #  #  #  
                      # ]
    2340                 :             :     }
    2341   [ #  #  #  #  :           0 :     if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
                   #  # ]
    2342   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
             #  #  #  # ]
    2343                 :             :     }
    2344                 :             : 
    2345                 :             :     // TopUp
    2346         [ #  # ]:           0 :     TopUpWithDB(batch);
    2347                 :             : 
    2348         [ #  # ]:           0 :     m_storage.UnsetBlankWalletFlag(batch);
    2349                 :           0 :     return true;
    2350                 :           0 : }
    2351                 :             : 
    2352                 :         382 : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
    2353                 :             : {
    2354                 :         382 :     LOCK(cs_desc_man);
    2355         [ +  - ]:         382 :     return m_wallet_descriptor.descriptor->IsRange();
    2356                 :         382 : }
    2357                 :             : 
    2358                 :      548478 : bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
    2359                 :             : {
    2360                 :             :     // We can only give out addresses from descriptors that are single type (not combo), ranged,
    2361                 :             :     // and either have cached keys or can generate more keys (ignoring encryption)
    2362                 :      548478 :     LOCK(cs_desc_man);
    2363   [ +  -  +  - ]:      548478 :     return m_wallet_descriptor.descriptor->IsSingleType() &&
    2364   [ +  -  +  + ]:      548478 :            m_wallet_descriptor.descriptor->IsRange() &&
    2365   [ +  -  +  + ]:      548229 :            (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
    2366                 :      548478 : }
    2367                 :             : 
    2368                 :     5353122 : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
    2369                 :             : {
    2370                 :     5353122 :     LOCK(cs_desc_man);
    2371         [ +  + ]:     5353122 :     return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
    2372                 :     5353122 : }
    2373                 :             : 
    2374                 :           0 : std::optional<int64_t> DescriptorScriptPubKeyMan::GetOldestKeyPoolTime() const
    2375                 :             : {
    2376                 :             :     // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
    2377                 :           0 :     return std::nullopt;
    2378                 :             : }
    2379                 :             : 
    2380                 :             : 
    2381                 :        7213 : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
    2382                 :             : {
    2383                 :        7213 :     LOCK(cs_desc_man);
    2384                 :        7213 :     return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
    2385                 :        7213 : }
    2386                 :             : 
    2387                 :       29021 : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
    2388                 :             : {
    2389                 :       29021 :     LOCK(cs_desc_man);
    2390                 :       29021 :     return m_wallet_descriptor.creation_time;
    2391                 :       29021 : }
    2392                 :             : 
    2393                 :     5159590 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
    2394                 :             : {
    2395                 :     5159590 :     LOCK(cs_desc_man);
    2396                 :             : 
    2397                 :             :     // Find the index of the script
    2398         [ +  - ]:     5159590 :     auto it = m_map_script_pub_keys.find(script);
    2399         [ +  + ]:     5159590 :     if (it == m_map_script_pub_keys.end()) {
    2400                 :      354697 :         return nullptr;
    2401                 :             :     }
    2402                 :     4804893 :     int32_t index = it->second;
    2403                 :             : 
    2404         [ +  - ]:     4804893 :     return GetSigningProvider(index, include_private);
    2405                 :     5159590 : }
    2406                 :             : 
    2407                 :           0 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
    2408                 :             : {
    2409                 :           0 :     LOCK(cs_desc_man);
    2410                 :             : 
    2411                 :             :     // Find index of the pubkey
    2412         [ #  # ]:           0 :     auto it = m_map_pubkeys.find(pubkey);
    2413         [ #  # ]:           0 :     if (it == m_map_pubkeys.end()) {
    2414                 :           0 :         return nullptr;
    2415                 :             :     }
    2416                 :           0 :     int32_t index = it->second;
    2417                 :             : 
    2418                 :             :     // Always try to get the signing provider with private keys. This function should only be called during signing anyways
    2419         [ #  # ]:           0 :     return GetSigningProvider(index, true);
    2420                 :           0 : }
    2421                 :             : 
    2422                 :     4804893 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
    2423                 :             : {
    2424                 :     4804893 :     AssertLockHeld(cs_desc_man);
    2425                 :             : 
    2426                 :     4804893 :     std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
    2427                 :             : 
    2428                 :             :     // Fetch SigningProvider from cache to avoid re-deriving
    2429         [ +  - ]:     4804893 :     auto it = m_map_signing_providers.find(index);
    2430         [ +  + ]:     4804893 :     if (it != m_map_signing_providers.end()) {
    2431   [ +  -  +  - ]:     4230573 :         out_keys->Merge(FlatSigningProvider{it->second});
    2432                 :     4230573 :     } else {
    2433                 :             :         // Get the scripts, keys, and key origins for this script
    2434                 :      574320 :         std::vector<CScript> scripts_temp;
    2435   [ +  -  +  - ]:      574320 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
    2436                 :             : 
    2437                 :             :         // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
    2438   [ +  -  +  - ]:      574320 :         m_map_signing_providers[index] = *out_keys;
    2439         [ -  + ]:      574320 :     }
    2440                 :             : 
    2441   [ +  -  +  +  :     4804893 :     if (HavePrivateKeys() && include_private) {
                   +  + ]
    2442                 :       14974 :         FlatSigningProvider master_provider;
    2443         [ +  - ]:       14974 :         master_provider.keys = GetKeys();
    2444         [ +  - ]:       14974 :         m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
    2445                 :       14974 :     }
    2446                 :             : 
    2447                 :     4804893 :     return out_keys;
    2448                 :     4804893 : }
    2449                 :             : 
    2450                 :     4419823 : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
    2451                 :             : {
    2452                 :     4419823 :     return GetSigningProvider(script, false);
    2453                 :             : }
    2454                 :             : 
    2455                 :     4822133 : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
    2456                 :             : {
    2457                 :     4822133 :     return IsMine(script);
    2458                 :             : }
    2459                 :             : 
    2460                 :         175 : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
    2461                 :             : {
    2462                 :         175 :     std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
    2463         [ +  + ]:         238 :     for (const auto& coin_pair : coins) {
    2464         [ -  + ]:          63 :         std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
    2465         [ -  + ]:          63 :         if (!coin_keys) {
    2466                 :          63 :             continue;
    2467                 :             :         }
    2468         [ #  # ]:           0 :         keys->Merge(std::move(*coin_keys));
    2469   [ +  -  -  +  :          63 :     }
                      - ]
    2470                 :             : 
    2471         [ +  - ]:         175 :     return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
    2472                 :         175 : }
    2473                 :             : 
    2474                 :      369852 : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
    2475                 :             : {
    2476   [ +  -  +  - ]:      369852 :     std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
    2477         [ +  + ]:      369852 :     if (!keys) {
    2478                 :      354585 :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
    2479                 :             :     }
    2480                 :             : 
    2481                 :       15267 :     CKey key;
    2482   [ +  -  +  -  :       15267 :     if (!keys->GetKey(ToKeyID(pkhash), key)) {
                   +  + ]
    2483                 :         302 :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
    2484                 :             :     }
    2485                 :             : 
    2486   [ +  -  +  - ]:       14965 :     if (!MessageSign(key, message, str_sig)) {
    2487                 :           0 :         return SigningResult::SIGNING_FAILED;
    2488                 :             :     }
    2489                 :       14965 :     return SigningResult::OK;
    2490                 :      369852 : }
    2491                 :             : 
    2492                 :          55 : std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
    2493                 :             : {
    2494         [ -  + ]:          55 :     if (n_signed) {
    2495                 :           0 :         *n_signed = 0;
    2496                 :           0 :     }
    2497   [ -  +  -  + ]:          55 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
    2498                 :           0 :         const CTxIn& txin = psbtx.tx->vin[i];
    2499                 :           0 :         PSBTInput& input = psbtx.inputs.at(i);
    2500                 :             : 
    2501         [ #  # ]:           0 :         if (PSBTInputSigned(input)) {
    2502                 :           0 :             continue;
    2503                 :             :         }
    2504                 :             : 
    2505                 :             :         // Get the Sighash type
    2506   [ #  #  #  #  :           0 :         if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
                   #  # ]
    2507                 :           0 :             return PSBTError::SIGHASH_MISMATCH;
    2508                 :             :         }
    2509                 :             : 
    2510                 :             :         // Get the scriptPubKey to know which SigningProvider to use
    2511                 :           0 :         CScript script;
    2512   [ #  #  #  # ]:           0 :         if (!input.witness_utxo.IsNull()) {
    2513         [ #  # ]:           0 :             script = input.witness_utxo.scriptPubKey;
    2514         [ #  # ]:           0 :         } else if (input.non_witness_utxo) {
    2515         [ #  # ]:           0 :             if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
    2516                 :           0 :                 return PSBTError::MISSING_INPUTS;
    2517                 :             :             }
    2518         [ #  # ]:           0 :             script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
    2519                 :           0 :         } else {
    2520                 :             :             // There's no UTXO so we can just skip this now
    2521                 :           0 :             continue;
    2522                 :             :         }
    2523                 :             : 
    2524         [ #  # ]:           0 :         std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
    2525         [ #  # ]:           0 :         std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
    2526         [ #  # ]:           0 :         if (script_keys) {
    2527         [ #  # ]:           0 :             keys->Merge(std::move(*script_keys));
    2528                 :           0 :         } else {
    2529                 :             :             // Maybe there are pubkeys listed that we can sign for
    2530                 :           0 :             std::vector<CPubKey> pubkeys;
    2531         [ #  # ]:           0 :             pubkeys.reserve(input.hd_keypaths.size() + 2);
    2532                 :             : 
    2533                 :             :             // ECDSA Pubkeys
    2534         [ #  # ]:           0 :             for (const auto& [pk, _] : input.hd_keypaths) {
    2535         [ #  # ]:           0 :                 pubkeys.push_back(pk);
    2536                 :           0 :             }
    2537                 :             : 
    2538                 :             :             // Taproot output pubkey
    2539                 :           0 :             std::vector<std::vector<unsigned char>> sols;
    2540   [ #  #  #  # ]:           0 :             if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
    2541         [ #  # ]:           0 :                 sols[0].insert(sols[0].begin(), 0x02);
    2542         [ #  # ]:           0 :                 pubkeys.emplace_back(sols[0]);
    2543                 :           0 :                 sols[0][0] = 0x03;
    2544         [ #  # ]:           0 :                 pubkeys.emplace_back(sols[0]);
    2545                 :           0 :             }
    2546                 :             : 
    2547                 :             :             // Taproot pubkeys
    2548         [ #  # ]:           0 :             for (const auto& pk_pair : input.m_tap_bip32_paths) {
    2549                 :           0 :                 const XOnlyPubKey& pubkey = pk_pair.first;
    2550         [ #  # ]:           0 :                 for (unsigned char prefix : {0x02, 0x03}) {
    2551                 :           0 :                     unsigned char b[33] = {prefix};
    2552   [ #  #  #  #  :           0 :                     std::copy(pubkey.begin(), pubkey.end(), b + 1);
                   #  # ]
    2553         [ #  # ]:           0 :                     CPubKey fullpubkey;
    2554         [ #  # ]:           0 :                     fullpubkey.Set(b, b + 33);
    2555         [ #  # ]:           0 :                     pubkeys.push_back(fullpubkey);
    2556                 :           0 :                 }
    2557                 :           0 :             }
    2558                 :             : 
    2559         [ #  # ]:           0 :             for (const auto& pubkey : pubkeys) {
    2560         [ #  # ]:           0 :                 std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
    2561         [ #  # ]:           0 :                 if (pk_keys) {
    2562         [ #  # ]:           0 :                     keys->Merge(std::move(*pk_keys));
    2563                 :           0 :                 }
    2564                 :           0 :             }
    2565                 :           0 :         }
    2566                 :             : 
    2567   [ #  #  #  # ]:           0 :         SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
    2568                 :             : 
    2569         [ #  # ]:           0 :         bool signed_one = PSBTInputSigned(input);
    2570   [ #  #  #  #  :           0 :         if (n_signed && (signed_one || !sign)) {
                   #  # ]
    2571                 :             :             // If sign is false, we assume that we _could_ sign if we get here. This
    2572                 :             :             // will never have false negatives; it is hard to tell under what i
    2573                 :             :             // circumstances it could have false positives.
    2574                 :           0 :             (*n_signed)++;
    2575                 :           0 :         }
    2576      [ #  #  # ]:           0 :     }
    2577                 :             : 
    2578                 :             :     // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
    2579         [ +  + ]:         104 :     for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
    2580                 :          49 :         std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
    2581         [ -  + ]:          49 :         if (!keys) {
    2582                 :          49 :             continue;
    2583                 :             :         }
    2584   [ #  #  #  # ]:           0 :         UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
    2585         [ +  - ]:          49 :     }
    2586                 :             : 
    2587                 :          55 :     return {};
    2588                 :          55 : }
    2589                 :             : 
    2590                 :      369852 : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
    2591                 :             : {
    2592         [ +  - ]:      369852 :     std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
    2593         [ -  + ]:      369852 :     if (provider) {
    2594                 :      369852 :         KeyOriginInfo orig;
    2595         [ +  - ]:      369852 :         CKeyID key_id = GetKeyForDestination(*provider, dest);
    2596   [ +  -  +  + ]:      369852 :         if (provider->GetKeyOrigin(key_id, orig)) {
    2597   [ +  -  +  - ]:      321734 :             LOCK(cs_desc_man);
    2598         [ +  - ]:      321734 :             std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
    2599         [ +  - ]:      321734 :             meta->key_origin = orig;
    2600                 :      321734 :             meta->has_key_origin = true;
    2601                 :      321734 :             meta->nCreateTime = m_wallet_descriptor.creation_time;
    2602                 :      321734 :             return meta;
    2603         [ +  - ]:      321734 :         }
    2604         [ +  + ]:      369852 :     }
    2605                 :       48118 :     return nullptr;
    2606                 :      369852 : }
    2607                 :             : 
    2608                 :     2707418 : uint256 DescriptorScriptPubKeyMan::GetID() const
    2609                 :             : {
    2610                 :     2707418 :     LOCK(cs_desc_man);
    2611                 :     2707418 :     return m_wallet_descriptor.id;
    2612                 :     2707418 : }
    2613                 :             : 
    2614                 :           0 : void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
    2615                 :             : {
    2616                 :           0 :     LOCK(cs_desc_man);
    2617                 :           0 :     std::set<CScript> new_spks;
    2618         [ #  # ]:           0 :     m_wallet_descriptor.cache = cache;
    2619         [ #  # ]:           0 :     for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
    2620                 :           0 :         FlatSigningProvider out_keys;
    2621                 :           0 :         std::vector<CScript> scripts_temp;
    2622   [ #  #  #  # ]:           0 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
    2623         [ #  # ]:           0 :             throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
    2624                 :             :         }
    2625                 :             :         // Add all of the scriptPubKeys to the scriptPubKey set
    2626         [ #  # ]:           0 :         new_spks.insert(scripts_temp.begin(), scripts_temp.end());
    2627         [ #  # ]:           0 :         for (const CScript& script : scripts_temp) {
    2628   [ #  #  #  # ]:           0 :             if (m_map_script_pub_keys.count(script) != 0) {
    2629   [ #  #  #  #  :           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]));
             #  #  #  # ]
    2630                 :             :             }
    2631         [ #  # ]:           0 :             m_map_script_pub_keys[script] = i;
    2632                 :           0 :         }
    2633         [ #  # ]:           0 :         for (const auto& pk_pair : out_keys.pubkeys) {
    2634                 :           0 :             const CPubKey& pubkey = pk_pair.second;
    2635   [ #  #  #  # ]:           0 :             if (m_map_pubkeys.count(pubkey) != 0) {
    2636                 :             :                 // We don't need to give an error here.
    2637                 :             :                 // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
    2638                 :           0 :                 continue;
    2639                 :             :             }
    2640         [ #  # ]:           0 :             m_map_pubkeys[pubkey] = i;
    2641   [ #  #  #  # ]:           0 :         }
    2642                 :           0 :         m_max_cached_index++;
    2643                 :           0 :     }
    2644                 :             :     // Make sure the wallet knows about our new spks
    2645         [ #  # ]:           0 :     m_storage.TopUpCallback(new_spks, this);
    2646                 :           0 : }
    2647                 :             : 
    2648                 :           0 : bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
    2649                 :             : {
    2650                 :           0 :     LOCK(cs_desc_man);
    2651   [ #  #  #  # ]:           0 :     m_map_keys[key_id] = key;
    2652                 :             :     return true;
    2653                 :           0 : }
    2654                 :             : 
    2655                 :           0 : bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
    2656                 :             : {
    2657                 :           0 :     LOCK(cs_desc_man);
    2658         [ #  # ]:           0 :     if (!m_map_keys.empty()) {
    2659                 :           0 :         return false;
    2660                 :             :     }
    2661                 :             : 
    2662   [ #  #  #  # ]:           0 :     m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
    2663                 :           0 :     return true;
    2664                 :           0 : }
    2665                 :             : 
    2666                 :      160046 : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
    2667                 :             : {
    2668                 :      160046 :     LOCK(cs_desc_man);
    2669   [ +  -  +  -  :      160046 :     return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
          +  -  +  -  +  
                      - ]
    2670                 :      160046 : }
    2671                 :             : 
    2672                 :       28925 : void DescriptorScriptPubKeyMan::WriteDescriptor()
    2673                 :             : {
    2674                 :       28925 :     LOCK(cs_desc_man);
    2675   [ +  -  +  - ]:       28925 :     WalletBatch batch(m_storage.GetDatabase());
    2676   [ +  -  +  -  :       28925 :     if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
                   +  - ]
    2677   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
          #  #  #  #  #  
                      # ]
    2678                 :             :     }
    2679                 :       28925 : }
    2680                 :             : 
    2681                 :        3654 : WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
    2682                 :             : {
    2683                 :        3654 :     return m_wallet_descriptor;
    2684                 :             : }
    2685                 :             : 
    2686                 :       15540 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
    2687                 :             : {
    2688                 :       15540 :     return GetScriptPubKeys(0);
    2689                 :             : }
    2690                 :             : 
    2691                 :       15540 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
    2692                 :             : {
    2693                 :       15540 :     LOCK(cs_desc_man);
    2694         [ +  - ]:       15540 :     std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
    2695         [ +  - ]:       15540 :     script_pub_keys.reserve(m_map_script_pub_keys.size());
    2696                 :             : 
    2697         [ +  + ]:      570983 :     for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
    2698   [ -  +  -  + ]:      555443 :         if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
    2699                 :      555443 :     }
    2700                 :       15540 :     return script_pub_keys;
    2701         [ -  + ]:       15540 : }
    2702                 :             : 
    2703                 :        7213 : int32_t DescriptorScriptPubKeyMan::GetEndRange() const
    2704                 :             : {
    2705                 :        7213 :     return m_max_cached_index + 1;
    2706                 :             : }
    2707                 :             : 
    2708                 :        8900 : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
    2709                 :             : {
    2710                 :        8900 :     LOCK(cs_desc_man);
    2711                 :             : 
    2712                 :        8900 :     FlatSigningProvider provider;
    2713         [ +  - ]:        8900 :     provider.keys = GetKeys();
    2714                 :             : 
    2715         [ +  + ]:        8900 :     if (priv) {
    2716                 :             :         // For the private version, always return the master key to avoid
    2717                 :             :         // exposing child private keys. The risk implications of exposing child
    2718                 :             :         // private keys together with the parent xpub may be non-obvious for users.
    2719         [ +  - ]:        8419 :         return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
    2720                 :             :     }
    2721                 :             : 
    2722         [ +  - ]:         481 :     return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
    2723                 :        8900 : }
    2724                 :             : 
    2725                 :           0 : void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
    2726                 :             : {
    2727                 :           0 :     LOCK(cs_desc_man);
    2728   [ #  #  #  #  :           0 :     if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
             #  #  #  # ]
    2729                 :           0 :         return;
    2730                 :             :     }
    2731                 :             : 
    2732                 :             :     // Skip if we have the last hardened xpub cache
    2733   [ #  #  #  # ]:           0 :     if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
    2734                 :           0 :         return;
    2735                 :             :     }
    2736                 :             : 
    2737                 :             :     // Expand the descriptor
    2738                 :           0 :     FlatSigningProvider provider;
    2739         [ #  # ]:           0 :     provider.keys = GetKeys();
    2740                 :           0 :     FlatSigningProvider out_keys;
    2741                 :           0 :     std::vector<CScript> scripts_temp;
    2742                 :           0 :     DescriptorCache temp_cache;
    2743   [ #  #  #  # ]:           0 :     if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
    2744         [ #  # ]:           0 :         throw std::runtime_error("Unable to expand descriptor");
    2745                 :             :     }
    2746                 :             : 
    2747                 :             :     // Cache the last hardened xpubs
    2748         [ #  # ]:           0 :     DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
    2749   [ #  #  #  #  :           0 :     if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
          #  #  #  #  #  
                      # ]
    2750   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
             #  #  #  # ]
    2751                 :             :     }
    2752                 :           0 : }
    2753                 :             : 
    2754                 :          38 : void DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
    2755                 :             : {
    2756                 :          38 :     LOCK(cs_desc_man);
    2757                 :          38 :     std::string error;
    2758   [ +  -  +  - ]:          38 :     if (!CanUpdateToWalletDescriptor(descriptor, error)) {
    2759   [ #  #  #  #  :           0 :         throw std::runtime_error(std::string(__func__) + ": " + error);
          #  #  #  #  #  
                #  #  # ]
    2760                 :             :     }
    2761                 :             : 
    2762                 :          38 :     m_map_pubkeys.clear();
    2763                 :          38 :     m_map_script_pub_keys.clear();
    2764                 :          38 :     m_max_cached_index = -1;
    2765         [ +  - ]:          38 :     m_wallet_descriptor = descriptor;
    2766                 :             : 
    2767         [ +  - ]:          38 :     NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
    2768                 :          38 : }
    2769                 :             : 
    2770                 :         101 : bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
    2771                 :             : {
    2772                 :         101 :     LOCK(cs_desc_man);
    2773   [ +  -  +  + ]:         101 :     if (!HasWalletDescriptor(descriptor)) {
    2774         [ +  - ]:          25 :         error = "can only update matching descriptor";
    2775                 :          25 :         return false;
    2776                 :             :     }
    2777                 :             : 
    2778   [ +  -  -  + ]:          76 :     if (descriptor.range_start > m_wallet_descriptor.range_start ||
    2779                 :          76 :         descriptor.range_end < m_wallet_descriptor.range_end) {
    2780                 :             :         // Use inclusive range for error
    2781   [ #  #  #  # ]:           0 :         error = strprintf("new range must include current range = [%d,%d]",
    2782                 :           0 :                           m_wallet_descriptor.range_start,
    2783                 :           0 :                           m_wallet_descriptor.range_end - 1);
    2784                 :           0 :         return false;
    2785                 :             :     }
    2786                 :             : 
    2787                 :          76 :     return true;
    2788                 :         101 : }
    2789                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1