LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 4 1773 0.2 %
Date: 2024-01-03 14:57:27 Functions: 0 137 0.0 %
Branches: 1 3026 0.1 %

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

Generated by: LCOV version 1.14