LCOV - code coverage report
Current view: top level - src/wallet - scriptpubkeyman.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 18.4 % 76 14
Test Date: 2024-07-04 04:02:30 Functions: 16.7 % 66 11
Branches: 5.6 % 162 9

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

Generated by: LCOV version 2.0-1