LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 0 81 0.0 %
Date: 2024-01-03 14:57:27 Functions: 0 67 0.0 %
Branches: 0 162 0.0 %

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

Generated by: LCOV version 1.14