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

Generated by: LCOV version 1.14