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

Generated by: LCOV version 1.14