LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 56.1 % 1636 918
Test Date: 2024-08-28 04:44:32 Functions: 69.2 % 143 99
Branches: 29.9 % 2670 797

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

Generated by: LCOV version 2.0-1