LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.cpp (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 800 1921 41.6 %
Date: 2026-06-25 07:23:51 Functions: 86 151 57.0 %

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

Generated by: LCOV version 1.16