LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 1419 1690 84.0 %
Date: 2021-06-29 14:35:33 Functions: 118 124 95.2 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 549 712 77.1 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2019-2020 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 <key_io.h>
#       6                 :            : #include <logging.h>
#       7                 :            : #include <outputtype.h>
#       8                 :            : #include <script/descriptor.h>
#       9                 :            : #include <script/sign.h>
#      10                 :            : #include <util/bip32.h>
#      11                 :            : #include <util/strencodings.h>
#      12                 :            : #include <util/string.h>
#      13                 :            : #include <util/system.h>
#      14                 :            : #include <util/time.h>
#      15                 :            : #include <util/translation.h>
#      16                 :            : #include <external_signer.h>
#      17                 :            : #include <wallet/scriptpubkeyman.h>
#      18                 :            : 
#      19                 :            : #include <optional>
#      20                 :            : 
#      21                 :            : //! 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.
#      22                 :            : const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
#      23                 :            : 
#      24                 :            : bool LegacyScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error)
#      25                 :       9111 : {
#      26                 :       9111 :     LOCK(cs_KeyStore);
#      27                 :       9111 :     error.clear();
#      28                 :            : 
#      29                 :            :     // Generate a new key that is added to wallet
#      30                 :       9111 :     CPubKey new_key;
#      31         [ +  + ]:       9111 :     if (!GetKeyFromPool(new_key, type)) {
#      32                 :          4 :         error = _("Error: Keypool ran out, please call keypoolrefill first").translated;
#      33                 :          4 :         return false;
#      34                 :          4 :     }
#      35                 :       9107 :     LearnRelatedScripts(new_key, type);
#      36                 :       9107 :     dest = GetDestinationForKey(new_key, type);
#      37                 :       9107 :     return true;
#      38                 :       9107 : }
#      39                 :            : 
#      40                 :            : typedef std::vector<unsigned char> valtype;
#      41                 :            : 
#      42                 :            : namespace {
#      43                 :            : 
#      44                 :            : /**
#      45                 :            :  * This is an enum that tracks the execution context of a script, similar to
#      46                 :            :  * SigVersion in script/interpreter. It is separate however because we want to
#      47                 :            :  * distinguish between top-level scriptPubKey execution and P2SH redeemScript
#      48                 :            :  * execution (a distinction that has no impact on consensus rules).
#      49                 :            :  */
#      50                 :            : enum class IsMineSigVersion
#      51                 :            : {
#      52                 :            :     TOP = 0,        //!< scriptPubKey execution
#      53                 :            :     P2SH = 1,       //!< P2SH redeemScript
#      54                 :            :     WITNESS_V0 = 2, //!< P2WSH witness script execution
#      55                 :            : };
#      56                 :            : 
#      57                 :            : /**
#      58                 :            :  * This is an internal representation of isminetype + invalidity.
#      59                 :            :  * Its order is significant, as we return the max of all explored
#      60                 :            :  * possibilities.
#      61                 :            :  */
#      62                 :            : enum class IsMineResult
#      63                 :            : {
#      64                 :            :     NO = 0,         //!< Not ours
#      65                 :            :     WATCH_ONLY = 1, //!< Included in watch-only balance
#      66                 :            :     SPENDABLE = 2,  //!< Included in all balances
#      67                 :            :     INVALID = 3,    //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
#      68                 :            : };
#      69                 :            : 
#      70                 :            : bool PermitsUncompressed(IsMineSigVersion sigversion)
#      71                 :    1238618 : {
#      72 [ +  + ][ +  + ]:    1238618 :     return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
#      73                 :    1238618 : }
#      74                 :            : 
#      75                 :            : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyScriptPubKeyMan& keystore)
#      76                 :       3243 : {
#      77         [ +  + ]:       5188 :     for (const valtype& pubkey : pubkeys) {
#      78                 :       5188 :         CKeyID keyID = CPubKey(pubkey).GetID();
#      79         [ +  + ]:       5188 :         if (!keystore.HaveKey(keyID)) return false;
#      80                 :       5188 :     }
#      81                 :       3243 :     return true;
#      82                 :       3243 : }
#      83                 :            : 
#      84                 :            : //! Recursively solve script and return spendable/watchonly/invalid status.
#      85                 :            : //!
#      86                 :            : //! @param keystore            legacy key and script store
#      87                 :            : //! @param scriptPubKey        script to solve
#      88                 :            : //! @param sigversion          script type (top-level / redeemscript / witnessscript)
#      89                 :            : //! @param recurse_scripthash  whether to recurse into nested p2sh and p2wsh
#      90                 :            : //!                            scripts or simply treat any script that has been
#      91                 :            : //!                            stored in the keystore as spendable
#      92                 :            : IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
#      93                 :    2451845 : {
#      94                 :    2451845 :     IsMineResult ret = IsMineResult::NO;
#      95                 :            : 
#      96                 :    2451845 :     std::vector<valtype> vSolutions;
#      97                 :    2451845 :     TxoutType whichType = Solver(scriptPubKey, vSolutions);
#      98                 :            : 
#      99                 :    2451845 :     CKeyID keyID;
#     100         [ -  + ]:    2451845 :     switch (whichType) {
#     101         [ +  + ]:     121346 :     case TxoutType::NONSTANDARD:
#     102         [ +  + ]:     258611 :     case TxoutType::NULL_DATA:
#     103         [ +  + ]:     259215 :     case TxoutType::WITNESS_UNKNOWN:
#     104         [ +  + ]:     268655 :     case TxoutType::WITNESS_V1_TAPROOT:
#     105                 :     268655 :         break;
#     106         [ +  + ]:     259215 :     case TxoutType::PUBKEY:
#     107                 :      15147 :         keyID = CPubKey(vSolutions[0]).GetID();
#     108 [ +  + ][ +  + ]:      15147 :         if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
#     109                 :        352 :             return IsMineResult::INVALID;
#     110                 :        352 :         }
#     111         [ +  + ]:      14795 :         if (keystore.HaveKey(keyID)) {
#     112                 :       9312 :             ret = std::max(ret, IsMineResult::SPENDABLE);
#     113                 :       9312 :         }
#     114                 :      14795 :         break;
#     115         [ +  + ]:     783990 :     case TxoutType::WITNESS_V0_KEYHASH:
#     116                 :     783990 :     {
#     117         [ +  + ]:     783990 :         if (sigversion == IsMineSigVersion::WITNESS_V0) {
#     118                 :            :             // P2WPKH inside P2WSH is invalid.
#     119                 :          1 :             return IsMineResult::INVALID;
#     120                 :          1 :         }
#     121 [ +  + ][ +  + ]:     783989 :         if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
#                 [ +  + ]
#     122                 :            :             // We do not support bare witness outputs unless the P2SH version of it would be
#     123                 :            :             // acceptable as well. This protects against matching before segwit activates.
#     124                 :            :             // This also applies to the P2WSH case.
#     125                 :     233475 :             break;
#     126                 :     233475 :         }
#     127                 :     550514 :         ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
#     128                 :     550514 :         break;
#     129                 :     550514 :     }
#     130         [ +  + ]:    1219699 :     case TxoutType::PUBKEYHASH:
#     131                 :    1219699 :         keyID = CKeyID(uint160(vSolutions[0]));
#     132         [ +  + ]:    1219699 :         if (!PermitsUncompressed(sigversion)) {
#     133                 :     551471 :             CPubKey pubkey;
#     134 [ +  + ][ +  + ]:     551471 :             if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
#     135                 :        705 :                 return IsMineResult::INVALID;
#     136                 :        705 :             }
#     137                 :    1218994 :         }
#     138         [ +  + ]:    1218994 :         if (keystore.HaveKey(keyID)) {
#     139                 :    1132321 :             ret = std::max(ret, IsMineResult::SPENDABLE);
#     140                 :    1132321 :         }
#     141                 :    1218994 :         break;
#     142         [ +  + ]:    1218994 :     case TxoutType::SCRIPTHASH:
#     143                 :     129228 :     {
#     144         [ +  + ]:     129228 :         if (sigversion != IsMineSigVersion::TOP) {
#     145                 :            :             // P2SH inside P2WSH or P2SH is invalid.
#     146                 :          2 :             return IsMineResult::INVALID;
#     147                 :          2 :         }
#     148                 :     129226 :         CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
#     149                 :     129226 :         CScript subscript;
#     150         [ +  + ]:     129226 :         if (keystore.GetCScript(scriptID, subscript)) {
#     151         [ +  + ]:      17887 :             ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
#     152                 :      17887 :         }
#     153                 :     129226 :         break;
#     154                 :     129226 :     }
#     155         [ +  + ]:     129226 :     case TxoutType::WITNESS_V0_SCRIPTHASH:
#     156                 :      30416 :     {
#     157         [ +  + ]:      30416 :         if (sigversion == IsMineSigVersion::WITNESS_V0) {
#     158                 :            :             // P2WSH inside P2WSH is invalid.
#     159                 :          1 :             return IsMineResult::INVALID;
#     160                 :          1 :         }
#     161 [ +  + ][ +  + ]:      30415 :         if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
#                 [ +  + ]
#     162                 :      23702 :             break;
#     163                 :      23702 :         }
#     164                 :       6713 :         uint160 hash;
#     165                 :       6713 :         CRIPEMD160().Write(vSolutions[0].data(), vSolutions[0].size()).Finalize(hash.begin());
#     166                 :       6713 :         CScriptID scriptID = CScriptID(hash);
#     167                 :       6713 :         CScript subscript;
#     168         [ +  + ]:       6713 :         if (keystore.GetCScript(scriptID, subscript)) {
#     169         [ +  + ]:       6692 :             ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
#     170                 :       6692 :         }
#     171                 :       6713 :         break;
#     172                 :       6713 :     }
#     173                 :            : 
#     174         [ +  + ]:       6713 :     case TxoutType::MULTISIG:
#     175                 :       4710 :     {
#     176                 :            :         // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
#     177         [ +  + ]:       4710 :         if (sigversion == IsMineSigVersion::TOP) {
#     178                 :        938 :             break;
#     179                 :        938 :         }
#     180                 :            : 
#     181                 :            :         // Only consider transactions "mine" if we own ALL the
#     182                 :            :         // keys involved. Multi-signature transactions that are
#     183                 :            :         // partially owned (somebody else has a key that can spend
#     184                 :            :         // them) enable spend-out-from-under-you attacks, especially
#     185                 :            :         // in shared-wallet situations.
#     186                 :       3772 :         std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
#     187         [ +  + ]:       3772 :         if (!PermitsUncompressed(sigversion)) {
#     188         [ +  + ]:       6642 :             for (size_t i = 0; i < keys.size(); i++) {
#     189         [ +  + ]:       4394 :                 if (keys[i].size() != 33) {
#     190                 :        529 :                     return IsMineResult::INVALID;
#     191                 :        529 :                 }
#     192                 :       4394 :             }
#     193                 :       2777 :         }
#     194         [ +  + ]:       3772 :         if (HaveKeys(keys, keystore)) {
#     195                 :       2482 :             ret = std::max(ret, IsMineResult::SPENDABLE);
#     196                 :       2482 :         }
#     197                 :       3243 :         break;
#     198                 :    2450255 :     }
#     199                 :    2450255 :     } // no default case, so the compiler can warn about missing cases
#     200                 :            : 
#     201 [ +  + ][ +  + ]:    2450255 :     if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
#     202                 :      12590 :         ret = std::max(ret, IsMineResult::WATCH_ONLY);
#     203                 :      12590 :     }
#     204                 :    2450255 :     return ret;
#     205                 :    2450255 : }
#     206                 :            : 
#     207                 :            : } // namespace
#     208                 :            : 
#     209                 :            : isminetype LegacyScriptPubKeyMan::IsMine(const CScript& script) const
#     210                 :    1104272 : {
#     211         [ -  + ]:    1104272 :     switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
#     212         [ +  + ]:       1590 :     case IsMineResult::INVALID:
#     213         [ +  + ]:     609749 :     case IsMineResult::NO:
#     214                 :     609749 :         return ISMINE_NO;
#     215         [ +  + ]:      11104 :     case IsMineResult::WATCH_ONLY:
#     216                 :      11104 :         return ISMINE_WATCH_ONLY;
#     217         [ +  + ]:     483419 :     case IsMineResult::SPENDABLE:
#     218                 :     483419 :         return ISMINE_SPENDABLE;
#     219                 :          0 :     }
#     220                 :          0 :     assert(false);
#     221                 :          0 : }
#     222                 :            : 
#     223                 :            : bool LegacyScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
#     224                 :         49 : {
#     225                 :         49 :     {
#     226                 :         49 :         LOCK(cs_KeyStore);
#     227                 :         49 :         assert(mapKeys.empty());
#     228                 :            : 
#     229                 :         49 :         bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
#     230                 :         49 :         bool keyFail = false;
#     231                 :         49 :         CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
#     232                 :         49 :         WalletBatch batch(m_storage.GetDatabase());
#     233         [ +  + ]:        120 :         for (; mi != mapCryptedKeys.end(); ++mi)
#     234                 :        105 :         {
#     235                 :        105 :             const CPubKey &vchPubKey = (*mi).second.first;
#     236                 :        105 :             const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
#     237                 :        105 :             CKey key;
#     238         [ -  + ]:        105 :             if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
#     239                 :          0 :             {
#     240                 :          0 :                 keyFail = true;
#     241                 :          0 :                 break;
#     242                 :          0 :             }
#     243                 :        105 :             keyPass = true;
#     244         [ +  + ]:        105 :             if (fDecryptionThoroughlyChecked)
#     245                 :         34 :                 break;
#     246                 :         71 :             else {
#     247                 :            :                 // Rewrite these encrypted keys with checksums
#     248                 :         71 :                 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
#     249                 :         71 :             }
#     250                 :        105 :         }
#     251 [ +  - ][ -  + ]:         49 :         if (keyPass && keyFail)
#     252                 :          0 :         {
#     253                 :          0 :             LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
#     254                 :          0 :             throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
#     255                 :          0 :         }
#     256 [ -  + ][ -  + ]:         49 :         if (keyFail || (!keyPass && !accept_no_keys))
#                 [ #  # ]
#     257                 :          0 :             return false;
#     258                 :         49 :         fDecryptionThoroughlyChecked = true;
#     259                 :         49 :     }
#     260                 :         49 :     return true;
#     261                 :         49 : }
#     262                 :            : 
#     263                 :            : bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
#     264                 :         16 : {
#     265                 :         16 :     LOCK(cs_KeyStore);
#     266                 :         16 :     encrypted_batch = batch;
#     267         [ -  + ]:         16 :     if (!mapCryptedKeys.empty()) {
#     268                 :          0 :         encrypted_batch = nullptr;
#     269                 :          0 :         return false;
#     270                 :          0 :     }
#     271                 :            : 
#     272                 :         16 :     KeyMap keys_to_encrypt;
#     273                 :         16 :     keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
#     274         [ +  + ]:         16 :     for (const KeyMap::value_type& mKey : keys_to_encrypt)
#     275                 :        267 :     {
#     276                 :        267 :         const CKey &key = mKey.second;
#     277                 :        267 :         CPubKey vchPubKey = key.GetPubKey();
#     278                 :        267 :         CKeyingMaterial vchSecret(key.begin(), key.end());
#     279                 :        267 :         std::vector<unsigned char> vchCryptedSecret;
#     280         [ -  + ]:        267 :         if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
#     281                 :          0 :             encrypted_batch = nullptr;
#     282                 :          0 :             return false;
#     283                 :          0 :         }
#     284         [ -  + ]:        267 :         if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
#     285                 :          0 :             encrypted_batch = nullptr;
#     286                 :          0 :             return false;
#     287                 :          0 :         }
#     288                 :        267 :     }
#     289                 :         16 :     encrypted_batch = nullptr;
#     290                 :         16 :     return true;
#     291                 :         16 : }
#     292                 :            : 
#     293                 :            : bool LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool)
#     294                 :       2976 : {
#     295                 :       2976 :     LOCK(cs_KeyStore);
#     296         [ +  + ]:       2976 :     if (!CanGetAddresses(internal)) {
#     297                 :         12 :         return false;
#     298                 :         12 :     }
#     299                 :            : 
#     300         [ +  + ]:       2964 :     if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
#     301                 :          4 :         return false;
#     302                 :          4 :     }
#     303                 :       2960 :     address = GetDestinationForKey(keypool.vchPubKey, type);
#     304                 :       2960 :     return true;
#     305                 :       2960 : }
#     306                 :            : 
#     307                 :            : bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
#     308                 :         10 : {
#     309                 :         10 :     LOCK(cs_KeyStore);
#     310                 :            : 
#     311         [ -  + ]:         10 :     if (m_storage.IsLocked()) return false;
#     312                 :            : 
#     313                 :         10 :     auto it = m_inactive_hd_chains.find(seed_id);
#     314         [ -  + ]:         10 :     if (it == m_inactive_hd_chains.end()) {
#     315                 :          0 :         return false;
#     316                 :          0 :     }
#     317                 :            : 
#     318                 :         10 :     CHDChain& chain = it->second;
#     319                 :            : 
#     320                 :            :     // Top up key pool
#     321                 :         10 :     int64_t target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
#     322                 :            : 
#     323                 :            :     // "size" of the keypools. Not really the size, actually the difference between index and the chain counter
#     324                 :            :     // Since chain counter is 1 based and index is 0 based, one of them needs to be offset by 1.
#     325         [ +  + ]:         10 :     int64_t kp_size = (internal ? chain.nInternalChainCounter : chain.nExternalChainCounter) - (index + 1);
#     326                 :            : 
#     327                 :            :     // make sure the keypool fits the user-selected target (-keypool)
#     328                 :         10 :     int64_t missing = std::max(target_size - kp_size, (int64_t) 0);
#     329                 :            : 
#     330         [ +  + ]:         10 :     if (missing > 0) {
#     331                 :          4 :         WalletBatch batch(m_storage.GetDatabase());
#     332         [ +  + ]:         16 :         for (int64_t i = missing; i > 0; --i) {
#     333                 :         12 :             GenerateNewKey(batch, chain, internal);
#     334                 :         12 :         }
#     335         [ +  + ]:          4 :         if (internal) {
#     336                 :          1 :             WalletLogPrintf("inactive seed with id %s added %d internal keys\n", HexStr(seed_id), missing);
#     337                 :          3 :         } else {
#     338                 :          3 :             WalletLogPrintf("inactive seed with id %s added %d keys\n", HexStr(seed_id), missing);
#     339                 :          3 :         }
#     340                 :          4 :     }
#     341                 :         10 :     return true;
#     342                 :         10 : }
#     343                 :            : 
#     344                 :            : void LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
#     345                 :     188186 : {
#     346                 :     188186 :     LOCK(cs_KeyStore);
#     347                 :            :     // extract addresses and check if they match with an unused keypool key
#     348         [ +  + ]:     188186 :     for (const auto& keyid : GetAffectedKeys(script, *this)) {
#     349                 :      77596 :         std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
#     350         [ +  + ]:      77596 :         if (mi != m_pool_key_to_index.end()) {
#     351                 :         37 :             WalletLogPrintf("%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
#     352                 :         37 :             MarkReserveKeysAsUsed(mi->second);
#     353                 :            : 
#     354         [ +  + ]:         37 :             if (!TopUp()) {
#     355                 :          1 :                 WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
#     356                 :          1 :             }
#     357                 :         37 :         }
#     358                 :            : 
#     359                 :            :         // 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.
#     360                 :            :         // If so, TopUp the inactive hd chain
#     361                 :      77596 :         auto it = mapKeyMetadata.find(keyid);
#     362         [ +  + ]:      77596 :         if (it != mapKeyMetadata.end()){
#     363                 :      77594 :             CKeyMetadata meta = it->second;
#     364 [ +  + ][ +  + ]:      77594 :             if (!meta.hd_seed_id.IsNull() && meta.hd_seed_id != m_hd_chain.seed_id) {
#     365                 :         10 :                 bool internal = (meta.key_origin.path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
#     366                 :         10 :                 int64_t index = meta.key_origin.path[2] & ~BIP32_HARDENED_KEY_LIMIT;
#     367                 :            : 
#     368         [ -  + ]:         10 :                 if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
#     369                 :          0 :                     WalletLogPrintf("%s: Adding inactive seed keys failed\n", __func__);
#     370                 :          0 :                 }
#     371                 :         10 :             }
#     372                 :      77594 :         }
#     373                 :      77596 :     }
#     374                 :     188186 : }
#     375                 :            : 
#     376                 :            : void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
#     377                 :        113 : {
#     378                 :        113 :     LOCK(cs_KeyStore);
#     379 [ -  + ][ -  + ]:        113 :     if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
#     380                 :          0 :         return;
#     381                 :          0 :     }
#     382                 :            : 
#     383                 :        113 :     std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
#     384         [ +  + ]:       6801 :     for (auto& meta_pair : mapKeyMetadata) {
#     385                 :       6801 :         CKeyMetadata& meta = meta_pair.second;
#     386 [ +  + ][ +  + ]:       6801 :         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
#                 [ -  + ]
#     387                 :          0 :             CKey key;
#     388                 :          0 :             GetKey(meta.hd_seed_id, key);
#     389                 :          0 :             CExtKey masterKey;
#     390                 :          0 :             masterKey.SetSeed(key.begin(), key.size());
#     391                 :            :             // Add to map
#     392                 :          0 :             CKeyID master_id = masterKey.key.GetPubKey().GetID();
#     393                 :          0 :             std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
#     394         [ #  # ]:          0 :             if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
#     395                 :          0 :                 throw std::runtime_error("Invalid stored hdKeypath");
#     396                 :          0 :             }
#     397                 :          0 :             meta.has_key_origin = true;
#     398         [ #  # ]:          0 :             if (meta.nVersion < CKeyMetadata::VERSION_WITH_KEY_ORIGIN) {
#     399                 :          0 :                 meta.nVersion = CKeyMetadata::VERSION_WITH_KEY_ORIGIN;
#     400                 :          0 :             }
#     401                 :            : 
#     402                 :            :             // Write meta to wallet
#     403                 :          0 :             CPubKey pubkey;
#     404         [ #  # ]:          0 :             if (GetPubKey(meta_pair.first, pubkey)) {
#     405                 :          0 :                 batch->WriteKeyMetadata(meta, pubkey, true);
#     406                 :          0 :             }
#     407                 :          0 :         }
#     408                 :       6801 :     }
#     409                 :        113 : }
#     410                 :            : 
#     411                 :            : bool LegacyScriptPubKeyMan::SetupGeneration(bool force)
#     412                 :        242 : {
#     413 [ +  + ][ -  + ]:        242 :     if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
#                 [ -  + ]
#     414                 :          0 :         return false;
#     415                 :          0 :     }
#     416                 :            : 
#     417                 :        242 :     SetHDSeed(GenerateNewSeed());
#     418         [ -  + ]:        242 :     if (!NewKeyPool()) {
#     419                 :          0 :         return false;
#     420                 :          0 :     }
#     421                 :        242 :     return true;
#     422                 :        242 : }
#     423                 :            : 
#     424                 :            : bool LegacyScriptPubKeyMan::IsHDEnabled() const
#     425                 :      73445 : {
#     426                 :      73445 :     return !m_hd_chain.seed_id.IsNull();
#     427                 :      73445 : }
#     428                 :            : 
#     429                 :            : bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
#     430                 :      21351 : {
#     431                 :      21351 :     LOCK(cs_KeyStore);
#     432                 :            :     // Check if the keypool has keys
#     433                 :      21351 :     bool keypool_has_keys;
#     434 [ +  + ][ +  + ]:      21351 :     if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
#     435                 :       3077 :         keypool_has_keys = setInternalKeyPool.size() > 0;
#     436                 :      18274 :     } else {
#     437                 :      18274 :         keypool_has_keys = KeypoolCountExternalKeys() > 0;
#     438                 :      18274 :     }
#     439                 :            :     // If the keypool doesn't have keys, check if we can generate them
#     440         [ +  + ]:      21351 :     if (!keypool_has_keys) {
#     441                 :       8500 :         return CanGenerateKeys();
#     442                 :       8500 :     }
#     443                 :      12851 :     return keypool_has_keys;
#     444                 :      12851 : }
#     445                 :            : 
#     446                 :            : bool LegacyScriptPubKeyMan::Upgrade(int prev_version, int new_version, bilingual_str& error)
#     447                 :          0 : {
#     448                 :          0 :     LOCK(cs_KeyStore);
#     449                 :          0 :     bool hd_upgrade = false;
#     450                 :          0 :     bool split_upgrade = false;
#     451 [ #  # ][ #  # ]:          0 :     if (IsFeatureSupported(new_version, FEATURE_HD) && !IsHDEnabled()) {
#     452                 :          0 :         WalletLogPrintf("Upgrading wallet to HD\n");
#     453                 :          0 :         m_storage.SetMinVersion(FEATURE_HD);
#     454                 :            : 
#     455                 :            :         // generate a new master key
#     456                 :          0 :         CPubKey masterPubKey = GenerateNewSeed();
#     457                 :          0 :         SetHDSeed(masterPubKey);
#     458                 :          0 :         hd_upgrade = true;
#     459                 :          0 :     }
#     460                 :            :     // Upgrade to HD chain split if necessary
#     461 [ #  # ][ #  # ]:          0 :     if (!IsFeatureSupported(prev_version, FEATURE_HD_SPLIT) && IsFeatureSupported(new_version, FEATURE_HD_SPLIT)) {
#     462                 :          0 :         WalletLogPrintf("Upgrading wallet to use HD chain split\n");
#     463                 :          0 :         m_storage.SetMinVersion(FEATURE_PRE_SPLIT_KEYPOOL);
#     464                 :          0 :         split_upgrade = FEATURE_HD_SPLIT > prev_version;
#     465                 :            :         // Upgrade the HDChain
#     466         [ #  # ]:          0 :         if (m_hd_chain.nVersion < CHDChain::VERSION_HD_CHAIN_SPLIT) {
#     467                 :          0 :             m_hd_chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
#     468         [ #  # ]:          0 :             if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(m_hd_chain)) {
#     469                 :          0 :                 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
#     470                 :          0 :             }
#     471                 :          0 :         }
#     472                 :          0 :     }
#     473                 :            :     // Mark all keys currently in the keypool as pre-split
#     474         [ #  # ]:          0 :     if (split_upgrade) {
#     475                 :          0 :         MarkPreSplitKeys();
#     476                 :          0 :     }
#     477                 :            :     // Regenerate the keypool if upgraded to HD
#     478         [ #  # ]:          0 :     if (hd_upgrade) {
#     479         [ #  # ]:          0 :         if (!TopUp()) {
#     480                 :          0 :             error = _("Unable to generate keys");
#     481                 :          0 :             return false;
#     482                 :          0 :         }
#     483                 :          0 :     }
#     484                 :          0 :     return true;
#     485                 :          0 : }
#     486                 :            : 
#     487                 :            : bool LegacyScriptPubKeyMan::HavePrivateKeys() const
#     488                 :         13 : {
#     489                 :         13 :     LOCK(cs_KeyStore);
#     490 [ -  + ][ -  + ]:         13 :     return !mapKeys.empty() || !mapCryptedKeys.empty();
#     491                 :         13 : }
#     492                 :            : 
#     493                 :            : void LegacyScriptPubKeyMan::RewriteDB()
#     494                 :          0 : {
#     495                 :          0 :     LOCK(cs_KeyStore);
#     496                 :          0 :     setInternalKeyPool.clear();
#     497                 :          0 :     setExternalKeyPool.clear();
#     498                 :          0 :     m_pool_key_to_index.clear();
#     499                 :            :     // Note: can't top-up keypool here, because wallet is locked.
#     500                 :            :     // User will be prompted to unlock wallet the next operation
#     501                 :            :     // that requires a new key.
#     502                 :          0 : }
#     503                 :            : 
#     504                 :       1236 : static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
#     505         [ +  + ]:       1236 :     if (setKeyPool.empty()) {
#     506                 :        296 :         return GetTime();
#     507                 :        296 :     }
#     508                 :            : 
#     509                 :        940 :     CKeyPool keypool;
#     510                 :        940 :     int64_t nIndex = *(setKeyPool.begin());
#     511         [ -  + ]:        940 :     if (!batch.ReadPool(nIndex, keypool)) {
#     512                 :          0 :         throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
#     513                 :          0 :     }
#     514                 :        940 :     assert(keypool.vchPubKey.IsValid());
#     515                 :        940 :     return keypool.nTime;
#     516                 :        940 : }
#     517                 :            : 
#     518                 :            : int64_t LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
#     519                 :        658 : {
#     520                 :        658 :     LOCK(cs_KeyStore);
#     521                 :            : 
#     522                 :        658 :     WalletBatch batch(m_storage.GetDatabase());
#     523                 :            : 
#     524                 :            :     // load oldest key from keypool, get time and return
#     525                 :        658 :     int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
#     526 [ +  + ][ +  - ]:        658 :     if (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
#     527                 :        578 :         oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
#     528         [ -  + ]:        578 :         if (!set_pre_split_keypool.empty()) {
#     529                 :          0 :             oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
#     530                 :          0 :         }
#     531                 :        578 :     }
#     532                 :            : 
#     533                 :        658 :     return oldestKey;
#     534                 :        658 : }
#     535                 :            : 
#     536                 :            : size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
#     537                 :      18932 : {
#     538                 :      18932 :     LOCK(cs_KeyStore);
#     539                 :      18932 :     return setExternalKeyPool.size() + set_pre_split_keypool.size();
#     540                 :      18932 : }
#     541                 :            : 
#     542                 :            : unsigned int LegacyScriptPubKeyMan::GetKeyPoolSize() const
#     543                 :       1153 : {
#     544                 :       1153 :     LOCK(cs_KeyStore);
#     545                 :       1153 :     return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
#     546                 :       1153 : }
#     547                 :            : 
#     548                 :            : int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
#     549                 :         62 : {
#     550                 :         62 :     LOCK(cs_KeyStore);
#     551                 :         62 :     return nTimeFirstKey;
#     552                 :         62 : }
#     553                 :            : 
#     554                 :            : std::unique_ptr<SigningProvider> LegacyScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
#     555                 :     671148 : {
#     556                 :     671148 :     return std::make_unique<LegacySigningProvider>(*this);
#     557                 :     671148 : }
#     558                 :            : 
#     559                 :            : bool LegacyScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
#     560                 :     783009 : {
#     561                 :     783009 :     IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
#     562 [ +  + ][ +  + ]:     783009 :     if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
#     563                 :            :         // If ismine, it means we recognize keys or script ids in the script, or
#     564                 :            :         // are watching the script itself, and we can at least provide metadata
#     565                 :            :         // or solving information, even if not able to sign fully.
#     566                 :     672711 :         return true;
#     567                 :     672711 :     } else {
#     568                 :            :         // If, given the stuff in sigdata, we could make a valid sigature, then we can provide for this script
#     569                 :     110298 :         ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
#     570         [ -  + ]:     110298 :         if (!sigdata.signatures.empty()) {
#     571                 :            :             // If we could make signatures, make sure we have a private key to actually make a signature
#     572                 :          0 :             bool has_privkeys = false;
#     573         [ #  # ]:          0 :             for (const auto& key_sig_pair : sigdata.signatures) {
#     574                 :          0 :                 has_privkeys |= HaveKey(key_sig_pair.first);
#     575                 :          0 :             }
#     576                 :          0 :             return has_privkeys;
#     577                 :          0 :         }
#     578                 :     110298 :         return false;
#     579                 :     110298 :     }
#     580                 :     783009 : }
#     581                 :            : 
#     582                 :            : bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
#     583                 :       3788 : {
#     584                 :       3788 :     return ::SignTransaction(tx, this, coins, sighash, input_errors);
#     585                 :       3788 : }
#     586                 :            : 
#     587                 :            : SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
#     588                 :          8 : {
#     589                 :          8 :     CKey key;
#     590         [ -  + ]:          8 :     if (!GetKey(ToKeyID(pkhash), key)) {
#     591                 :          0 :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
#     592                 :          0 :     }
#     593                 :            : 
#     594         [ +  - ]:          8 :     if (MessageSign(key, message, str_sig)) {
#     595                 :          8 :         return SigningResult::OK;
#     596                 :          8 :     }
#     597                 :          0 :     return SigningResult::SIGNING_FAILED;
#     598                 :          0 : }
#     599                 :            : 
#     600                 :            : TransactionError LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, int sighash_type, bool sign, bool bip32derivs, int* n_signed) const
#     601                 :        237 : {
#     602         [ +  + ]:        237 :     if (n_signed) {
#     603                 :        236 :         *n_signed = 0;
#     604                 :        236 :     }
#     605         [ +  + ]:        544 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
#     606                 :        309 :         const CTxIn& txin = psbtx.tx->vin[i];
#     607                 :        309 :         PSBTInput& input = psbtx.inputs.at(i);
#     608                 :            : 
#     609         [ +  + ]:        309 :         if (PSBTInputSigned(input)) {
#     610                 :         17 :             continue;
#     611                 :         17 :         }
#     612                 :            : 
#     613                 :            :         // Get the Sighash type
#     614 [ +  + ][ +  + ]:        292 :         if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
#                 [ -  + ]
#     615                 :          0 :             return TransactionError::SIGHASH_MISMATCH;
#     616                 :          0 :         }
#     617                 :            : 
#     618                 :            :         // Check non_witness_utxo has specified prevout
#     619         [ +  + ]:        292 :         if (input.non_witness_utxo) {
#     620         [ +  + ]:        278 :             if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
#     621                 :          2 :                 return TransactionError::MISSING_INPUTS;
#     622                 :          2 :             }
#     623         [ +  + ]:         14 :         } else if (input.witness_utxo.IsNull()) {
#     624                 :            :             // There's no UTXO so we can just skip this now
#     625                 :          7 :             continue;
#     626                 :          7 :         }
#     627                 :        283 :         SignatureData sigdata;
#     628                 :        283 :         input.FillSignatureData(sigdata);
#     629                 :        283 :         SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, sighash_type);
#     630                 :            : 
#     631                 :        283 :         bool signed_one = PSBTInputSigned(input);
#     632 [ +  - ][ +  + ]:        283 :         if (n_signed && (signed_one || !sign)) {
#                 [ +  + ]
#     633                 :            :             // If sign is false, we assume that we _could_ sign if we get here. This
#     634                 :            :             // will never have false negatives; it is hard to tell under what i
#     635                 :            :             // circumstances it could have false positives.
#     636                 :        257 :             (*n_signed)++;
#     637                 :        257 :         }
#     638                 :        283 :     }
#     639                 :            : 
#     640                 :            :     // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
#     641         [ +  + ]:        593 :     for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
#     642                 :        358 :         UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
#     643                 :        358 :     }
#     644                 :            : 
#     645                 :        235 :     return TransactionError::OK;
#     646                 :        237 : }
#     647                 :            : 
#     648                 :            : std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
#     649                 :        777 : {
#     650                 :        777 :     LOCK(cs_KeyStore);
#     651                 :            : 
#     652                 :        777 :     CKeyID key_id = GetKeyForDestination(*this, dest);
#     653         [ +  + ]:        777 :     if (!key_id.IsNull()) {
#     654                 :        645 :         auto it = mapKeyMetadata.find(key_id);
#     655         [ +  + ]:        645 :         if (it != mapKeyMetadata.end()) {
#     656                 :        631 :             return std::make_unique<CKeyMetadata>(it->second);
#     657                 :        631 :         }
#     658                 :        146 :     }
#     659                 :            : 
#     660                 :        146 :     CScript scriptPubKey = GetScriptForDestination(dest);
#     661                 :        146 :     auto it = m_script_metadata.find(CScriptID(scriptPubKey));
#     662         [ +  + ]:        146 :     if (it != m_script_metadata.end()) {
#     663                 :         21 :         return std::make_unique<CKeyMetadata>(it->second);
#     664                 :         21 :     }
#     665                 :            : 
#     666                 :        125 :     return nullptr;
#     667                 :        125 : }
#     668                 :            : 
#     669                 :            : uint256 LegacyScriptPubKeyMan::GetID() const
#     670                 :        528 : {
#     671                 :        528 :     return uint256::ONE;
#     672                 :        528 : }
#     673                 :            : 
#     674                 :            : /**
#     675                 :            :  * Update wallet first key creation time. This should be called whenever keys
#     676                 :            :  * are added to the wallet, with the oldest key creation time.
#     677                 :            :  */
#     678                 :            : void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
#     679                 :      39292 : {
#     680                 :      39292 :     AssertLockHeld(cs_KeyStore);
#     681         [ +  + ]:      39292 :     if (nCreateTime <= 1) {
#     682                 :            :         // Cannot determine birthday information, so set the wallet birthday to
#     683                 :            :         // the beginning of time.
#     684                 :        730 :         nTimeFirstKey = 1;
#     685 [ +  + ][ +  + ]:      38562 :     } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
#     686                 :        471 :         nTimeFirstKey = nCreateTime;
#     687                 :        471 :     }
#     688                 :      39292 : }
#     689                 :            : 
#     690                 :            : bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
#     691                 :      10575 : {
#     692                 :      10575 :     return AddKeyPubKeyInner(key, pubkey);
#     693                 :      10575 : }
#     694                 :            : 
#     695                 :            : bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
#     696                 :        291 : {
#     697                 :        291 :     LOCK(cs_KeyStore);
#     698                 :        291 :     WalletBatch batch(m_storage.GetDatabase());
#     699                 :        291 :     return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
#     700                 :        291 : }
#     701                 :            : 
#     702                 :            : bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
#     703                 :      27680 : {
#     704                 :      27680 :     AssertLockHeld(cs_KeyStore);
#     705                 :            : 
#     706                 :            :     // Make sure we aren't adding private keys to private key disabled wallets
#     707                 :      27680 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
#     708                 :            : 
#     709                 :            :     // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
#     710                 :            :     // which is overridden below.  To avoid flushes, the database handle is
#     711                 :            :     // tunneled through to it.
#     712                 :      27680 :     bool needsDB = !encrypted_batch;
#     713         [ +  - ]:      27680 :     if (needsDB) {
#     714                 :      27680 :         encrypted_batch = &batch;
#     715                 :      27680 :     }
#     716         [ -  + ]:      27680 :     if (!AddKeyPubKeyInner(secret, pubkey)) {
#     717         [ #  # ]:          0 :         if (needsDB) encrypted_batch = nullptr;
#     718                 :          0 :         return false;
#     719                 :          0 :     }
#     720         [ +  - ]:      27680 :     if (needsDB) encrypted_batch = nullptr;
#     721                 :            : 
#     722                 :            :     // check if we need to remove from watch-only
#     723                 :      27680 :     CScript script;
#     724                 :      27680 :     script = GetScriptForDestination(PKHash(pubkey));
#     725         [ +  + ]:      27680 :     if (HaveWatchOnly(script)) {
#     726                 :          4 :         RemoveWatchOnly(script);
#     727                 :          4 :     }
#     728                 :      27680 :     script = GetScriptForRawPubKey(pubkey);
#     729         [ +  + ]:      27680 :     if (HaveWatchOnly(script)) {
#     730                 :          4 :         RemoveWatchOnly(script);
#     731                 :          4 :     }
#     732                 :            : 
#     733         [ +  + ]:      27680 :     if (!m_storage.HasEncryptionKeys()) {
#     734                 :      27139 :         return batch.WriteKey(pubkey,
#     735                 :      27139 :                                                  secret.GetPrivKey(),
#     736                 :      27139 :                                                  mapKeyMetadata[pubkey.GetID()]);
#     737                 :      27139 :     }
#     738                 :        541 :     m_storage.UnsetBlankWalletFlag(batch);
#     739                 :        541 :     return true;
#     740                 :        541 : }
#     741                 :            : 
#     742                 :            : bool LegacyScriptPubKeyMan::LoadCScript(const CScript& redeemScript)
#     743                 :       2625 : {
#     744                 :            :     /* A sanity check was added in pull #3843 to avoid adding redeemScripts
#     745                 :            :      * that never can be redeemed. However, old wallets may still contain
#     746                 :            :      * these. Do not add them to the wallet and warn. */
#     747         [ -  + ]:       2625 :     if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
#     748                 :          0 :     {
#     749                 :          0 :         std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
#     750                 :          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);
#     751                 :          0 :         return true;
#     752                 :          0 :     }
#     753                 :            : 
#     754                 :       2625 :     return FillableSigningProvider::AddCScript(redeemScript);
#     755                 :       2625 : }
#     756                 :            : 
#     757                 :            : void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
#     758                 :      10809 : {
#     759                 :      10809 :     LOCK(cs_KeyStore);
#     760                 :      10809 :     UpdateTimeFirstKey(meta.nCreateTime);
#     761                 :      10809 :     mapKeyMetadata[keyID] = meta;
#     762                 :      10809 : }
#     763                 :            : 
#     764                 :            : void LegacyScriptPubKeyMan::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
#     765                 :        255 : {
#     766                 :        255 :     LOCK(cs_KeyStore);
#     767                 :        255 :     UpdateTimeFirstKey(meta.nCreateTime);
#     768                 :        255 :     m_script_metadata[script_id] = meta;
#     769                 :        255 : }
#     770                 :            : 
#     771                 :            : bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
#     772                 :      38255 : {
#     773                 :      38255 :     LOCK(cs_KeyStore);
#     774         [ +  + ]:      38255 :     if (!m_storage.HasEncryptionKeys()) {
#     775                 :      37714 :         return FillableSigningProvider::AddKeyPubKey(key, pubkey);
#     776                 :      37714 :     }
#     777                 :            : 
#     778         [ -  + ]:        541 :     if (m_storage.IsLocked()) {
#     779                 :          0 :         return false;
#     780                 :          0 :     }
#     781                 :            : 
#     782                 :        541 :     std::vector<unsigned char> vchCryptedSecret;
#     783                 :        541 :     CKeyingMaterial vchSecret(key.begin(), key.end());
#     784         [ -  + ]:        541 :     if (!EncryptSecret(m_storage.GetEncryptionKey(), vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
#     785                 :          0 :         return false;
#     786                 :          0 :     }
#     787                 :            : 
#     788         [ -  + ]:        541 :     if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
#     789                 :          0 :         return false;
#     790                 :          0 :     }
#     791                 :        541 :     return true;
#     792                 :        541 : }
#     793                 :            : 
#     794                 :            : bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
#     795                 :        132 : {
#     796                 :            :     // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
#     797         [ +  - ]:        132 :     if (!checksum_valid) {
#     798                 :        132 :         fDecryptionThoroughlyChecked = false;
#     799                 :        132 :     }
#     800                 :            : 
#     801                 :        132 :     return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
#     802                 :        132 : }
#     803                 :            : 
#     804                 :            : bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
#     805                 :        940 : {
#     806                 :        940 :     LOCK(cs_KeyStore);
#     807                 :        940 :     assert(mapKeys.empty());
#     808                 :            : 
#     809                 :        940 :     mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
#     810                 :        940 :     ImplicitlyLearnRelatedKeyScripts(vchPubKey);
#     811                 :        940 :     return true;
#     812                 :        940 : }
#     813                 :            : 
#     814                 :            : bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
#     815                 :            :                             const std::vector<unsigned char> &vchCryptedSecret)
#     816                 :        808 : {
#     817         [ -  + ]:        808 :     if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
#     818                 :          0 :         return false;
#     819                 :        808 :     {
#     820                 :        808 :         LOCK(cs_KeyStore);
#     821         [ +  - ]:        808 :         if (encrypted_batch)
#     822                 :        808 :             return encrypted_batch->WriteCryptedKey(vchPubKey,
#     823                 :        808 :                                                         vchCryptedSecret,
#     824                 :        808 :                                                         mapKeyMetadata[vchPubKey.GetID()]);
#     825                 :          0 :         else
#     826                 :          0 :             return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
#     827                 :          0 :                                                             vchCryptedSecret,
#     828                 :          0 :                                                             mapKeyMetadata[vchPubKey.GetID()]);
#     829                 :        808 :     }
#     830                 :        808 : }
#     831                 :            : 
#     832                 :            : bool LegacyScriptPubKeyMan::HaveWatchOnly(const CScript &dest) const
#     833                 :     789407 : {
#     834                 :     789407 :     LOCK(cs_KeyStore);
#     835                 :     789407 :     return setWatchOnly.count(dest) > 0;
#     836                 :     789407 : }
#     837                 :            : 
#     838                 :            : bool LegacyScriptPubKeyMan::HaveWatchOnly() const
#     839                 :        528 : {
#     840                 :        528 :     LOCK(cs_KeyStore);
#     841                 :        528 :     return (!setWatchOnly.empty());
#     842                 :        528 : }
#     843                 :            : 
#     844                 :            : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
#     845                 :        945 : {
#     846                 :        945 :     std::vector<std::vector<unsigned char>> solutions;
#     847         [ +  + ]:        945 :     return Solver(dest, solutions) == TxoutType::PUBKEY &&
#     848         [ +  + ]:        945 :         (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
#     849                 :        945 : }
#     850                 :            : 
#     851                 :            : bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest)
#     852                 :         13 : {
#     853                 :         13 :     {
#     854                 :         13 :         LOCK(cs_KeyStore);
#     855                 :         13 :         setWatchOnly.erase(dest);
#     856                 :         13 :         CPubKey pubKey;
#     857         [ +  + ]:         13 :         if (ExtractPubKey(dest, pubKey)) {
#     858                 :          6 :             mapWatchKeys.erase(pubKey.GetID());
#     859                 :          6 :         }
#     860                 :            :         // Related CScripts are not removed; having superfluous scripts around is
#     861                 :            :         // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
#     862                 :         13 :     }
#     863                 :            : 
#     864         [ +  + ]:         13 :     if (!HaveWatchOnly())
#     865                 :          5 :         NotifyWatchonlyChanged(false);
#     866         [ -  + ]:         13 :     if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
#     867                 :          0 :         return false;
#     868                 :            : 
#     869                 :         13 :     return true;
#     870                 :         13 : }
#     871                 :            : 
#     872                 :            : bool LegacyScriptPubKeyMan::LoadWatchOnly(const CScript &dest)
#     873                 :        260 : {
#     874                 :        260 :     return AddWatchOnlyInMem(dest);
#     875                 :        260 : }
#     876                 :            : 
#     877                 :            : bool LegacyScriptPubKeyMan::AddWatchOnlyInMem(const CScript &dest)
#     878                 :        932 : {
#     879                 :        932 :     LOCK(cs_KeyStore);
#     880                 :        932 :     setWatchOnly.insert(dest);
#     881                 :        932 :     CPubKey pubKey;
#     882         [ +  + ]:        932 :     if (ExtractPubKey(dest, pubKey)) {
#     883                 :        337 :         mapWatchKeys[pubKey.GetID()] = pubKey;
#     884                 :        337 :         ImplicitlyLearnRelatedKeyScripts(pubKey);
#     885                 :        337 :     }
#     886                 :        932 :     return true;
#     887                 :        932 : }
#     888                 :            : 
#     889                 :            : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest)
#     890                 :        672 : {
#     891         [ -  + ]:        672 :     if (!AddWatchOnlyInMem(dest))
#     892                 :          0 :         return false;
#     893                 :        672 :     const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
#     894                 :        672 :     UpdateTimeFirstKey(meta.nCreateTime);
#     895                 :        672 :     NotifyWatchonlyChanged(true);
#     896         [ +  - ]:        672 :     if (batch.WriteWatchOnly(dest, meta)) {
#     897                 :        672 :         m_storage.UnsetBlankWalletFlag(batch);
#     898                 :        672 :         return true;
#     899                 :        672 :     }
#     900                 :          0 :     return false;
#     901                 :          0 : }
#     902                 :            : 
#     903                 :            : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
#     904                 :        672 : {
#     905                 :        672 :     m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
#     906                 :        672 :     return AddWatchOnlyWithDB(batch, dest);
#     907                 :        672 : }
#     908                 :            : 
#     909                 :            : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest)
#     910                 :          0 : {
#     911                 :          0 :     WalletBatch batch(m_storage.GetDatabase());
#     912                 :          0 :     return AddWatchOnlyWithDB(batch, dest);
#     913                 :          0 : }
#     914                 :            : 
#     915                 :            : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
#     916                 :          0 : {
#     917                 :          0 :     m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
#     918                 :          0 :     return AddWatchOnly(dest);
#     919                 :          0 : }
#     920                 :            : 
#     921                 :            : void LegacyScriptPubKeyMan::LoadHDChain(const CHDChain& chain)
#     922                 :        213 : {
#     923                 :        213 :     LOCK(cs_KeyStore);
#     924                 :        213 :     m_hd_chain = chain;
#     925                 :        213 : }
#     926                 :            : 
#     927                 :            : void LegacyScriptPubKeyMan::AddHDChain(const CHDChain& chain)
#     928                 :        257 : {
#     929                 :        257 :     LOCK(cs_KeyStore);
#     930                 :            :     // Store the new chain
#     931         [ -  + ]:        257 :     if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
#     932                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing chain failed");
#     933                 :          0 :     }
#     934                 :            :     // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
#     935         [ +  + ]:        257 :     if (!m_hd_chain.seed_id.IsNull()) {
#     936                 :         14 :         AddInactiveHDChain(m_hd_chain);
#     937                 :         14 :     }
#     938                 :            : 
#     939                 :        257 :     m_hd_chain = chain;
#     940                 :        257 : }
#     941                 :            : 
#     942                 :            : void LegacyScriptPubKeyMan::AddInactiveHDChain(const CHDChain& chain)
#     943                 :         26 : {
#     944                 :         26 :     LOCK(cs_KeyStore);
#     945                 :         26 :     assert(!chain.seed_id.IsNull());
#     946                 :         26 :     m_inactive_hd_chains[chain.seed_id] = chain;
#     947                 :         26 : }
#     948                 :            : 
#     949                 :            : bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const
#     950                 :    1264383 : {
#     951                 :    1264383 :     LOCK(cs_KeyStore);
#     952         [ +  + ]:    1264383 :     if (!m_storage.HasEncryptionKeys()) {
#     953                 :    1171676 :         return FillableSigningProvider::HaveKey(address);
#     954                 :    1171676 :     }
#     955                 :      92707 :     return mapCryptedKeys.count(address) > 0;
#     956                 :      92707 : }
#     957                 :            : 
#     958                 :            : bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey& keyOut) const
#     959                 :    1288024 : {
#     960                 :    1288024 :     LOCK(cs_KeyStore);
#     961         [ +  + ]:    1288024 :     if (!m_storage.HasEncryptionKeys()) {
#     962                 :    1286209 :         return FillableSigningProvider::GetKey(address, keyOut);
#     963                 :    1286209 :     }
#     964                 :            : 
#     965                 :       1815 :     CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
#     966         [ +  - ]:       1815 :     if (mi != mapCryptedKeys.end())
#     967                 :       1815 :     {
#     968                 :       1815 :         const CPubKey &vchPubKey = (*mi).second.first;
#     969                 :       1815 :         const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
#     970                 :       1815 :         return DecryptKey(m_storage.GetEncryptionKey(), vchCryptedSecret, vchPubKey, keyOut);
#     971                 :       1815 :     }
#     972                 :          0 :     return false;
#     973                 :          0 : }
#     974                 :            : 
#     975                 :            : bool LegacyScriptPubKeyMan::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
#     976                 :     761971 : {
#     977                 :     761971 :     CKeyMetadata meta;
#     978                 :     761971 :     {
#     979                 :     761971 :         LOCK(cs_KeyStore);
#     980                 :     761971 :         auto it = mapKeyMetadata.find(keyID);
#     981         [ +  + ]:     761971 :         if (it != mapKeyMetadata.end()) {
#     982                 :     761175 :             meta = it->second;
#     983                 :     761175 :         }
#     984                 :     761971 :     }
#     985         [ +  + ]:     761971 :     if (meta.has_key_origin) {
#     986                 :     377237 :         std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
#     987                 :     377237 :         info.path = meta.key_origin.path;
#     988                 :     384734 :     } else { // Single pubkeys get the master fingerprint of themselves
#     989                 :     384734 :         std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
#     990                 :     384734 :     }
#     991                 :     761971 :     return true;
#     992                 :     761971 : }
#     993                 :            : 
#     994                 :            : bool LegacyScriptPubKeyMan::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
#     995                 :      34218 : {
#     996                 :      34218 :     LOCK(cs_KeyStore);
#     997                 :      34218 :     WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
#     998         [ +  + ]:      34218 :     if (it != mapWatchKeys.end()) {
#     999                 :       5468 :         pubkey_out = it->second;
#    1000                 :       5468 :         return true;
#    1001                 :       5468 :     }
#    1002                 :      28750 :     return false;
#    1003                 :      28750 : }
#    1004                 :            : 
#    1005                 :            : bool LegacyScriptPubKeyMan::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
#    1006                 :    1351117 : {
#    1007                 :    1351117 :     LOCK(cs_KeyStore);
#    1008         [ +  + ]:    1351117 :     if (!m_storage.HasEncryptionKeys()) {
#    1009         [ +  + ]:    1237697 :         if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
#    1010                 :      33960 :             return GetWatchPubKey(address, vchPubKeyOut);
#    1011                 :      33960 :         }
#    1012                 :    1203737 :         return true;
#    1013                 :    1203737 :     }
#    1014                 :            : 
#    1015                 :     113420 :     CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
#    1016         [ +  + ]:     113420 :     if (mi != mapCryptedKeys.end())
#    1017                 :     113169 :     {
#    1018                 :     113169 :         vchPubKeyOut = (*mi).second.first;
#    1019                 :     113169 :         return true;
#    1020                 :     113169 :     }
#    1021                 :            :     // Check for watch-only pubkeys
#    1022                 :        251 :     return GetWatchPubKey(address, vchPubKeyOut);
#    1023                 :        251 : }
#    1024                 :            : 
#    1025                 :            : CPubKey LegacyScriptPubKeyMan::GenerateNewKey(WalletBatch &batch, CHDChain& hd_chain, bool internal)
#    1026                 :      26269 : {
#    1027                 :      26269 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
#    1028                 :      26269 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
#    1029                 :      26269 :     AssertLockHeld(cs_KeyStore);
#    1030                 :      26269 :     bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
#    1031                 :            : 
#    1032                 :      26269 :     CKey secret;
#    1033                 :            : 
#    1034                 :            :     // Create new metadata
#    1035                 :      26269 :     int64_t nCreationTime = GetTime();
#    1036                 :      26269 :     CKeyMetadata metadata(nCreationTime);
#    1037                 :            : 
#    1038                 :            :     // use HD key derivation if HD was enabled during wallet creation and a seed is present
#    1039         [ +  + ]:      26269 :     if (IsHDEnabled()) {
#    1040         [ +  + ]:      24267 :         DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
#    1041                 :      24267 :     } else {
#    1042                 :       2002 :         secret.MakeNewKey(fCompressed);
#    1043                 :       2002 :     }
#    1044                 :            : 
#    1045                 :            :     // Compressed public keys were introduced in version 0.6.0
#    1046         [ +  + ]:      26269 :     if (fCompressed) {
#    1047                 :      23267 :         m_storage.SetMinVersion(FEATURE_COMPRPUBKEY);
#    1048                 :      23267 :     }
#    1049                 :            : 
#    1050                 :      26269 :     CPubKey pubkey = secret.GetPubKey();
#    1051                 :      26269 :     assert(secret.VerifyPubKey(pubkey));
#    1052                 :            : 
#    1053                 :      26269 :     mapKeyMetadata[pubkey.GetID()] = metadata;
#    1054                 :      26269 :     UpdateTimeFirstKey(nCreationTime);
#    1055                 :            : 
#    1056         [ -  + ]:      26269 :     if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
#    1057                 :          0 :         throw std::runtime_error(std::string(__func__) + ": AddKey failed");
#    1058                 :          0 :     }
#    1059                 :      26269 :     return pubkey;
#    1060                 :      26269 : }
#    1061                 :            : 
#    1062                 :            : void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
#    1063                 :      24267 : {
#    1064                 :            :     // for now we use a fixed keypath scheme of m/0'/0'/k
#    1065                 :      24267 :     CKey seed;                     //seed (256bit)
#    1066                 :      24267 :     CExtKey masterKey;             //hd master key
#    1067                 :      24267 :     CExtKey accountKey;            //key at m/0'
#    1068                 :      24267 :     CExtKey chainChildKey;         //key at m/0'/0' (external) or m/0'/1' (internal)
#    1069                 :      24267 :     CExtKey childKey;              //key at m/0'/0'/<n>'
#    1070                 :            : 
#    1071                 :            :     // try to get the seed
#    1072         [ -  + ]:      24267 :     if (!GetKey(hd_chain.seed_id, seed))
#    1073                 :          0 :         throw std::runtime_error(std::string(__func__) + ": seed not found");
#    1074                 :            : 
#    1075                 :      24267 :     masterKey.SetSeed(seed.begin(), seed.size());
#    1076                 :            : 
#    1077                 :            :     // derive m/0'
#    1078                 :            :     // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
#    1079                 :      24267 :     masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
#    1080                 :            : 
#    1081                 :            :     // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
#    1082                 :      24267 :     assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
#    1083         [ +  + ]:      24267 :     accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
#    1084                 :            : 
#    1085                 :            :     // derive child key at next index, skip keys already known to the wallet
#    1086                 :      24269 :     do {
#    1087                 :            :         // always derive hardened keys
#    1088                 :            :         // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
#    1089                 :            :         // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
#    1090         [ +  + ]:      24269 :         if (internal) {
#    1091                 :       8478 :             chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
#    1092                 :       8478 :             metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
#    1093                 :       8478 :             metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
#    1094                 :       8478 :             metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
#    1095                 :       8478 :             metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
#    1096                 :       8478 :             hd_chain.nInternalChainCounter++;
#    1097                 :       8478 :         }
#    1098                 :      15791 :         else {
#    1099                 :      15791 :             chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
#    1100                 :      15791 :             metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
#    1101                 :      15791 :             metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
#    1102                 :      15791 :             metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
#    1103                 :      15791 :             metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
#    1104                 :      15791 :             hd_chain.nExternalChainCounter++;
#    1105                 :      15791 :         }
#    1106         [ +  + ]:      24269 :     } while (HaveKey(childKey.key.GetPubKey().GetID()));
#    1107                 :      24267 :     secret = childKey.key;
#    1108                 :      24267 :     metadata.hd_seed_id = hd_chain.seed_id;
#    1109                 :      24267 :     CKeyID master_id = masterKey.key.GetPubKey().GetID();
#    1110                 :      24267 :     std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
#    1111                 :      24267 :     metadata.has_key_origin = true;
#    1112                 :            :     // update the chain model in the database
#    1113 [ +  + ][ -  + ]:      24267 :     if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
#    1114                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
#    1115                 :      24267 : }
#    1116                 :            : 
#    1117                 :            : void LegacyScriptPubKeyMan::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
#    1118                 :       7839 : {
#    1119                 :       7839 :     LOCK(cs_KeyStore);
#    1120         [ -  + ]:       7839 :     if (keypool.m_pre_split) {
#    1121                 :          0 :         set_pre_split_keypool.insert(nIndex);
#    1122         [ +  + ]:       7839 :     } else if (keypool.fInternal) {
#    1123                 :       3986 :         setInternalKeyPool.insert(nIndex);
#    1124                 :       3986 :     } else {
#    1125                 :       3853 :         setExternalKeyPool.insert(nIndex);
#    1126                 :       3853 :     }
#    1127                 :       7839 :     m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
#    1128                 :       7839 :     m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
#    1129                 :            : 
#    1130                 :            :     // If no metadata exists yet, create a default with the pool key's
#    1131                 :            :     // creation time. Note that this may be overwritten by actually
#    1132                 :            :     // stored metadata for that key later, which is fine.
#    1133                 :       7839 :     CKeyID keyid = keypool.vchPubKey.GetID();
#    1134         [ +  - ]:       7839 :     if (mapKeyMetadata.count(keyid) == 0)
#    1135                 :       7839 :         mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
#    1136                 :       7839 : }
#    1137                 :            : 
#    1138                 :            : bool LegacyScriptPubKeyMan::CanGenerateKeys() const
#    1139                 :      21646 : {
#    1140                 :            :     // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
#    1141                 :      21646 :     LOCK(cs_KeyStore);
#    1142 [ +  + ][ +  + ]:      21646 :     return IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD);
#    1143                 :      21646 : }
#    1144                 :            : 
#    1145                 :            : CPubKey LegacyScriptPubKeyMan::GenerateNewSeed()
#    1146                 :        250 : {
#    1147                 :        250 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
#    1148                 :        250 :     CKey key;
#    1149                 :        250 :     key.MakeNewKey(true);
#    1150                 :        250 :     return DeriveNewSeed(key);
#    1151                 :        250 : }
#    1152                 :            : 
#    1153                 :            : CPubKey LegacyScriptPubKeyMan::DeriveNewSeed(const CKey& key)
#    1154                 :        257 : {
#    1155                 :        257 :     int64_t nCreationTime = GetTime();
#    1156                 :        257 :     CKeyMetadata metadata(nCreationTime);
#    1157                 :            : 
#    1158                 :            :     // calculate the seed
#    1159                 :        257 :     CPubKey seed = key.GetPubKey();
#    1160                 :        257 :     assert(key.VerifyPubKey(seed));
#    1161                 :            : 
#    1162                 :            :     // set the hd keypath to "s" -> Seed, refers the seed to itself
#    1163                 :        257 :     metadata.hdKeypath     = "s";
#    1164                 :        257 :     metadata.has_key_origin = false;
#    1165                 :        257 :     metadata.hd_seed_id = seed.GetID();
#    1166                 :            : 
#    1167                 :        257 :     {
#    1168                 :        257 :         LOCK(cs_KeyStore);
#    1169                 :            : 
#    1170                 :            :         // mem store the metadata
#    1171                 :        257 :         mapKeyMetadata[seed.GetID()] = metadata;
#    1172                 :            : 
#    1173                 :            :         // write the key&metadata to the database
#    1174         [ -  + ]:        257 :         if (!AddKeyPubKey(key, seed))
#    1175                 :          0 :             throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
#    1176                 :        257 :     }
#    1177                 :            : 
#    1178                 :        257 :     return seed;
#    1179                 :        257 : }
#    1180                 :            : 
#    1181                 :            : void LegacyScriptPubKeyMan::SetHDSeed(const CPubKey& seed)
#    1182                 :        257 : {
#    1183                 :        257 :     LOCK(cs_KeyStore);
#    1184                 :            :     // store the keyid (hash160) together with
#    1185                 :            :     // the child index counter in the database
#    1186                 :            :     // as a hdchain object
#    1187                 :        257 :     CHDChain newHdChain;
#    1188         [ +  + ]:        257 :     newHdChain.nVersion = m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
#    1189                 :        257 :     newHdChain.seed_id = seed.GetID();
#    1190                 :        257 :     AddHDChain(newHdChain);
#    1191                 :        257 :     NotifyCanGetAddressesChanged();
#    1192                 :        257 :     WalletBatch batch(m_storage.GetDatabase());
#    1193                 :        257 :     m_storage.UnsetBlankWalletFlag(batch);
#    1194                 :        257 : }
#    1195                 :            : 
#    1196                 :            : /**
#    1197                 :            :  * Mark old keypool keys as used,
#    1198                 :            :  * and generate all new keys
#    1199                 :            :  */
#    1200                 :            : bool LegacyScriptPubKeyMan::NewKeyPool()
#    1201                 :        256 : {
#    1202         [ -  + ]:        256 :     if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#    1203                 :          0 :         return false;
#    1204                 :          0 :     }
#    1205                 :        256 :     {
#    1206                 :        256 :         LOCK(cs_KeyStore);
#    1207                 :        256 :         WalletBatch batch(m_storage.GetDatabase());
#    1208                 :            : 
#    1209         [ +  + ]:        256 :         for (const int64_t nIndex : setInternalKeyPool) {
#    1210                 :        104 :             batch.ErasePool(nIndex);
#    1211                 :        104 :         }
#    1212                 :        256 :         setInternalKeyPool.clear();
#    1213                 :            : 
#    1214         [ +  + ]:        256 :         for (const int64_t nIndex : setExternalKeyPool) {
#    1215                 :        103 :             batch.ErasePool(nIndex);
#    1216                 :        103 :         }
#    1217                 :        256 :         setExternalKeyPool.clear();
#    1218                 :            : 
#    1219         [ -  + ]:        256 :         for (const int64_t nIndex : set_pre_split_keypool) {
#    1220                 :          0 :             batch.ErasePool(nIndex);
#    1221                 :          0 :         }
#    1222                 :        256 :         set_pre_split_keypool.clear();
#    1223                 :            : 
#    1224                 :        256 :         m_pool_key_to_index.clear();
#    1225                 :            : 
#    1226         [ -  + ]:        256 :         if (!TopUp()) {
#    1227                 :          0 :             return false;
#    1228                 :          0 :         }
#    1229                 :        256 :         WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
#    1230                 :        256 :     }
#    1231                 :        256 :     return true;
#    1232                 :        256 : }
#    1233                 :            : 
#    1234                 :            : bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
#    1235                 :      12904 : {
#    1236         [ +  + ]:      12904 :     if (!CanGenerateKeys()) {
#    1237                 :         86 :         return false;
#    1238                 :         86 :     }
#    1239                 :      12818 :     {
#    1240                 :      12818 :         LOCK(cs_KeyStore);
#    1241                 :            : 
#    1242         [ +  + ]:      12818 :         if (m_storage.IsLocked()) return false;
#    1243                 :            : 
#    1244                 :            :         // Top up key pool
#    1245                 :      12779 :         unsigned int nTargetSize;
#    1246         [ +  + ]:      12779 :         if (kpSize > 0)
#    1247                 :          8 :             nTargetSize = kpSize;
#    1248                 :      12771 :         else
#    1249                 :      12771 :             nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
#    1250                 :            : 
#    1251                 :            :         // count amount of available keys (internal, external)
#    1252                 :            :         // make sure the keypool of external and internal keys fits the user selected target (-keypool)
#    1253                 :      12779 :         int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
#    1254                 :      12779 :         int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
#    1255                 :            : 
#    1256 [ +  + ][ +  + ]:      12779 :         if (!IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))
#    1257                 :          5 :         {
#    1258                 :            :             // don't create extra internal keys
#    1259                 :          5 :             missingInternal = 0;
#    1260                 :          5 :         }
#    1261                 :      12779 :         bool internal = false;
#    1262                 :      12779 :         WalletBatch batch(m_storage.GetDatabase());
#    1263         [ +  + ]:      39036 :         for (int64_t i = missingInternal + missingExternal; i--;)
#    1264                 :      26257 :         {
#    1265         [ +  + ]:      26257 :             if (i < missingInternal) {
#    1266                 :       8473 :                 internal = true;
#    1267                 :       8473 :             }
#    1268                 :            : 
#    1269                 :      26257 :             CPubKey pubkey(GenerateNewKey(batch, m_hd_chain, internal));
#    1270                 :      26257 :             AddKeypoolPubkeyWithDB(pubkey, internal, batch);
#    1271                 :      26257 :         }
#    1272         [ +  + ]:      12779 :         if (missingInternal + missingExternal > 0) {
#    1273                 :      12126 :             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());
#    1274                 :      12126 :         }
#    1275                 :      12779 :     }
#    1276                 :      12779 :     NotifyCanGetAddressesChanged();
#    1277                 :      12779 :     return true;
#    1278                 :      12779 : }
#    1279                 :            : 
#    1280                 :            : void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
#    1281                 :      26395 : {
#    1282                 :      26395 :     LOCK(cs_KeyStore);
#    1283                 :      26395 :     assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
#    1284                 :      26395 :     int64_t index = ++m_max_keypool_index;
#    1285         [ -  + ]:      26395 :     if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
#    1286                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
#    1287                 :          0 :     }
#    1288         [ +  + ]:      26395 :     if (internal) {
#    1289                 :       8590 :         setInternalKeyPool.insert(index);
#    1290                 :      17805 :     } else {
#    1291                 :      17805 :         setExternalKeyPool.insert(index);
#    1292                 :      17805 :     }
#    1293                 :      26395 :     m_pool_key_to_index[pubkey.GetID()] = index;
#    1294                 :      26395 : }
#    1295                 :            : 
#    1296                 :            : void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
#    1297                 :      12000 : {
#    1298                 :            :     // Remove from key pool
#    1299                 :      12000 :     WalletBatch batch(m_storage.GetDatabase());
#    1300                 :      12000 :     batch.ErasePool(nIndex);
#    1301                 :      12000 :     CPubKey pubkey;
#    1302                 :      12000 :     bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
#    1303                 :      12000 :     assert(have_pk);
#    1304                 :      12000 :     LearnRelatedScripts(pubkey, type);
#    1305                 :      12000 :     m_index_to_reserved_key.erase(nIndex);
#    1306                 :      12000 :     WalletLogPrintf("keypool keep %d\n", nIndex);
#    1307                 :      12000 : }
#    1308                 :            : 
#    1309                 :            : void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
#    1310                 :         67 : {
#    1311                 :            :     // Return to key pool
#    1312                 :         67 :     {
#    1313                 :         67 :         LOCK(cs_KeyStore);
#    1314         [ +  - ]:         67 :         if (fInternal) {
#    1315                 :         67 :             setInternalKeyPool.insert(nIndex);
#    1316         [ #  # ]:         67 :         } else if (!set_pre_split_keypool.empty()) {
#    1317                 :          0 :             set_pre_split_keypool.insert(nIndex);
#    1318                 :          0 :         } else {
#    1319                 :          0 :             setExternalKeyPool.insert(nIndex);
#    1320                 :          0 :         }
#    1321                 :         67 :         CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
#    1322                 :         67 :         m_pool_key_to_index[pubkey_id] = nIndex;
#    1323                 :         67 :         m_index_to_reserved_key.erase(nIndex);
#    1324                 :         67 :         NotifyCanGetAddressesChanged();
#    1325                 :         67 :     }
#    1326                 :         67 :     WalletLogPrintf("keypool return %d\n", nIndex);
#    1327                 :         67 : }
#    1328                 :            : 
#    1329                 :            : bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type, bool internal)
#    1330                 :       9111 : {
#    1331         [ +  + ]:       9111 :     if (!CanGetAddresses(internal)) {
#    1332                 :          1 :         return false;
#    1333                 :          1 :     }
#    1334                 :            : 
#    1335                 :       9110 :     CKeyPool keypool;
#    1336                 :       9110 :     {
#    1337                 :       9110 :         LOCK(cs_KeyStore);
#    1338                 :       9110 :         int64_t nIndex;
#    1339 [ +  + ][ +  - ]:       9110 :         if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#    1340         [ +  - ]:          3 :             if (m_storage.IsLocked()) return false;
#    1341                 :          0 :             WalletBatch batch(m_storage.GetDatabase());
#    1342                 :          0 :             result = GenerateNewKey(batch, m_hd_chain, internal);
#    1343                 :          0 :             return true;
#    1344                 :          0 :         }
#    1345                 :       9107 :         KeepDestination(nIndex, type);
#    1346                 :       9107 :         result = keypool.vchPubKey;
#    1347                 :       9107 :     }
#    1348                 :       9107 :     return true;
#    1349                 :       9107 : }
#    1350                 :            : 
#    1351                 :            : bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
#    1352                 :      12074 : {
#    1353                 :      12074 :     nIndex = -1;
#    1354                 :      12074 :     keypool.vchPubKey = CPubKey();
#    1355                 :      12074 :     {
#    1356                 :      12074 :         LOCK(cs_KeyStore);
#    1357                 :            : 
#    1358                 :      12074 :         bool fReturningInternal = fRequestedInternal;
#    1359 [ +  + ][ +  - ]:      12074 :         fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
#                 [ +  + ]
#    1360                 :      12074 :         bool use_split_keypool = set_pre_split_keypool.empty();
#    1361 [ +  - ][ +  + ]:      12074 :         std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
#    1362                 :            : 
#    1363                 :            :         // Get the oldest key
#    1364         [ +  + ]:      12074 :         if (setKeyPool.empty()) {
#    1365                 :          7 :             return false;
#    1366                 :          7 :         }
#    1367                 :            : 
#    1368                 :      12067 :         WalletBatch batch(m_storage.GetDatabase());
#    1369                 :            : 
#    1370                 :      12067 :         auto it = setKeyPool.begin();
#    1371                 :      12067 :         nIndex = *it;
#    1372                 :      12067 :         setKeyPool.erase(it);
#    1373         [ -  + ]:      12067 :         if (!batch.ReadPool(nIndex, keypool)) {
#    1374                 :          0 :             throw std::runtime_error(std::string(__func__) + ": read failed");
#    1375                 :          0 :         }
#    1376                 :      12067 :         CPubKey pk;
#    1377         [ -  + ]:      12067 :         if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
#    1378                 :          0 :             throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
#    1379                 :          0 :         }
#    1380                 :            :         // If the key was pre-split keypool, we don't care about what type it is
#    1381 [ +  - ][ -  + ]:      12067 :         if (use_split_keypool && keypool.fInternal != fReturningInternal) {
#    1382                 :          0 :             throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
#    1383                 :          0 :         }
#    1384         [ -  + ]:      12067 :         if (!keypool.vchPubKey.IsValid()) {
#    1385                 :          0 :             throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
#    1386                 :          0 :         }
#    1387                 :            : 
#    1388                 :      12067 :         assert(m_index_to_reserved_key.count(nIndex) == 0);
#    1389                 :      12067 :         m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
#    1390                 :      12067 :         m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
#    1391                 :      12067 :         WalletLogPrintf("keypool reserve %d\n", nIndex);
#    1392                 :      12067 :     }
#    1393                 :      12067 :     NotifyCanGetAddressesChanged();
#    1394                 :      12067 :     return true;
#    1395                 :      12067 : }
#    1396                 :            : 
#    1397                 :            : void LegacyScriptPubKeyMan::LearnRelatedScripts(const CPubKey& key, OutputType type)
#    1398                 :      21273 : {
#    1399 [ +  + ][ +  + ]:      21273 :     if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
#                 [ +  + ]
#    1400                 :      20635 :         CTxDestination witdest = WitnessV0KeyHash(key.GetID());
#    1401                 :      20635 :         CScript witprog = GetScriptForDestination(witdest);
#    1402                 :            :         // Make sure the resulting program is solvable.
#    1403                 :      20635 :         assert(IsSolvable(*this, witprog));
#    1404                 :      20635 :         AddCScript(witprog);
#    1405                 :      20635 :     }
#    1406                 :      21273 : }
#    1407                 :            : 
#    1408                 :            : void LegacyScriptPubKeyMan::LearnAllRelatedScripts(const CPubKey& key)
#    1409                 :        166 : {
#    1410                 :            :     // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
#    1411                 :        166 :     LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
#    1412                 :        166 : }
#    1413                 :            : 
#    1414                 :            : void LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
#    1415                 :         37 : {
#    1416                 :         37 :     AssertLockHeld(cs_KeyStore);
#    1417                 :         37 :     bool internal = setInternalKeyPool.count(keypool_id);
#    1418         [ +  + ]:         37 :     if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
#    1419 [ +  + ][ +  - ]:         37 :     std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
#    1420                 :         37 :     auto it = setKeyPool->begin();
#    1421                 :            : 
#    1422                 :         37 :     WalletBatch batch(m_storage.GetDatabase());
#    1423         [ +  + ]:        203 :     while (it != std::end(*setKeyPool)) {
#    1424                 :        190 :         const int64_t& index = *(it);
#    1425         [ +  + ]:        190 :         if (index > keypool_id) break; // set*KeyPool is ordered
#    1426                 :            : 
#    1427                 :        166 :         CKeyPool keypool;
#    1428         [ +  - ]:        166 :         if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
#    1429                 :        166 :             m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
#    1430                 :        166 :         }
#    1431                 :        166 :         LearnAllRelatedScripts(keypool.vchPubKey);
#    1432                 :        166 :         batch.ErasePool(index);
#    1433                 :        166 :         WalletLogPrintf("keypool index %d removed\n", index);
#    1434                 :        166 :         it = setKeyPool->erase(it);
#    1435                 :        166 :     }
#    1436                 :         37 : }
#    1437                 :            : 
#    1438                 :            : std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
#    1439                 :     189019 : {
#    1440                 :     189019 :     std::vector<CScript> dummy;
#    1441                 :     189019 :     FlatSigningProvider out;
#    1442                 :     189019 :     InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
#    1443                 :     189019 :     std::vector<CKeyID> ret;
#    1444         [ +  + ]:     189019 :     for (const auto& entry : out.pubkeys) {
#    1445                 :      78175 :         ret.push_back(entry.first);
#    1446                 :      78175 :     }
#    1447                 :     189019 :     return ret;
#    1448                 :     189019 : }
#    1449                 :            : 
#    1450                 :            : void LegacyScriptPubKeyMan::MarkPreSplitKeys()
#    1451                 :          0 : {
#    1452                 :          0 :     WalletBatch batch(m_storage.GetDatabase());
#    1453         [ #  # ]:          0 :     for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
#    1454                 :          0 :         int64_t index = *it;
#    1455                 :          0 :         CKeyPool keypool;
#    1456         [ #  # ]:          0 :         if (!batch.ReadPool(index, keypool)) {
#    1457                 :          0 :             throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
#    1458                 :          0 :         }
#    1459                 :          0 :         keypool.m_pre_split = true;
#    1460         [ #  # ]:          0 :         if (!batch.WritePool(index, keypool)) {
#    1461                 :          0 :             throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
#    1462                 :          0 :         }
#    1463                 :          0 :         set_pre_split_keypool.insert(index);
#    1464                 :          0 :         it = setExternalKeyPool.erase(it);
#    1465                 :          0 :     }
#    1466                 :          0 : }
#    1467                 :            : 
#    1468                 :            : bool LegacyScriptPubKeyMan::AddCScript(const CScript& redeemScript)
#    1469                 :      20827 : {
#    1470                 :      20827 :     WalletBatch batch(m_storage.GetDatabase());
#    1471                 :      20827 :     return AddCScriptWithDB(batch, redeemScript);
#    1472                 :      20827 : }
#    1473                 :            : 
#    1474                 :            : bool LegacyScriptPubKeyMan::AddCScriptWithDB(WalletBatch& batch, const CScript& redeemScript)
#    1475                 :      20927 : {
#    1476         [ -  + ]:      20927 :     if (!FillableSigningProvider::AddCScript(redeemScript))
#    1477                 :          0 :         return false;
#    1478         [ +  + ]:      20927 :     if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
#    1479                 :      12088 :         m_storage.UnsetBlankWalletFlag(batch);
#    1480                 :      12088 :         return true;
#    1481                 :      12088 :     }
#    1482                 :       8839 :     return false;
#    1483                 :       8839 : }
#    1484                 :            : 
#    1485                 :            : bool LegacyScriptPubKeyMan::AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info)
#    1486                 :        156 : {
#    1487                 :        156 :     LOCK(cs_KeyStore);
#    1488                 :        156 :     std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
#    1489                 :        156 :     mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
#    1490                 :        156 :     mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
#    1491                 :        156 :     mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
#    1492                 :        156 :     return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
#    1493                 :        156 : }
#    1494                 :            : 
#    1495                 :            : bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
#    1496                 :       1273 : {
#    1497                 :       1273 :     WalletBatch batch(m_storage.GetDatabase());
#    1498         [ +  + ]:       1273 :     for (const auto& entry : scripts) {
#    1499                 :       1173 :         CScriptID id(entry);
#    1500         [ +  + ]:       1173 :         if (HaveCScript(id)) {
#    1501                 :       1073 :             WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
#    1502                 :       1073 :             continue;
#    1503                 :       1073 :         }
#    1504         [ -  + ]:        100 :         if (!AddCScriptWithDB(batch, entry)) {
#    1505                 :          0 :             return false;
#    1506                 :          0 :         }
#    1507                 :            : 
#    1508         [ +  + ]:        100 :         if (timestamp > 0) {
#    1509                 :         64 :             m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
#    1510                 :         64 :         }
#    1511                 :        100 :     }
#    1512         [ +  + ]:       1273 :     if (timestamp > 0) {
#    1513                 :        164 :         UpdateTimeFirstKey(timestamp);
#    1514                 :        164 :     }
#    1515                 :            : 
#    1516                 :       1273 :     return true;
#    1517                 :       1273 : }
#    1518                 :            : 
#    1519                 :            : bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
#    1520                 :       1231 : {
#    1521                 :       1231 :     WalletBatch batch(m_storage.GetDatabase());
#    1522         [ +  + ]:       1231 :     for (const auto& entry : privkey_map) {
#    1523                 :       1123 :         const CKey& key = entry.second;
#    1524                 :       1123 :         CPubKey pubkey = key.GetPubKey();
#    1525                 :       1123 :         const CKeyID& id = entry.first;
#    1526                 :       1123 :         assert(key.VerifyPubKey(pubkey));
#    1527                 :            :         // Skip if we already have the key
#    1528         [ +  + ]:       1123 :         if (HaveKey(id)) {
#    1529                 :          3 :             WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
#    1530                 :          3 :             continue;
#    1531                 :          3 :         }
#    1532                 :       1120 :         mapKeyMetadata[id].nCreateTime = timestamp;
#    1533                 :            :         // If the private key is not present in the wallet, insert it.
#    1534         [ -  + ]:       1120 :         if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
#    1535                 :          0 :             return false;
#    1536                 :          0 :         }
#    1537                 :       1120 :         UpdateTimeFirstKey(timestamp);
#    1538                 :       1120 :     }
#    1539                 :       1231 :     return true;
#    1540                 :       1231 : }
#    1541                 :            : 
#    1542                 :            : 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)
#    1543                 :        196 : {
#    1544                 :        196 :     WalletBatch batch(m_storage.GetDatabase());
#    1545         [ +  + ]:        196 :     for (const auto& entry : key_origins) {
#    1546                 :        156 :         AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
#    1547                 :        156 :     }
#    1548         [ +  + ]:        227 :     for (const CKeyID& id : ordered_pubkeys) {
#    1549                 :        227 :         auto entry = pubkey_map.find(id);
#    1550         [ +  + ]:        227 :         if (entry == pubkey_map.end()) {
#    1551                 :          2 :             continue;
#    1552                 :          2 :         }
#    1553                 :        225 :         const CPubKey& pubkey = entry->second;
#    1554                 :        225 :         CPubKey temp;
#    1555         [ +  + ]:        225 :         if (GetPubKey(id, temp)) {
#    1556                 :            :             // Already have pubkey, skipping
#    1557                 :          8 :             WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
#    1558                 :          8 :             continue;
#    1559                 :          8 :         }
#    1560         [ -  + ]:        217 :         if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
#    1561                 :          0 :             return false;
#    1562                 :          0 :         }
#    1563                 :        217 :         mapKeyMetadata[id].nCreateTime = timestamp;
#    1564                 :            : 
#    1565                 :            :         // Add to keypool only works with pubkeys
#    1566         [ +  + ]:        217 :         if (add_keypool) {
#    1567                 :        138 :             AddKeypoolPubkeyWithDB(pubkey, internal, batch);
#    1568                 :        138 :             NotifyCanGetAddressesChanged();
#    1569                 :        138 :         }
#    1570                 :        217 :     }
#    1571                 :        196 :     return true;
#    1572                 :        196 : }
#    1573                 :            : 
#    1574                 :            : bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
#    1575                 :        278 : {
#    1576                 :        278 :     WalletBatch batch(m_storage.GetDatabase());
#    1577         [ +  + ]:        506 :     for (const CScript& script : script_pub_keys) {
#    1578 [ +  + ][ +  + ]:        506 :         if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
#    1579         [ -  + ]:        455 :             if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
#    1580                 :          0 :                 return false;
#    1581                 :          0 :             }
#    1582                 :        455 :         }
#    1583                 :        506 :     }
#    1584                 :        278 :     return true;
#    1585                 :        278 : }
#    1586                 :            : 
#    1587                 :            : std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
#    1588                 :          6 : {
#    1589                 :          6 :     LOCK(cs_KeyStore);
#    1590         [ +  + ]:          6 :     if (!m_storage.HasEncryptionKeys()) {
#    1591                 :          5 :         return FillableSigningProvider::GetKeys();
#    1592                 :          5 :     }
#    1593                 :          1 :     std::set<CKeyID> set_address;
#    1594         [ +  + ]:        392 :     for (const auto& mi : mapCryptedKeys) {
#    1595                 :        392 :         set_address.insert(mi.first);
#    1596                 :        392 :     }
#    1597                 :          1 :     return set_address;
#    1598                 :          1 : }
#    1599                 :            : 
#    1600                 :          0 : void LegacyScriptPubKeyMan::SetInternal(bool internal) {}
#    1601                 :            : 
#    1602                 :            : bool DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error)
#    1603                 :       5418 : {
#    1604                 :            :     // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
#    1605         [ -  + ]:       5418 :     if (!CanGetAddresses(m_internal)) {
#    1606                 :          0 :         error = "No addresses available";
#    1607                 :          0 :         return false;
#    1608                 :          0 :     }
#    1609                 :       5418 :     {
#    1610                 :       5418 :         LOCK(cs_desc_man);
#    1611                 :       5418 :         assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
#    1612                 :       5418 :         std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
#    1613                 :       5418 :         assert(desc_addr_type);
#    1614         [ -  + ]:       5418 :         if (type != *desc_addr_type) {
#    1615                 :          0 :             throw std::runtime_error(std::string(__func__) + ": Types are inconsistent");
#    1616                 :          0 :         }
#    1617                 :            : 
#    1618                 :       5418 :         TopUp();
#    1619                 :            : 
#    1620                 :            :         // Get the scriptPubKey from the descriptor
#    1621                 :       5418 :         FlatSigningProvider out_keys;
#    1622                 :       5418 :         std::vector<CScript> scripts_temp;
#    1623 [ -  + ][ #  # ]:       5418 :         if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
#    1624                 :            :             // We can't generate anymore keys
#    1625                 :          0 :             error = "Error: Keypool ran out, please call keypoolrefill first";
#    1626                 :          0 :             return false;
#    1627                 :          0 :         }
#    1628         [ +  + ]:       5418 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
#    1629                 :            :             // We can't generate anymore keys
#    1630                 :          8 :             error = "Error: Keypool ran out, please call keypoolrefill first";
#    1631                 :          8 :             return false;
#    1632                 :          8 :         }
#    1633                 :            : 
#    1634                 :       5410 :         std::optional<OutputType> out_script_type = m_wallet_descriptor.descriptor->GetOutputType();
#    1635 [ +  - ][ +  - ]:       5410 :         if (out_script_type && out_script_type == type) {
#    1636                 :       5410 :             ExtractDestination(scripts_temp[0], dest);
#    1637                 :       5410 :         } else {
#    1638                 :          0 :             throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
#    1639                 :          0 :         }
#    1640                 :       5410 :         m_wallet_descriptor.next_index++;
#    1641                 :       5410 :         WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
#    1642                 :       5410 :         return true;
#    1643                 :       5410 :     }
#    1644                 :       5410 : }
#    1645                 :            : 
#    1646                 :            : isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
#    1647                 :    5138092 : {
#    1648                 :    5138092 :     LOCK(cs_desc_man);
#    1649         [ +  + ]:    5138092 :     if (m_map_script_pub_keys.count(script) > 0) {
#    1650                 :     511535 :         return ISMINE_SPENDABLE;
#    1651                 :     511535 :     }
#    1652                 :    4626557 :     return ISMINE_NO;
#    1653                 :    4626557 : }
#    1654                 :            : 
#    1655                 :            : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
#    1656                 :        457 : {
#    1657                 :        457 :     LOCK(cs_desc_man);
#    1658         [ -  + ]:        457 :     if (!m_map_keys.empty()) {
#    1659                 :          0 :         return false;
#    1660                 :          0 :     }
#    1661                 :            : 
#    1662                 :        457 :     bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
#    1663                 :        457 :     bool keyFail = false;
#    1664         [ +  + ]:        457 :     for (const auto& mi : m_map_crypted_keys) {
#    1665                 :        403 :         const CPubKey &pubkey = mi.second.first;
#    1666                 :        403 :         const std::vector<unsigned char> &crypted_secret = mi.second.second;
#    1667                 :        403 :         CKey key;
#    1668         [ -  + ]:        403 :         if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
#    1669                 :          0 :             keyFail = true;
#    1670                 :          0 :             break;
#    1671                 :          0 :         }
#    1672                 :        403 :         keyPass = true;
#    1673         [ +  + ]:        403 :         if (m_decryption_thoroughly_checked)
#    1674                 :        309 :             break;
#    1675                 :        403 :     }
#    1676 [ +  - ][ -  + ]:        457 :     if (keyPass && keyFail) {
#    1677                 :          0 :         LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
#    1678                 :          0 :         throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
#    1679                 :          0 :     }
#    1680 [ -  + ][ -  + ]:        457 :     if (keyFail || (!keyPass && !accept_no_keys)) {
#                 [ #  # ]
#    1681                 :          0 :         return false;
#    1682                 :          0 :     }
#    1683                 :        457 :     m_decryption_thoroughly_checked = true;
#    1684                 :        457 :     return true;
#    1685                 :        457 : }
#    1686                 :            : 
#    1687                 :            : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
#    1688                 :         47 : {
#    1689                 :         47 :     LOCK(cs_desc_man);
#    1690         [ -  + ]:         47 :     if (!m_map_crypted_keys.empty()) {
#    1691                 :          0 :         return false;
#    1692                 :          0 :     }
#    1693                 :            : 
#    1694         [ +  + ]:         47 :     for (const KeyMap::value_type& key_in : m_map_keys)
#    1695                 :         47 :     {
#    1696                 :         47 :         const CKey &key = key_in.second;
#    1697                 :         47 :         CPubKey pubkey = key.GetPubKey();
#    1698                 :         47 :         CKeyingMaterial secret(key.begin(), key.end());
#    1699                 :         47 :         std::vector<unsigned char> crypted_secret;
#    1700         [ -  + ]:         47 :         if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
#    1701                 :          0 :             return false;
#    1702                 :          0 :         }
#    1703                 :         47 :         m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
#    1704                 :         47 :         batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
#    1705                 :         47 :     }
#    1706                 :         47 :     m_map_keys.clear();
#    1707                 :         47 :     return true;
#    1708                 :         47 : }
#    1709                 :            : 
#    1710                 :            : bool DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool)
#    1711                 :       1881 : {
#    1712                 :       1881 :     LOCK(cs_desc_man);
#    1713                 :       1881 :     std::string error;
#    1714                 :       1881 :     bool result = GetNewDestination(type, address, error);
#    1715                 :       1881 :     index = m_wallet_descriptor.next_index - 1;
#    1716                 :       1881 :     return result;
#    1717                 :       1881 : }
#    1718                 :            : 
#    1719                 :            : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
#    1720                 :         58 : {
#    1721                 :         58 :     LOCK(cs_desc_man);
#    1722                 :            :     // Only return when the index was the most recent
#    1723         [ +  - ]:         58 :     if (m_wallet_descriptor.next_index - 1 == index) {
#    1724                 :         58 :         m_wallet_descriptor.next_index--;
#    1725                 :         58 :     }
#    1726                 :         58 :     WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
#    1727                 :         58 :     NotifyCanGetAddressesChanged();
#    1728                 :         58 : }
#    1729                 :            : 
#    1730                 :            : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
#    1731                 :      44439 : {
#    1732                 :      44439 :     AssertLockHeld(cs_desc_man);
#    1733 [ +  + ][ +  + ]:      44439 :     if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
#    1734                 :       3654 :         KeyMap keys;
#    1735         [ +  + ]:       3654 :         for (auto key_pair : m_map_crypted_keys) {
#    1736                 :       3654 :             const CPubKey& pubkey = key_pair.second.first;
#    1737                 :       3654 :             const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
#    1738                 :       3654 :             CKey key;
#    1739                 :       3654 :             DecryptKey(m_storage.GetEncryptionKey(), crypted_secret, pubkey, key);
#    1740                 :       3654 :             keys[pubkey.GetID()] = key;
#    1741                 :       3654 :         }
#    1742                 :       3654 :         return keys;
#    1743                 :       3654 :     }
#    1744                 :      40785 :     return m_map_keys;
#    1745                 :      40785 : }
#    1746                 :            : 
#    1747                 :            : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
#    1748                 :      37169 : {
#    1749                 :      37169 :     LOCK(cs_desc_man);
#    1750                 :      37169 :     unsigned int target_size;
#    1751         [ +  + ]:      37169 :     if (size > 0) {
#    1752                 :         30 :         target_size = size;
#    1753                 :      37139 :     } else {
#    1754                 :      37139 :         target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
#    1755                 :      37139 :     }
#    1756                 :            : 
#    1757                 :            :     // Calculate the new range_end
#    1758                 :      37169 :     int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
#    1759                 :            : 
#    1760                 :            :     // If the descriptor is not ranged, we actually just want to fill the first cache item
#    1761         [ +  + ]:      37169 :     if (!m_wallet_descriptor.descriptor->IsRange()) {
#    1762                 :       7182 :         new_range_end = 1;
#    1763                 :       7182 :         m_wallet_descriptor.range_end = 1;
#    1764                 :       7182 :         m_wallet_descriptor.range_start = 0;
#    1765                 :       7182 :     }
#    1766                 :            : 
#    1767                 :      37169 :     FlatSigningProvider provider;
#    1768                 :      37169 :     provider.keys = GetKeys();
#    1769                 :            : 
#    1770                 :      37169 :     WalletBatch batch(m_storage.GetDatabase());
#    1771                 :      37169 :     uint256 id = GetID();
#    1772         [ +  + ]:      69912 :     for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
#    1773                 :      32957 :         FlatSigningProvider out_keys;
#    1774                 :      32957 :         std::vector<CScript> scripts_temp;
#    1775                 :      32957 :         DescriptorCache temp_cache;
#    1776                 :            :         // Maybe we have a cached xpub and we can expand from the cache first
#    1777         [ +  + ]:      32957 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
#    1778         [ +  + ]:       1771 :             if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
#    1779                 :      32743 :         }
#    1780                 :            :         // Add all of the scriptPubKeys to the scriptPubKey set
#    1781         [ +  + ]:      33034 :         for (const CScript& script : scripts_temp) {
#    1782                 :      33034 :             m_map_script_pub_keys[script] = i;
#    1783                 :      33034 :         }
#    1784         [ +  + ]:      32743 :         for (const auto& pk_pair : out_keys.pubkeys) {
#    1785                 :      20697 :             const CPubKey& pubkey = pk_pair.second;
#    1786         [ -  + ]:      20697 :             if (m_map_pubkeys.count(pubkey) != 0) {
#    1787                 :            :                 // We don't need to give an error here.
#    1788                 :            :                 // 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
#    1789                 :          0 :                 continue;
#    1790                 :          0 :             }
#    1791                 :      20697 :             m_map_pubkeys[pubkey] = i;
#    1792                 :      20697 :         }
#    1793                 :            :         // Write the cache
#    1794         [ +  + ]:      32743 :         for (const auto& parent_xpub_pair : temp_cache.GetCachedParentExtPubKeys()) {
#    1795                 :        869 :             CExtPubKey xpub;
#    1796         [ -  + ]:        869 :             if (m_wallet_descriptor.cache.GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
#    1797         [ #  # ]:          0 :                 if (xpub != parent_xpub_pair.second) {
#    1798                 :          0 :                     throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
#    1799                 :          0 :                 }
#    1800                 :          0 :                 continue;
#    1801                 :          0 :             }
#    1802         [ -  + ]:        869 :             if (!batch.WriteDescriptorParentCache(parent_xpub_pair.second, id, parent_xpub_pair.first)) {
#    1803                 :          0 :                 throw std::runtime_error(std::string(__func__) + ": writing cache item failed");
#    1804                 :          0 :             }
#    1805                 :        869 :             m_wallet_descriptor.cache.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
#    1806                 :        869 :         }
#    1807         [ +  + ]:      32743 :         for (const auto& derived_xpub_map_pair : temp_cache.GetCachedDerivedExtPubKeys()) {
#    1808         [ +  + ]:        770 :             for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
#    1809                 :        770 :                 CExtPubKey xpub;
#    1810         [ -  + ]:        770 :                 if (m_wallet_descriptor.cache.GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
#    1811         [ #  # ]:          0 :                     if (xpub != derived_xpub_pair.second) {
#    1812                 :          0 :                         throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
#    1813                 :          0 :                     }
#    1814                 :          0 :                     continue;
#    1815                 :          0 :                 }
#    1816         [ -  + ]:        770 :                 if (!batch.WriteDescriptorDerivedCache(derived_xpub_pair.second, id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
#    1817                 :          0 :                     throw std::runtime_error(std::string(__func__) + ": writing cache item failed");
#    1818                 :          0 :                 }
#    1819                 :        770 :                 m_wallet_descriptor.cache.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
#    1820                 :        770 :             }
#    1821                 :        770 :         }
#    1822                 :      32743 :         m_max_cached_index++;
#    1823                 :      32743 :     }
#    1824                 :      37169 :     m_wallet_descriptor.range_end = new_range_end;
#    1825                 :      36955 :     batch.WriteDescriptor(GetID(), m_wallet_descriptor);
#    1826                 :            : 
#    1827                 :            :     // By this point, the cache size should be the size of the entire range
#    1828                 :      36955 :     assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
#    1829                 :            : 
#    1830                 :      36955 :     NotifyCanGetAddressesChanged();
#    1831                 :      36955 :     return true;
#    1832                 :      37169 : }
#    1833                 :            : 
#    1834                 :            : void DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
#    1835                 :     435348 : {
#    1836                 :     435348 :     LOCK(cs_desc_man);
#    1837         [ +  + ]:     435348 :     if (IsMine(script)) {
#    1838                 :      23959 :         int32_t index = m_map_script_pub_keys[script];
#    1839         [ +  + ]:      23959 :         if (index >= m_wallet_descriptor.next_index) {
#    1840                 :        136 :             WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
#    1841                 :        136 :             m_wallet_descriptor.next_index = index + 1;
#    1842                 :        136 :         }
#    1843         [ -  + ]:      23959 :         if (!TopUp()) {
#    1844                 :          0 :             WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
#    1845                 :          0 :         }
#    1846                 :      23959 :     }
#    1847                 :     435348 : }
#    1848                 :            : 
#    1849                 :            : void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
#    1850                 :        127 : {
#    1851                 :        127 :     LOCK(cs_desc_man);
#    1852                 :        127 :     WalletBatch batch(m_storage.GetDatabase());
#    1853         [ -  + ]:        127 :     if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
#    1854                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
#    1855                 :          0 :     }
#    1856                 :        127 : }
#    1857                 :            : 
#    1858                 :            : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
#    1859                 :        877 : {
#    1860                 :        877 :     AssertLockHeld(cs_desc_man);
#    1861                 :        877 :     assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
#    1862                 :            : 
#    1863         [ +  + ]:        877 :     if (m_storage.HasEncryptionKeys()) {
#    1864         [ -  + ]:         65 :         if (m_storage.IsLocked()) {
#    1865                 :          0 :             return false;
#    1866                 :          0 :         }
#    1867                 :            : 
#    1868                 :         65 :         std::vector<unsigned char> crypted_secret;
#    1869                 :         65 :         CKeyingMaterial secret(key.begin(), key.end());
#    1870         [ -  + ]:         65 :         if (!EncryptSecret(m_storage.GetEncryptionKey(), secret, pubkey.GetHash(), crypted_secret)) {
#    1871                 :          0 :             return false;
#    1872                 :          0 :         }
#    1873                 :            : 
#    1874                 :         65 :         m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
#    1875                 :         65 :         return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
#    1876                 :        812 :     } else {
#    1877                 :        812 :         m_map_keys[pubkey.GetID()] = key;
#    1878                 :        812 :         return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
#    1879                 :        812 :     }
#    1880                 :        877 : }
#    1881                 :            : 
#    1882                 :            : bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(const CExtKey& master_key, OutputType addr_type)
#    1883                 :        750 : {
#    1884                 :        750 :     LOCK(cs_desc_man);
#    1885                 :        750 :     assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
#    1886                 :            : 
#    1887                 :            :     // Ignore when there is already a descriptor
#    1888         [ -  + ]:        750 :     if (m_wallet_descriptor.descriptor) {
#    1889                 :          0 :         return false;
#    1890                 :          0 :     }
#    1891                 :            : 
#    1892                 :        750 :     int64_t creation_time = GetTime();
#    1893                 :            : 
#    1894                 :        750 :     std::string xpub = EncodeExtPubKey(master_key.Neuter());
#    1895                 :            : 
#    1896                 :            :     // Build descriptor string
#    1897                 :        750 :     std::string desc_prefix;
#    1898                 :        750 :     std::string desc_suffix = "/*)";
#    1899         [ -  + ]:        750 :     switch (addr_type) {
#    1900         [ +  + ]:        250 :     case OutputType::LEGACY: {
#    1901                 :        250 :         desc_prefix = "pkh(" + xpub + "/44'";
#    1902                 :        250 :         break;
#    1903                 :          0 :     }
#    1904         [ +  + ]:        250 :     case OutputType::P2SH_SEGWIT: {
#    1905                 :        250 :         desc_prefix = "sh(wpkh(" + xpub + "/49'";
#    1906                 :        250 :         desc_suffix += ")";
#    1907                 :        250 :         break;
#    1908                 :          0 :     }
#    1909         [ +  + ]:        250 :     case OutputType::BECH32: {
#    1910                 :        250 :         desc_prefix = "wpkh(" + xpub + "/84'";
#    1911                 :        250 :         break;
#    1912                 :        750 :     }
#    1913                 :        750 :     } // no default case, so the compiler can warn about missing cases
#    1914                 :        750 :     assert(!desc_prefix.empty());
#    1915                 :            : 
#    1916                 :            :     // Mainnet derives at 0', testnet and regtest derive at 1'
#    1917         [ +  - ]:        750 :     if (Params().IsTestChain()) {
#    1918                 :        750 :         desc_prefix += "/1'";
#    1919                 :        750 :     } else {
#    1920                 :          0 :         desc_prefix += "/0'";
#    1921                 :          0 :     }
#    1922                 :            : 
#    1923         [ +  + ]:        750 :     std::string internal_path = m_internal ? "/1" : "/0";
#    1924                 :        750 :     std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
#    1925                 :            : 
#    1926                 :            :     // Make the descriptor
#    1927                 :        750 :     FlatSigningProvider keys;
#    1928                 :        750 :     std::string error;
#    1929                 :        750 :     std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
#    1930                 :        750 :     WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
#    1931                 :        750 :     m_wallet_descriptor = w_desc;
#    1932                 :            : 
#    1933                 :            :     // Store the master private key, and descriptor
#    1934                 :        750 :     WalletBatch batch(m_storage.GetDatabase());
#    1935         [ -  + ]:        750 :     if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
#    1936                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
#    1937                 :          0 :     }
#    1938         [ -  + ]:        750 :     if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
#    1939                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
#    1940                 :          0 :     }
#    1941                 :            : 
#    1942                 :            :     // TopUp
#    1943                 :        750 :     TopUp();
#    1944                 :            : 
#    1945                 :        750 :     m_storage.UnsetBlankWalletFlag(batch);
#    1946                 :        750 :     return true;
#    1947                 :        750 : }
#    1948                 :            : 
#    1949                 :            : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
#    1950                 :         18 : {
#    1951                 :         18 :     LOCK(cs_desc_man);
#    1952                 :         18 :     return m_wallet_descriptor.descriptor->IsRange();
#    1953                 :         18 : }
#    1954                 :            : 
#    1955                 :            : bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
#    1956                 :       9101 : {
#    1957                 :            :     // We can only give out addresses from descriptors that are single type (not combo), ranged,
#    1958                 :            :     // and either have cached keys or can generate more keys (ignoring encryption)
#    1959                 :       9101 :     LOCK(cs_desc_man);
#    1960         [ +  - ]:       9101 :     return m_wallet_descriptor.descriptor->IsSingleType() &&
#    1961         [ +  - ]:       9101 :            m_wallet_descriptor.descriptor->IsRange() &&
#    1962 [ +  + ][ +  - ]:       9101 :            (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
#    1963                 :       9101 : }
#    1964                 :            : 
#    1965                 :            : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
#    1966                 :     269884 : {
#    1967                 :     269884 :     LOCK(cs_desc_man);
#    1968 [ +  + ][ +  + ]:     269884 :     return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
#    1969                 :     269884 : }
#    1970                 :            : 
#    1971                 :            : int64_t DescriptorScriptPubKeyMan::GetOldestKeyPoolTime() const
#    1972                 :       1881 : {
#    1973                 :            :     // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
#    1974                 :            :     // The magic number 0 indicates that it shouldn't be displayed so that's what we return.
#    1975                 :       1881 :     return 0;
#    1976                 :       1881 : }
#    1977                 :            : 
#    1978                 :            : size_t DescriptorScriptPubKeyMan::KeypoolCountExternalKeys() const
#    1979                 :       1503 : {
#    1980         [ +  + ]:       1503 :     if (m_internal) {
#    1981                 :        741 :         return 0;
#    1982                 :        741 :     }
#    1983                 :        762 :     return GetKeyPoolSize();
#    1984                 :        762 : }
#    1985                 :            : 
#    1986                 :            : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
#    1987                 :       3561 : {
#    1988                 :       3561 :     LOCK(cs_desc_man);
#    1989                 :       3561 :     return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
#    1990                 :       3561 : }
#    1991                 :            : 
#    1992                 :            : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
#    1993                 :        232 : {
#    1994                 :        232 :     LOCK(cs_desc_man);
#    1995                 :        232 :     return m_wallet_descriptor.creation_time;
#    1996                 :        232 : }
#    1997                 :            : 
#    1998                 :            : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
#    1999                 :     302970 : {
#    2000                 :     302970 :     LOCK(cs_desc_man);
#    2001                 :            : 
#    2002                 :            :     // Find the index of the script
#    2003                 :     302970 :     auto it = m_map_script_pub_keys.find(script);
#    2004         [ +  + ]:     302970 :     if (it == m_map_script_pub_keys.end()) {
#    2005                 :      42212 :         return nullptr;
#    2006                 :      42212 :     }
#    2007                 :     260758 :     int32_t index = it->second;
#    2008                 :            : 
#    2009                 :     260758 :     return GetSigningProvider(index, include_private);
#    2010                 :     260758 : }
#    2011                 :            : 
#    2012                 :            : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
#    2013                 :        931 : {
#    2014                 :        931 :     LOCK(cs_desc_man);
#    2015                 :            : 
#    2016                 :            :     // Find index of the pubkey
#    2017                 :        931 :     auto it = m_map_pubkeys.find(pubkey);
#    2018         [ +  + ]:        931 :     if (it == m_map_pubkeys.end()) {
#    2019                 :        909 :         return nullptr;
#    2020                 :        909 :     }
#    2021                 :         22 :     int32_t index = it->second;
#    2022                 :            : 
#    2023                 :            :     // Always try to get the signing provider with private keys. This function should only be called during signing anyways
#    2024                 :         22 :     return GetSigningProvider(index, true);
#    2025                 :         22 : }
#    2026                 :            : 
#    2027                 :            : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
#    2028                 :     260780 : {
#    2029                 :     260780 :     AssertLockHeld(cs_desc_man);
#    2030                 :            :     // Get the scripts, keys, and key origins for this script
#    2031                 :     260780 :     std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
#    2032                 :     260780 :     std::vector<CScript> scripts_temp;
#    2033         [ -  + ]:     260780 :     if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
#    2034                 :            : 
#    2035 [ +  + ][ +  + ]:     260780 :     if (HavePrivateKeys() && include_private) {
#    2036                 :       6953 :         FlatSigningProvider master_provider;
#    2037                 :       6953 :         master_provider.keys = GetKeys();
#    2038                 :       6953 :         m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
#    2039                 :       6953 :     }
#    2040                 :            : 
#    2041                 :     260780 :     return out_keys;
#    2042                 :     260780 : }
#    2043                 :            : 
#    2044                 :            : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
#    2045                 :     255121 : {
#    2046                 :     255121 :     return GetSigningProvider(script, false);
#    2047                 :     255121 : }
#    2048                 :            : 
#    2049                 :            : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
#    2050                 :    1258569 : {
#    2051                 :    1258569 :     return IsMine(script);
#    2052                 :    1258569 : }
#    2053                 :            : 
#    2054                 :            : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
#    2055                 :       9894 : {
#    2056                 :       9894 :     std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
#    2057         [ +  + ]:      46060 :     for (const auto& coin_pair : coins) {
#    2058                 :      46060 :         std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
#    2059         [ +  + ]:      46060 :         if (!coin_keys) {
#    2060                 :      39182 :             continue;
#    2061                 :      39182 :         }
#    2062                 :       6878 :         *keys = Merge(*keys, *coin_keys);
#    2063                 :       6878 :     }
#    2064                 :            : 
#    2065                 :       9894 :     return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
#    2066                 :       9894 : }
#    2067                 :            : 
#    2068                 :            : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
#    2069                 :          5 : {
#    2070                 :          5 :     std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
#    2071         [ -  + ]:          5 :     if (!keys) {
#    2072                 :          0 :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
#    2073                 :          0 :     }
#    2074                 :            : 
#    2075                 :          5 :     CKey key;
#    2076         [ -  + ]:          5 :     if (!keys->GetKey(ToKeyID(pkhash), key)) {
#    2077                 :          0 :         return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
#    2078                 :          0 :     }
#    2079                 :            : 
#    2080         [ -  + ]:          5 :     if (!MessageSign(key, message, str_sig)) {
#    2081                 :          0 :         return SigningResult::SIGNING_FAILED;
#    2082                 :          0 :     }
#    2083                 :          5 :     return SigningResult::OK;
#    2084                 :          5 : }
#    2085                 :            : 
#    2086                 :            : TransactionError DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, int sighash_type, bool sign, bool bip32derivs, int* n_signed) const
#    2087                 :       1168 : {
#    2088         [ +  - ]:       1168 :     if (n_signed) {
#    2089                 :       1168 :         *n_signed = 0;
#    2090                 :       1168 :     }
#    2091         [ +  + ]:       2819 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
#    2092                 :       1652 :         const CTxIn& txin = psbtx.tx->vin[i];
#    2093                 :       1652 :         PSBTInput& input = psbtx.inputs.at(i);
#    2094                 :            : 
#    2095         [ +  + ]:       1652 :         if (PSBTInputSigned(input)) {
#    2096                 :        131 :             continue;
#    2097                 :        131 :         }
#    2098                 :            : 
#    2099                 :            :         // Get the Sighash type
#    2100 [ +  + ][ +  + ]:       1521 :         if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
#                 [ -  + ]
#    2101                 :          0 :             return TransactionError::SIGHASH_MISMATCH;
#    2102                 :          0 :         }
#    2103                 :            : 
#    2104                 :            :         // Get the scriptPubKey to know which SigningProvider to use
#    2105                 :       1521 :         CScript script;
#    2106         [ +  + ]:       1521 :         if (!input.witness_utxo.IsNull()) {
#    2107                 :        600 :             script = input.witness_utxo.scriptPubKey;
#    2108         [ +  + ]:        921 :         } else if (input.non_witness_utxo) {
#    2109         [ +  + ]:        872 :             if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
#    2110                 :          1 :                 return TransactionError::MISSING_INPUTS;
#    2111                 :          1 :             }
#    2112                 :        871 :             script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
#    2113                 :        871 :         } else {
#    2114                 :            :             // There's no UTXO so we can just skip this now
#    2115                 :         49 :             continue;
#    2116                 :         49 :         }
#    2117                 :       1471 :         SignatureData sigdata;
#    2118                 :       1471 :         input.FillSignatureData(sigdata);
#    2119                 :            : 
#    2120                 :       1471 :         std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
#    2121                 :       1471 :         std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, sign);
#    2122         [ +  + ]:       1471 :         if (script_keys) {
#    2123                 :        213 :             *keys = Merge(*keys, *script_keys);
#    2124                 :       1258 :         } else {
#    2125                 :            :             // Maybe there are pubkeys listed that we can sign for
#    2126                 :       1258 :             script_keys = std::make_unique<FlatSigningProvider>();
#    2127         [ +  + ]:       1258 :             for (const auto& pk_pair : input.hd_keypaths) {
#    2128                 :        931 :                 const CPubKey& pubkey = pk_pair.first;
#    2129                 :        931 :                 std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
#    2130         [ +  + ]:        931 :                 if (pk_keys) {
#    2131                 :         22 :                     *keys = Merge(*keys, *pk_keys);
#    2132                 :         22 :                 }
#    2133                 :        931 :             }
#    2134                 :       1258 :         }
#    2135                 :            : 
#    2136                 :       1471 :         SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs), psbtx, i, sighash_type);
#    2137                 :            : 
#    2138                 :       1471 :         bool signed_one = PSBTInputSigned(input);
#    2139 [ +  - ][ +  + ]:       1471 :         if (n_signed && (signed_one || !sign)) {
#                 [ +  + ]
#    2140                 :            :             // If sign is false, we assume that we _could_ sign if we get here. This
#    2141                 :            :             // will never have false negatives; it is hard to tell under what i
#    2142                 :            :             // circumstances it could have false positives.
#    2143                 :       1093 :             (*n_signed)++;
#    2144                 :       1093 :         }
#    2145                 :       1471 :     }
#    2146                 :            : 
#    2147                 :            :     // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
#    2148         [ +  + ]:       3107 :     for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
#    2149                 :       1940 :         std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
#    2150         [ +  + ]:       1940 :         if (!keys) {
#    2151                 :       1772 :             continue;
#    2152                 :       1772 :         }
#    2153                 :        168 :         UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs), psbtx, i);
#    2154                 :        168 :     }
#    2155                 :            : 
#    2156                 :       1167 :     return TransactionError::OK;
#    2157                 :       1168 : }
#    2158                 :            : 
#    2159                 :            : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
#    2160                 :        313 : {
#    2161                 :        313 :     std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
#    2162         [ +  - ]:        313 :     if (provider) {
#    2163                 :        313 :         KeyOriginInfo orig;
#    2164                 :        313 :         CKeyID key_id = GetKeyForDestination(*provider, dest);
#    2165         [ +  + ]:        313 :         if (provider->GetKeyOrigin(key_id, orig)) {
#    2166                 :        312 :             LOCK(cs_desc_man);
#    2167                 :        312 :             std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
#    2168                 :        312 :             meta->key_origin = orig;
#    2169                 :        312 :             meta->has_key_origin = true;
#    2170                 :        312 :             meta->nCreateTime = m_wallet_descriptor.creation_time;
#    2171                 :        312 :             return meta;
#    2172                 :        312 :         }
#    2173                 :          1 :     }
#    2174                 :          1 :     return nullptr;
#    2175                 :          1 : }
#    2176                 :            : 
#    2177                 :            : uint256 DescriptorScriptPubKeyMan::GetID() const
#    2178                 :      82451 : {
#    2179                 :      82451 :     LOCK(cs_desc_man);
#    2180                 :      82451 :     std::string desc_str = m_wallet_descriptor.descriptor->ToString();
#    2181                 :      82451 :     uint256 id;
#    2182                 :      82451 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
#    2183                 :      82451 :     return id;
#    2184                 :      82451 : }
#    2185                 :            : 
#    2186                 :            : void DescriptorScriptPubKeyMan::SetInternal(bool internal)
#    2187                 :       1394 : {
#    2188                 :       1394 :     this->m_internal = internal;
#    2189                 :       1394 : }
#    2190                 :            : 
#    2191                 :            : void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
#    2192                 :        776 : {
#    2193                 :        776 :     LOCK(cs_desc_man);
#    2194                 :        776 :     m_wallet_descriptor.cache = cache;
#    2195         [ +  + ]:      16091 :     for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
#    2196                 :      15315 :         FlatSigningProvider out_keys;
#    2197                 :      15315 :         std::vector<CScript> scripts_temp;
#    2198         [ -  + ]:      15315 :         if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
#    2199                 :          0 :             throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
#    2200                 :          0 :         }
#    2201                 :            :         // Add all of the scriptPubKeys to the scriptPubKey set
#    2202         [ +  + ]:      15480 :         for (const CScript& script : scripts_temp) {
#    2203         [ -  + ]:      15480 :             if (m_map_script_pub_keys.count(script) != 0) {
#    2204                 :          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]));
#    2205                 :          0 :             }
#    2206                 :      15480 :             m_map_script_pub_keys[script] = i;
#    2207                 :      15480 :         }
#    2208         [ +  + ]:      15315 :         for (const auto& pk_pair : out_keys.pubkeys) {
#    2209                 :      13235 :             const CPubKey& pubkey = pk_pair.second;
#    2210         [ -  + ]:      13235 :             if (m_map_pubkeys.count(pubkey) != 0) {
#    2211                 :            :                 // We don't need to give an error here.
#    2212                 :            :                 // 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
#    2213                 :          0 :                 continue;
#    2214                 :          0 :             }
#    2215                 :      13235 :             m_map_pubkeys[pubkey] = i;
#    2216                 :      13235 :         }
#    2217                 :      15315 :         m_max_cached_index++;
#    2218                 :      15315 :     }
#    2219                 :        776 : }
#    2220                 :            : 
#    2221                 :            : bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
#    2222                 :        613 : {
#    2223                 :        613 :     LOCK(cs_desc_man);
#    2224                 :        613 :     m_map_keys[key_id] = key;
#    2225                 :        613 :     return true;
#    2226                 :        613 : }
#    2227                 :            : 
#    2228                 :            : bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
#    2229                 :         76 : {
#    2230                 :         76 :     LOCK(cs_desc_man);
#    2231         [ -  + ]:         76 :     if (!m_map_keys.empty()) {
#    2232                 :          0 :         return false;
#    2233                 :          0 :     }
#    2234                 :            : 
#    2235                 :         76 :     m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
#    2236                 :         76 :     return true;
#    2237                 :         76 : }
#    2238                 :            : 
#    2239                 :            : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
#    2240                 :       1796 : {
#    2241                 :       1796 :     LOCK(cs_desc_man);
#    2242 [ +  - ][ +  - ]:       1796 :     return m_wallet_descriptor.descriptor != nullptr && desc.descriptor != nullptr && m_wallet_descriptor.descriptor->ToString() == desc.descriptor->ToString();
#                 [ +  + ]
#    2243                 :       1796 : }
#    2244                 :            : 
#    2245                 :            : void DescriptorScriptPubKeyMan::WriteDescriptor()
#    2246                 :        190 : {
#    2247                 :        190 :     LOCK(cs_desc_man);
#    2248                 :        190 :     WalletBatch batch(m_storage.GetDatabase());
#    2249         [ -  + ]:        190 :     if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
#    2250                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
#    2251                 :          0 :     }
#    2252                 :        190 : }
#    2253                 :            : 
#    2254                 :            : const WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
#    2255                 :         34 : {
#    2256                 :         34 :     return m_wallet_descriptor;
#    2257                 :         34 : }
#    2258                 :            : 
#    2259                 :            : const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
#    2260                 :        143 : {
#    2261                 :        143 :     LOCK(cs_desc_man);
#    2262                 :        143 :     std::vector<CScript> script_pub_keys;
#    2263                 :        143 :     script_pub_keys.reserve(m_map_script_pub_keys.size());
#    2264                 :            : 
#    2265         [ +  + ]:        434 :     for (auto const& script_pub_key: m_map_script_pub_keys) {
#    2266                 :        434 :         script_pub_keys.push_back(script_pub_key.first);
#    2267                 :        434 :     }
#    2268                 :        143 :     return script_pub_keys;
#    2269                 :        143 : }
#    2270                 :            : 
#    2271                 :            : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, bool priv) const
#    2272                 :        321 : {
#    2273                 :        321 :     LOCK(cs_desc_man);
#    2274         [ +  + ]:        321 :     if (m_storage.IsLocked()) {
#    2275                 :          4 :         return false;
#    2276                 :          4 :     }
#    2277                 :            : 
#    2278                 :        317 :     FlatSigningProvider provider;
#    2279                 :        317 :     provider.keys = GetKeys();
#    2280                 :            : 
#    2281                 :        317 :     return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, priv);
#    2282                 :        317 : }

Generated by: LCOV version 1.14