LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 1 82 1.2 %
Date: 2023-09-26 12:08:55 Functions: 2 67 3.0 %

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

Generated by: LCOV version 1.14