LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.h (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 42 72 58.3 %
Date: 2026-06-25 07:23:51 Functions: 31 70 44.3 %

          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             : #ifndef BITCOIN_WALLET_SCRIPTPUBKEYMAN_H
       6             : #define BITCOIN_WALLET_SCRIPTPUBKEYMAN_H
       7             : 
       8             : #include <outputtype.h>
       9             : #include <psbt.h>
      10             : #include <script/descriptor.h>
      11             : #include <script/signingprovider.h>
      12             : #include <script/standard.h>
      13             : #include <util/error.h>
      14             : #include <util/message.h>
      15             : #include <util/result.h>
      16             : #include <util/time.h>
      17             : #include <wallet/crypter.h>
      18             : #include <wallet/hdchain.h>
      19             : #include <wallet/ismine.h>
      20             : #include <wallet/walletdb.h>
      21             : #include <wallet/walletutil.h>
      22             : 
      23             : #include <boost/signals2/signal.hpp>
      24             : 
      25             : #include <functional>
      26             : #include <optional>
      27             : 
      28             : namespace wallet {
      29             : // Wallet storage things that ScriptPubKeyMans need in order to be able to store things to the wallet database.
      30             : // It provides access to things that are part of the entire wallet and not specific to a ScriptPubKeyMan such as
      31             : // wallet flags, wallet version, encryption keys, encryption status, and the database itself. This allows a
      32             : // ScriptPubKeyMan to have callbacks into CWallet without causing a circular dependency.
      33             : // WalletStorage should be the same for all ScriptPubKeyMans of a wallet.
      34             : class WalletStorage
      35             : {
      36             : public:
      37          68 :     virtual ~WalletStorage() = default;
      38             :     virtual std::string GetDisplayName() const = 0;
      39             :     virtual WalletDatabase& GetDatabase() const = 0;
      40             :     virtual bool IsWalletFlagSet(uint64_t) const = 0;
      41             :     virtual void UnsetBlankWalletFlag(WalletBatch&) = 0;
      42             :     virtual bool CanSupportFeature(enum WalletFeature) const = 0;
      43             :     virtual void SetMinVersion(enum WalletFeature, WalletBatch* = nullptr) = 0;
      44             :     //! Pass the encryption key to cb().
      45             :     virtual bool WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const = 0;
      46             :     virtual bool HasEncryptionKeys() const = 0;
      47             :     virtual bool IsLocked(bool fForMixing) const = 0;
      48             : 
      49             :     // for LegacyScriptPubKeyMan::TopUpInner needs:
      50             :     virtual void UpdateProgress(const std::string&, int) = 0;
      51             : 
      52             :     // methods below are unique from Dash due to different implementation of HD
      53             :     virtual void NewKeyPoolCallback() = 0;
      54             :     virtual void KeepDestinationCallback(bool erased) = 0;
      55             : };
      56             : 
      57             : //! Default for -keypool
      58             : static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
      59             : 
      60             : std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider);
      61             : 
      62             : /** A key from a CWallet's keypool
      63             :  *
      64             :  * The wallet holds several keypools. These are sets of keys that have not
      65             :  * yet been used to provide addresses or receive change.
      66             :  *
      67             :  * The Bitcoin Core wallet was originally a collection of unrelated private
      68             :  * keys with their associated addresses. If a non-HD wallet generated a
      69             :  * key/address, gave that address out and then restored a backup from before
      70             :  * that key's generation, then any funds sent to that address would be
      71             :  * lost definitively.
      72             :  *
      73             :  * The keypool was implemented to avoid this scenario (commit: 10384941). The
      74             :  * wallet would generate a set of keys (100 by default). When a new public key
      75             :  * was required, either to give out as an address or to use in a change output,
      76             :  * it would be drawn from the keypool. The keypool would then be topped up to
      77             :  * maintain 100 keys. This ensured that as long as the wallet hadn't used more
      78             :  * than 100 keys since the previous backup, all funds would be safe, since a
      79             :  * restored wallet would be able to scan for all owned addresses.
      80             :  *
      81             :  * A keypool also allowed encrypted wallets to give out addresses without
      82             :  * having to be decrypted to generate a new private key.
      83             :  *
      84             :  * With the introduction of HD wallets (commit: f1902510), the keypool
      85             :  * essentially became an address look-ahead pool. Restoring old backups can no
      86             :  * longer definitively lose funds as long as the addresses used were from the
      87             :  * wallet's HD seed (since all private keys can be rederived from the seed).
      88             :  * However, if many addresses were used since the backup, then the wallet may
      89             :  * not know how far ahead in the HD chain to look for its addresses. The
      90             :  * keypool is used to implement a 'gap limit'. The keypool maintains a set of
      91             :  * keys (by default 1000) ahead of the last used key and scans for the
      92             :  * addresses of those keys.  This avoids the risk of not seeing transactions
      93             :  * involving the wallet's addresses, or of re-using the same address.
      94             :  * In the unlikely case where none of the addresses in the `gap limit` are
      95             :  * used on-chain, the look-ahead will not be incremented to keep
      96             :  * a constant size and addresses beyond this range will not be detected by an
      97             :  * old backup. For this reason, it is not recommended to decrease keypool size
      98             :  * lower than default value.
      99             :  *
     100             :  * There is an external keypool (for addresses to hand out) and an internal keypool
     101             :  * (for change addresses).
     102             :  *
     103             :  * Keypool keys are stored in the wallet/keystore's keymap. The keypool data is
     104             :  * stored as sets of indexes in the wallet (setInternalKeyPool and
     105             :  * setExternalKeyPool), and a map from the key to the
     106             :  * index (m_pool_key_to_index). The CKeyPool object is used to
     107             :  * serialize/deserialize the pool data to/from the database.
     108             :  */
     109             : class CKeyPool
     110             : {
     111             : public:
     112             :     //! The time at which the key was generated. Set in AddKeypoolPubKeyWithDB
     113             :     int64_t nTime;
     114             :     //! The public key
     115             :     CPubKey vchPubKey;
     116             :     //! Whether this keypool entry is in the internal keypool (for change outputs)
     117             :     bool fInternal;
     118             : 
     119             :     CKeyPool();
     120             :     CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn);
     121             : 
     122             :     template<typename Stream>
     123        9389 :     void Serialize(Stream& s) const
     124             :     {
     125        9389 :         int nVersion = s.GetVersion();
     126        9389 :         if (!(s.GetType() & SER_GETHASH)) {
     127        9389 :             s << nVersion;
     128        9389 :         }
     129        9389 :         s << nTime << vchPubKey << fInternal;
     130        9389 :     }
     131             : 
     132             :     template<typename Stream>
     133        6460 :     void Unserialize(Stream& s)
     134             :     {
     135        6460 :         int nVersion = s.GetVersion();
     136        6460 :         if (!(s.GetType() & SER_GETHASH)) {
     137        6460 :             s >> nVersion;
     138        6460 :         }
     139        6460 :         s >> nTime >> vchPubKey;
     140             :         try {
     141        6460 :             s >> fInternal;
     142        6460 :         } catch (std::ios_base::failure&) {
     143             :             /* flag as external address if we can't read the internal boolean
     144             :                (this will be the case for any wallet before the HD chain split version) */
     145           0 :             fInternal = false;
     146           0 :         }
     147        6460 :     }
     148             : };
     149             : 
     150             : struct WalletDestination
     151             : {
     152             :     CTxDestination dest;
     153             :     std::optional<bool> internal;
     154             : };
     155             : 
     156             : enum class PathDerivationType
     157             : {
     158             :     BIP44_External,
     159             :     BIP44_Internal,
     160             :     DIP0009_CoinJoin,
     161             : };
     162             : 
     163             : /*
     164             :  * A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet.
     165             :  * It contains the scripts and keys related to the scriptPubKeys it manages.
     166             :  * A ScriptPubKeyMan will be able to give out scriptPubKeys to be used, as well as marking
     167             :  * when a scriptPubKey has been used. It also handles when and how to store a scriptPubKey
     168             :  * and its related scripts and keys, including encryption.
     169             :  */
     170             : class ScriptPubKeyMan
     171             : {
     172             : protected:
     173             :     WalletStorage& m_storage;
     174             : 
     175             : public:
     176         109 :     explicit ScriptPubKeyMan(WalletStorage& storage) : m_storage(storage) {}
     177             : 
     178         109 :     virtual ~ScriptPubKeyMan() {};
     179           0 :     virtual util::Result<CTxDestination> GetNewDestination() { return util::Error{Untranslated("Not supported")}; }
     180           0 :     virtual isminetype IsMine(const CScript& script) const { return ISMINE_NO; }
     181           0 :     virtual isminetype IsMine(const CTxDestination& dest) const { return ISMINE_NO; }
     182             : 
     183             :     //! Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the keys handled by it.
     184           0 :     virtual bool CheckDecryptionKey(const CKeyingMaterial& master_key) { return false; }
     185           0 :     virtual bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) { return false; }
     186             : 
     187           0 :     virtual util::Result<CTxDestination> GetReservedDestination(bool internal, int64_t& index, CKeyPool& keypool) { return util::Error{Untranslated("Not supported")}; }
     188          12 :     virtual void KeepDestination(int64_t index) {}
     189           0 :     virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) {}
     190             : 
     191             :     /** Fills internal address pool. Use within ScriptPubKeyMan implementations should be used sparingly and only
     192             :       * when something from the address pool is removed, excluding GetNewDestination and GetReservedDestination.
     193             :       * External wallet code is primarily responsible for topping up prior to fetching new addresses
     194             :       */
     195           0 :     virtual bool TopUp(unsigned int size = 0) { return false; }
     196             : 
     197             :     /** Mark unused addresses as being used
     198             :      * Affects all keys up to and including the one determined by provided script.
     199             :      *
     200             :      * @param script determines the last key to mark as used
     201             :      *
     202             :      * @return All of the addresses affected
     203             :      */
     204           0 :     virtual std::vector<WalletDestination> MarkUnusedAddresses(WalletBatch &batch, const CScript& script, const std::optional<int64_t>& block_time) { return {}; }
     205             : 
     206             :     /* Returns true if HD is enabled */
     207           0 :     virtual bool IsHDEnabled() const { return false; }
     208             : 
     209             :     /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
     210           0 :     virtual bool CanGetAddresses(bool internal = false) const { return false; }
     211             : 
     212           0 :     virtual bool HavePrivateKeys() const { return false; }
     213             : 
     214             :     //! The action to do when the DB needs rewrite
     215           0 :     virtual void RewriteDB() {}
     216             : 
     217           0 :     virtual std::optional<int64_t> GetOldestKeyPoolTime() const { return GetTime(); }
     218             : 
     219           0 :     virtual unsigned int GetKeyPoolSize() const { return 0; }
     220             : 
     221           0 :     virtual int64_t GetTimeFirstKey() const { return 0; }
     222             : 
     223           0 :     virtual std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const { return nullptr; }
     224             : 
     225           0 :     virtual std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const { return nullptr; }
     226             : 
     227             :     /** Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that, combined with
     228             :       * sigdata, can produce solving data.
     229             :       */
     230           0 :     virtual bool CanProvide(const CScript& script, SignatureData& sigdata) { return false; }
     231             : 
     232             :     /** Creates new signatures and adds them to the transaction. Returns whether all inputs were signed */
     233           0 :     virtual bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const { return false; }
     234             :     /** Sign a message with the given script */
     235           0 :     virtual SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const { return SigningResult::SIGNING_FAILED; };
     236           0 :     virtual bool SignSpecialTxPayload(const uint256& hash, const CKeyID& keyid, std::vector<unsigned char>& vchSig) const { return false; }
     237             :     /** Adds script and derivation path information to a PSBT, and optionally signs it. */
     238           0 :     virtual TransactionError FillPSBT(PartiallySignedTransaction& psbt, const PrecomputedTransactionData& txdata, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false, int* n_signed = nullptr, bool finalize = true) const { return TransactionError::INVALID_PSBT; }
     239             : 
     240           0 :     virtual uint256 GetID() const { return uint256(); }
     241             : 
     242             :     /** Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches */
     243           0 :     virtual std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys() const { return {}; };
     244             : 
     245             :     /** Prepends the wallet name in logging output to ease debugging in multi-wallet use cases */
     246             :     template<typename... Params>
     247       25704 :     void WalletLogPrintf(std::string fmt, Params... parameters) const {
     248       25704 :         LogPrintf(("%s " + fmt).c_str(), m_storage.GetDisplayName(), parameters...);
     249       25704 :     };
     250             : 
     251             :     /** Watch-only address added */
     252             :     boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
     253             : 
     254             :     /** Keypool has new keys */
     255             :     boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
     256             : };
     257             : 
     258             : class DescriptorScriptPubKeyMan;
     259             : 
     260             : class LegacyScriptPubKeyMan : public ScriptPubKeyMan, public FillableSigningProvider
     261             : {
     262             : private:
     263             :     //! keeps track of whether Unlock has run a thorough check before
     264          21 :     bool fDecryptionThoroughlyChecked = true;
     265             : 
     266             :     using WatchOnlySet = std::set<CScript>;
     267             :     using WatchKeyMap = std::map<CKeyID, CPubKey>;
     268             :     using HDPubKeyMap = std::map<CKeyID, CHDPubKey>;
     269             : 
     270             : 
     271          21 :     WalletBatch *encrypted_batch GUARDED_BY(cs_KeyStore) = nullptr;
     272             : 
     273             :     using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>;
     274             : 
     275             :     CryptedKeyMap mapCryptedKeys GUARDED_BY(cs_KeyStore);
     276             :     WatchOnlySet setWatchOnly GUARDED_BY(cs_KeyStore);
     277             :     WatchKeyMap mapWatchKeys GUARDED_BY(cs_KeyStore);
     278             :     HDPubKeyMap mapHdPubKeys GUARDED_BY(cs_KeyStore); ///<! memory map of HD extended pubkeys
     279             : 
     280          21 :     int64_t nTimeFirstKey GUARDED_BY(cs_KeyStore) = 0;
     281             : 
     282             :     bool HaveKeyInner(const CKeyID &address) const;
     283             :     bool AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey);
     284             :     bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
     285             :     bool GetKeyInner(const CKeyID &address, CKey& keyOut) const;
     286             :     bool GetPubKeyInner(const CKeyID &address, CPubKey& vchPubKeyOut) const;
     287             : 
     288             :     bool TopUpInner(unsigned int size = 0) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     289             :     /**
     290             :      * Private version of AddWatchOnly method which does not accept a
     291             :      * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
     292             :      * the watch key did not previously have a timestamp associated with it.
     293             :      * Because this is an inherited virtual method, it is accessible despite
     294             :      * being marked private, but it is marked private anyway to encourage use
     295             :      * of the other AddWatchOnly which accepts a timestamp and sets
     296             :      * nTimeFirstKey more intelligently for more efficient rescans.
     297             :      */
     298             :     bool AddWatchOnly(const CScript& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     299             :     bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     300             :     bool AddWatchOnlyInMem(const CScript &dest);
     301             : 
     302             :     void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch);
     303             : 
     304             :     /** Add a KeyOriginInfo to the wallet */
     305             :     bool AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info);
     306             : 
     307             :     bool EncryptHDChain(const CKeyingMaterial& vMasterKeyIn, CHDChain& chain);
     308             :     bool DecryptHDChain(const CKeyingMaterial& vMasterKeyIn, CHDChain& hdChainRet) const;
     309             : 
     310             :     /* the HD chain data model (external chain counters) */
     311             :     CHDChain m_hd_chain GUARDED_BY(cs_KeyStore);
     312             : 
     313             :     /* HD derive new child key (on internal or external chain) */
     314             :     void DeriveNewChildKey(WalletBatch& batch, CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     315             : 
     316             :     std::set<int64_t> setInternalKeyPool GUARDED_BY(cs_KeyStore);
     317             :     std::set<int64_t> setExternalKeyPool GUARDED_BY(cs_KeyStore);
     318          21 :     int64_t m_max_keypool_index GUARDED_BY(cs_KeyStore) = 0;
     319             :     std::map<CKeyID, int64_t> m_pool_key_to_index;
     320             :     // Tracks keypool indexes to CKeyIDs of keys that have been taken out of the keypool but may be returned to it
     321             :     std::map<int64_t, CKeyID> m_index_to_reserved_key;
     322             : 
     323             :     //! Fetches a key from the keypool
     324             :     bool GetKeyFromPool(CPubKey &key, bool fInternal /*= false*/);
     325             : 
     326             :     /**
     327             :      * Reserves a key from the keypool and sets nIndex to its index
     328             :      *
     329             :      * @param[out] nIndex the index of the key in keypool
     330             :      * @param[out] keypool the keypool the key was drawn from, which could be the
     331             :      *     the pre-split pool if present, or the internal or external pool
     332             :      * @param fRequestedInternal true if the caller would like the key drawn
     333             :      *     from the internal keypool, false if external is preferred
     334             :      *
     335             :      * @return true if succeeded, false if failed due to empty keypool
     336             :      * @throws std::runtime_error if keypool read failed, key was invalid,
     337             :      *     was not found in the wallet, or was misclassified in the internal
     338             :      *     or external keypool
     339             :      */
     340             :     bool ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
     341             : 
     342             : public:
     343          63 :     using ScriptPubKeyMan::ScriptPubKeyMan;
     344             : 
     345             :     util::Result<CTxDestination> GetNewDestination() override;
     346             :     isminetype IsMine(const CScript& script) const override;
     347             :     isminetype IsMine(const CTxDestination& dest) const override;
     348             : 
     349             :     bool CheckDecryptionKey(const CKeyingMaterial& master_key) override;
     350             :     bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
     351             : 
     352             :     util::Result<CTxDestination> GetReservedDestination(bool internal, int64_t& index, CKeyPool& keypool) override;
     353             :     void KeepDestination(int64_t index) override;
     354             :     void ReturnDestination(int64_t index, bool internal, const CTxDestination&) override;
     355             : 
     356             :     bool TopUp(unsigned int size = 0) override;
     357             : 
     358             :     std::vector<WalletDestination> MarkUnusedAddresses(WalletBatch &batch, const CScript& script, const std::optional<int64_t>& block_time) override;
     359             : 
     360             :     //! Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo
     361             :     void UpgradeKeyMetadata();
     362             : 
     363             :     /* Returns true if HD is enabled */
     364             :     bool IsHDEnabled() const override;
     365             : 
     366             :     bool HavePrivateKeys() const override;
     367             : 
     368             :     void RewriteDB() override;
     369             : 
     370             :     std::optional<int64_t> GetOldestKeyPoolTime() const override;
     371             :     size_t KeypoolCountExternalKeys() const;
     372             :     unsigned int GetKeyPoolSize() const override;
     373             : 
     374             :     int64_t GetTimeFirstKey() const override;
     375             : 
     376             :     std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const override;
     377             : 
     378             :     bool CanGetAddresses(bool internal = false) const override;
     379             : 
     380             :     std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const override;
     381             : 
     382             :     bool CanProvide(const CScript& script, SignatureData& sigdata) override;
     383             : 
     384             :     bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const override;
     385             :     SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const override;
     386             :     bool SignSpecialTxPayload(const uint256& hash, const CKeyID& keyid, std::vector<unsigned char>& vchSig) const override;
     387             :     TransactionError FillPSBT(PartiallySignedTransaction& psbt, const PrecomputedTransactionData& txdata, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false, int* n_signed = nullptr, bool finalize = true) const override;
     388             : 
     389             :     uint256 GetID() const override;
     390             : 
     391             :     // Map from Key ID to key metadata.
     392             :     std::map<CKeyID, CKeyMetadata> mapKeyMetadata GUARDED_BY(cs_KeyStore);
     393             : 
     394             :     // Map from Script ID to key metadata (for watch-only keys).
     395             :     std::map<CScriptID, CKeyMetadata> m_script_metadata GUARDED_BY(cs_KeyStore);
     396             : 
     397             :     //! Adds a script to the store and saves it to disk
     398             :     bool AddCScriptWithDB(WalletBatch& batch, const CScript& script);
     399             : 
     400             :     //! Adds a key to the store, and saves it to disk.
     401             :     bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     402             : 
     403             :     //! Adds a key to the store, and saves it to disk.
     404             :     bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
     405             :     //! Adds a key to the store, without saving it to disk (used by LoadWallet)
     406             :     bool LoadKey(const CKey& key, const CPubKey &pubkey);
     407             :     //! Adds an encrypted key to the store, and saves it to disk.
     408             :     bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
     409             :     //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
     410             :     bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid);
     411             :     void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     412             :     //! Adds a CScript to the store
     413             :     bool LoadCScript(const CScript& redeemScript);
     414             :     //! Load metadata (used by LoadWallet)
     415             :     void LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &metadata);
     416             :     bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, bool overwrite);
     417             :     void LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &metadata);
     418             :     //! Generate a new key
     419             :     CPubKey GenerateNewKey(WalletBatch& batch, uint32_t nAccountIndex, bool fInternal /*= false*/) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     420             : 
     421             :     /* Set the HD chain model (chain child index counters) and writes it to the database */
     422             :     bool AddHDChain(WalletBatch &batch, const CHDChain& chain);
     423             :     //! Load a HD chain model (used by LoadWallet)
     424             :     bool LoadHDChain(const CHDChain& chain, bool skip_encryption_check = false);
     425             :     /**
     426             :      * Set the HD chain model (chain child index counters) using temporary wallet db object
     427             :      * which causes db flush every time these methods are used
     428             :      */
     429             :     bool AddHDChainSingle(const CHDChain& chain);
     430             : 
     431             :     //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
     432             :     bool LoadWatchOnly(const CScript &dest);
     433             :     //! Returns whether the watch-only script is in the wallet
     434             :     bool HaveWatchOnly(const CScript &dest) const;
     435             :     //! Returns whether there are any watch-only things in the wallet
     436             :     bool HaveWatchOnly() const;
     437             :     //! Remove a watch only script from the keystore
     438             :     bool RemoveWatchOnly(const CScript &dest);
     439             :     //! Adds a watch-only address to the store, and saves it to disk.
     440             :     bool AddWatchOnly(const CScript& dest, int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     441             :     //! Adds a watch-only address to the store, and saves it to disk.
     442             :     bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     443             : 
     444             :     //! Fetches a pubkey from mapWatchKeys if it exists there
     445             :     bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const;
     446             : 
     447             :     //! HaveHDKey similar to HaveKey() but checks only mapHdPubKeys
     448             :     bool HaveHDKey(const CKeyID &address, CHDChain& hdChainCurrent) const;
     449             : 
     450             :     /* SigningProvider overrides */
     451             :     //! HaveKey implementation that also checks the mapHdPubKeys
     452             :     bool HaveKey(const CKeyID &address) const override;
     453             :     //! GetKey implementation that can derive a HD private key on the fly
     454             :     bool GetKey(const CKeyID &address, CKey& keyOut) const override;
     455             :     //! GetPubKey implementation that also checks the mapHdPubKeys
     456             :     bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override;
     457             :     bool AddCScript(const CScript& redeemScript) override;
     458             :     /** Implement lookup of key origin information through wallet key metadata. */
     459             :     bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
     460             : 
     461             :     void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool);
     462             :     bool NewKeyPool();
     463             :     // Seems as not used now anywhere in code
     464             :     // void AddKeypoolPubkey(const CPubKey& pubkey, const bool internal);
     465             : 
     466             :     bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     467             : 
     468             :     bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     469             :     bool 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) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     470             :     bool ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     471             : 
     472             :     /* Returns true if the wallet can generate new keys */
     473             :     bool CanGenerateKeys() const;
     474             : 
     475             :     //! Adds a HDPubKey into the wallet(database)
     476             :     bool AddHDPubKey(WalletBatch &batch, const CExtPubKey &extPubKey, bool fInternal);
     477             :     //! loads a HDPubKey into the wallets memory
     478             :     bool LoadHDPubKey(const CHDPubKey &hdPubKey) /*EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore) */;
     479             : 
     480             :     /**
     481             :      * HD Wallet Functions
     482             :      */
     483             : 
     484             :     bool GetHDChain(CHDChain& hdChainRet) const;
     485             :     bool GetDecryptedHDChain(CHDChain& hdChainRet) const;
     486             : 
     487             :     /* Generates a new HD chain */
     488             :     void GenerateNewHDChain(const SecureString& secureMnemonic, const SecureString& secureMnemonicPassphrase, std::optional<CKeyingMaterial> vMasterKey = std::nullopt);
     489             : 
     490             :     /**
     491             :      * Explicitly make the wallet learn the related scripts for outputs to the
     492             :      * given key. This is purely to make the wallet file compatible with older
     493             :      * software, as FillableSigningProvider automatically does this implicitly for all
     494             :      * keys now.
     495             :      */
     496             :     // void LearnRelatedScripts(const CPubKey& key, OutputType);
     497             : 
     498             :     /**
     499             :      * Same as LearnRelatedScripts, but when the OutputType is not known (and could
     500             :      * be anything).
     501             :      */
     502             :     // void LearnAllRelatedScripts(const CPubKey& key);
     503             : 
     504             :     /**
     505             :      * Marks all keys in the keypool up to and including the provided key as used.
     506             :      *
     507             :      * @param keypool_id determines the last key to mark as used
     508             :      *
     509             :      * @return All affected keys
     510             :      */
     511             :     std::vector<CKeyPool> MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
     512           1 :     const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
     513             : 
     514             :     std::set<CKeyID> GetKeys() const override;
     515             :     std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys() const override;
     516             : 
     517             :     /** Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this LegacyScriptPubKeyMan.
     518             :      * Does not modify this ScriptPubKeyMan. */
     519             :     std::optional<MigrationData> MigrateToDescriptor();
     520             :     /** Delete all the records ofthis LegacyScriptPubKeyMan from disk*/
     521             :     bool DeleteRecords();
     522             : };
     523             : 
     524             : /** Wraps a LegacyScriptPubKeyMan so that it can be returned in a new unique_ptr. Does not provide privkeys */
     525             : class LegacySigningProvider : public SigningProvider
     526             : {
     527             : private:
     528             :     const LegacyScriptPubKeyMan& m_spk_man;
     529             : public:
     530        6866 :     explicit LegacySigningProvider(const LegacyScriptPubKeyMan& spk_man) : m_spk_man(spk_man) {}
     531             : 
     532           3 :     bool GetCScript(const CScriptID &scriptid, CScript& script) const override { return m_spk_man.GetCScript(scriptid, script); }
     533           0 :     bool HaveCScript(const CScriptID &scriptid) const override { return m_spk_man.HaveCScript(scriptid); }
     534        3345 :     bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const override { return m_spk_man.GetPubKey(address, pubkey); }
     535           0 :     bool GetKey(const CKeyID &address, CKey& key) const override { return false; }
     536           0 :     bool HaveKey(const CKeyID &address) const override { return false; }
     537        3435 :     bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override { return m_spk_man.GetKeyOrigin(keyid, info); }
     538             : };
     539             : 
     540             : class DescriptorScriptPubKeyMan : public ScriptPubKeyMan
     541             : {
     542             : private:
     543             :     using ScriptPubKeyMap = std::map<CScript, int32_t>; // Map of scripts to descriptor range index
     544             :     using PubKeyMap = std::map<CPubKey, int32_t>; // Map of pubkeys involved in scripts to descriptor range index
     545             :     using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>;
     546             :     using KeyMap = std::map<CKeyID, CKey>;
     547             : 
     548             :     using Mnemonic = std::pair<SecureString, SecureString>;
     549             :     using MnemonicMap = std::map<CKeyID, Mnemonic>;
     550             :     using CryptedMnemonic = std::pair<std::vector<unsigned char>, std::vector<unsigned char>>;
     551             :     using CryptedMnemonicMap = std::map<CKeyID, CryptedMnemonic>;
     552             : 
     553             :     ScriptPubKeyMap m_map_script_pub_keys GUARDED_BY(cs_desc_man);
     554             :     PubKeyMap m_map_pubkeys GUARDED_BY(cs_desc_man);
     555          88 :     int32_t m_max_cached_index = -1;
     556             : 
     557             :     KeyMap m_map_keys GUARDED_BY(cs_desc_man);
     558             :     CryptedKeyMap m_map_crypted_keys GUARDED_BY(cs_desc_man);
     559             : 
     560             :     MnemonicMap m_mnemonics GUARDED_BY(cs_desc_man);
     561             :     CryptedMnemonicMap m_crypted_mnemonics GUARDED_BY(cs_desc_man);
     562             : 
     563             :     //! keeps track of whether Unlock has run a thorough check before
     564          88 :     bool m_decryption_thoroughly_checked = false;
     565             : 
     566             :     bool AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey, const SecureString& mnemonic, const SecureString& mnemonic_passphrase) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
     567             : 
     568             :     KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
     569             : 
     570             :     // Cached FlatSigningProviders to avoid regenerating them each time they are needed.
     571             :     mutable std::map<int32_t, FlatSigningProvider> m_map_signing_providers;
     572             :     // Fetch the SigningProvider for the given script and optionally include private keys
     573             :     std::unique_ptr<FlatSigningProvider> GetSigningProvider(const CScript& script, bool include_private = false) const;
     574             :     // Fetch the SigningProvider for the given pubkey and always include private keys. This should only be called by signing code.
     575             :     std::unique_ptr<FlatSigningProvider> GetSigningProvider(const CPubKey& pubkey) const;
     576             :     // Fetch the SigningProvider for a given index and optionally include private keys. Called by the above functions.
     577             :     std::unique_ptr<FlatSigningProvider> GetSigningProvider(int32_t index, bool include_private = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
     578             : 
     579             : protected:
     580             :   WalletDescriptor m_wallet_descriptor GUARDED_BY(cs_desc_man);
     581             : 
     582             : public:
     583         110 :     DescriptorScriptPubKeyMan(WalletStorage& storage, WalletDescriptor& descriptor)
     584          22 :         :   ScriptPubKeyMan(storage),
     585          22 :             m_wallet_descriptor(descriptor)
     586          66 :         {}
     587         330 :     DescriptorScriptPubKeyMan(WalletStorage& storage)
     588          66 :         :   ScriptPubKeyMan(storage)
     589         198 :         {}
     590             : 
     591             :     mutable RecursiveMutex cs_desc_man;
     592             : 
     593             :     util::Result<CTxDestination> GetNewDestination() override;
     594             :     isminetype IsMine(const CScript& script) const override;
     595             :     isminetype IsMine(const CTxDestination& dest) const override;
     596             : 
     597             :     bool CheckDecryptionKey(const CKeyingMaterial& master_key) override;
     598             :     bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
     599             : 
     600             :     util::Result<CTxDestination> GetReservedDestination(bool internal, int64_t& index, CKeyPool& keypool) override;
     601             :     void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) override;
     602             : 
     603             :     // Tops up the descriptor cache and m_map_script_pub_keys. The cache is stored in the wallet file
     604             :     // and is used to expand the descriptor in GetNewDestination. DescriptorScriptPubKeyMan relies
     605             :     // more on ephemeral data than LegacyScriptPubKeyMan. For wallets using unhardened derivation
     606             :     // (with or without private keys), the "keypool" is a single xpub.
     607             :     bool TopUp(unsigned int size = 0) override;
     608             : 
     609             :     //! Fast-forward this descriptor's next_index to `target` (topping up the
     610             :     //! script cache as needed) so the next GetNewDestination() returns the
     611             :     //! script at `target`. Used by wallet migration to make sure the active
     612             :     //! pkh() descriptors don't re-derive addresses the legacy wallet had
     613             :     //! already given out. No-op if next_index is already at or beyond target.
     614             :     [[nodiscard]] bool AdvanceNextIndexTo(int32_t target);
     615             : 
     616             :     std::vector<WalletDestination> MarkUnusedAddresses(WalletBatch &batch, const CScript& script, const std::optional<int64_t>& block_time) override;
     617             : 
     618             :     bool IsHDEnabled() const override;
     619             : 
     620             :     //! Setup descriptors based on the given CExtkey
     621             :     bool SetupDescriptorGeneration(const CExtKey& master_key, const SecureString& secure_mnemonic, const SecureString& secure_mnemonic_passphrase, PathDerivationType type);
     622             : 
     623             :     /** Provide a descriptor at setup time
     624             :     * Returns false if already setup or setup fails, true if setup is successful
     625             :     */
     626             :     bool SetupDescriptor(std::unique_ptr<Descriptor>desc);
     627             : 
     628             :     bool HavePrivateKeys() const override;
     629             : 
     630             :     std::optional<int64_t> GetOldestKeyPoolTime() const override;
     631             :     unsigned int GetKeyPoolSize() const override;
     632             : 
     633             :     int64_t GetTimeFirstKey() const override;
     634             : 
     635             :     std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const override;
     636             : 
     637             :     bool CanGetAddresses(bool internal = false) const override;
     638             : 
     639             :     std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const override;
     640             : 
     641             :     bool CanProvide(const CScript& script, SignatureData& sigdata) override;
     642             : 
     643             :     bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const override;
     644             :     SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const override;
     645             :     bool SignSpecialTxPayload(const uint256& hash, const CKeyID& keyid, std::vector<unsigned char>& vchSig) const override;
     646             :     TransactionError FillPSBT(PartiallySignedTransaction& psbt, const PrecomputedTransactionData& txdata, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false, int* n_signed = nullptr, bool finalize = true) const override;
     647             : 
     648             :     uint256 GetID() const override;
     649             : 
     650             :     void SetCache(const DescriptorCache& cache);
     651             : 
     652             :     bool AddKey(const CKeyID& key_id, const CKey& key, const SecureString& mnemonic, const SecureString& mnemonic_passphrase);
     653             :     bool 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);
     654             : 
     655             :     bool HasWalletDescriptor(const WalletDescriptor& desc) const;
     656             :     void UpdateWalletDescriptor(WalletDescriptor& descriptor);
     657             :     bool CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error);
     658             :     void AddDescriptorKey(const CKey& key, const CPubKey &pubkey, const SecureString& mnemonic = "", const SecureString& mnemonic_passphrase = "");
     659             :     void WriteDescriptor();
     660             : 
     661             :     WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
     662             :     std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys() const override;
     663             :     std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys(int32_t minimum_index) const;
     664             :     int32_t GetEndRange() const;
     665             : 
     666             :     bool GetDescriptorString(std::string& out, const bool priv) const;
     667             :     bool GetMnemonicString(SecureString& mnemonic_out, SecureString& mnemonic_passphrase_out) const;
     668             : 
     669             :     void UpgradeDescriptorCache();
     670             : };
     671             : } // namespace wallet
     672             : 
     673             : #endif // BITCOIN_WALLET_SCRIPTPUBKEYMAN_H

Generated by: LCOV version 1.16