Bitcoin Core  27.1.0
P2P Digital Currency
scriptpubkeyman.h
Go to the documentation of this file.
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 <functional>
26 #include <optional>
27 #include <unordered_map>
28 
29 enum class OutputType;
30 struct bilingual_str;
31 
32 namespace wallet {
33 struct MigrationData;
34 class ScriptPubKeyMan;
35 
36 // Wallet storage things that ScriptPubKeyMans need in order to be able to store things to the wallet database.
37 // It provides access to things that are part of the entire wallet and not specific to a ScriptPubKeyMan such as
38 // wallet flags, wallet version, encryption keys, encryption status, and the database itself. This allows a
39 // ScriptPubKeyMan to have callbacks into CWallet without causing a circular dependency.
40 // WalletStorage should be the same for all ScriptPubKeyMans of a wallet.
42 {
43 public:
44  virtual ~WalletStorage() = default;
45  virtual std::string GetDisplayName() const = 0;
46  virtual WalletDatabase& GetDatabase() const = 0;
47  virtual bool IsWalletFlagSet(uint64_t) const = 0;
48  virtual void UnsetBlankWalletFlag(WalletBatch&) = 0;
49  virtual bool CanSupportFeature(enum WalletFeature) const = 0;
50  virtual void SetMinVersion(enum WalletFeature, WalletBatch* = nullptr) = 0;
52  virtual bool WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const = 0;
53  virtual bool HasEncryptionKeys() const = 0;
54  virtual bool IsLocked() const = 0;
56  virtual void TopUpCallback(const std::set<CScript>&, ScriptPubKeyMan*) = 0;
57 };
58 
60 static constexpr int64_t UNKNOWN_TIME = std::numeric_limits<int64_t>::max();
61 
63 static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
64 
65 std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider);
66 
116 class CKeyPool
117 {
118 public:
120  int64_t nTime;
124  bool fInternal;
127 
128  CKeyPool();
129  CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
130 
131  template<typename Stream>
132  void Serialize(Stream& s) const
133  {
134  s << int{259900}; // Unused field, writes the highest client version ever written
135  s << nTime << vchPubKey << fInternal << m_pre_split;
136  }
137 
138  template<typename Stream>
139  void Unserialize(Stream& s)
140  {
141  s >> int{}; // Discard unused field
142  s >> nTime >> vchPubKey;
143  try {
144  s >> fInternal;
145  } catch (std::ios_base::failure&) {
146  /* flag as external address if we can't read the internal boolean
147  (this will be the case for any wallet before the HD chain split version) */
148  fInternal = false;
149  }
150  try {
151  s >> m_pre_split;
152  } catch (std::ios_base::failure&) {
153  /* flag as postsplit address if we can't read the m_pre_split boolean
154  (this will be the case for any wallet that upgrades to HD chain split) */
155  m_pre_split = false;
156  }
157  }
158 };
159 
161 {
163  std::optional<bool> internal;
164 };
165 
166 /*
167  * A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet.
168  * It contains the scripts and keys related to the scriptPubKeys it manages.
169  * A ScriptPubKeyMan will be able to give out scriptPubKeys to be used, as well as marking
170  * when a scriptPubKey has been used. It also handles when and how to store a scriptPubKey
171  * and its related scripts and keys, including encryption.
172  */
174 {
175 protected:
177 
178 public:
179  explicit ScriptPubKeyMan(WalletStorage& storage) : m_storage(storage) {}
180  virtual ~ScriptPubKeyMan() {};
181  virtual util::Result<CTxDestination> GetNewDestination(const OutputType type) { return util::Error{Untranslated("Not supported")}; }
182  virtual isminetype IsMine(const CScript& script) const { return ISMINE_NO; }
183 
185  virtual bool CheckDecryptionKey(const CKeyingMaterial& master_key) { return false; }
186  virtual bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) { return false; }
187 
188  virtual util::Result<CTxDestination> GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool) { return util::Error{Untranslated("Not supported")}; }
189  virtual void KeepDestination(int64_t index, const OutputType& type) {}
190  virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) {}
191 
196  virtual bool TopUp(unsigned int size = 0) { return false; }
197 
205  virtual std::vector<WalletDestination> MarkUnusedAddresses(const CScript& script) { return {}; }
206 
211  virtual bool SetupGeneration(bool force = false) { return false; }
212 
213  /* Returns true if HD is enabled */
214  virtual bool IsHDEnabled() const { return false; }
215 
216  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
217  virtual bool CanGetAddresses(bool internal = false) const { return false; }
218 
220  virtual bool Upgrade(int prev_version, int new_version, bilingual_str& error) { return true; }
221 
222  virtual bool HavePrivateKeys() const { return false; }
223 
225  virtual void RewriteDB() {}
226 
227  virtual std::optional<int64_t> GetOldestKeyPoolTime() const { return GetTime(); }
228 
229  virtual unsigned int GetKeyPoolSize() const { return 0; }
230 
231  virtual int64_t GetTimeFirstKey() const { return 0; }
232 
233  virtual std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const { return nullptr; }
234 
235  virtual std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const { return nullptr; }
236 
240  virtual bool CanProvide(const CScript& script, SignatureData& sigdata) { return false; }
241 
243  virtual bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const { return false; }
245  virtual SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const { return SigningResult::SIGNING_FAILED; };
247  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; }
248 
249  virtual uint256 GetID() const { return uint256(); }
250 
252  virtual std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys() const { return {}; };
253 
255  template <typename... Params>
256  void WalletLogPrintf(const char* fmt, Params... parameters) const
257  {
258  LogPrintf(("%s " + std::string{fmt}).c_str(), m_storage.GetDisplayName(), parameters...);
259  };
260 
262  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
263 
265  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
266 
268  boost::signals2::signal<void (const ScriptPubKeyMan* spkm, int64_t new_birth_time)> NotifyFirstKeyTimeChanged;
269 };
270 
272 static const std::unordered_set<OutputType> LEGACY_OUTPUT_TYPES {
276 };
277 
278 class DescriptorScriptPubKeyMan;
279 
281 {
282 private:
285 
286  using WatchOnlySet = std::set<CScript>;
287  using WatchKeyMap = std::map<CKeyID, CPubKey>;
288 
289  WalletBatch *encrypted_batch GUARDED_BY(cs_KeyStore) = nullptr;
290 
291  using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>;
292 
293  CryptedKeyMap mapCryptedKeys GUARDED_BY(cs_KeyStore);
294  WatchOnlySet setWatchOnly GUARDED_BY(cs_KeyStore);
295  WatchKeyMap mapWatchKeys GUARDED_BY(cs_KeyStore);
296 
297  // By default, do not scan any block until keys/scripts are generated/imported
298  int64_t nTimeFirstKey GUARDED_BY(cs_KeyStore) = UNKNOWN_TIME;
299 
301  int64_t m_keypool_size GUARDED_BY(cs_KeyStore){DEFAULT_KEYPOOL_SIZE};
302 
303  bool AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey);
304  bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
305 
317  bool AddWatchOnlyInMem(const CScript &dest);
319  bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
320 
322  bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
323 
324  void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch);
325 
327  bool AddCScriptWithDB(WalletBatch& batch, const CScript& script);
328 
330  bool AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info);
331 
332  /* the HD chain data model (external chain counters) */
334  std::unordered_map<CKeyID, CHDChain, SaltedSipHasher> m_inactive_hd_chains;
335 
336  /* HD derive new child key (on internal or external chain) */
337  void DeriveNewChildKey(WalletBatch& batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
338 
339  std::set<int64_t> setInternalKeyPool GUARDED_BY(cs_KeyStore);
340  std::set<int64_t> setExternalKeyPool GUARDED_BY(cs_KeyStore);
341  std::set<int64_t> set_pre_split_keypool GUARDED_BY(cs_KeyStore);
342  int64_t m_max_keypool_index GUARDED_BY(cs_KeyStore) = 0;
344  // Tracks keypool indexes to CKeyIDs of keys that have been taken out of the keypool but may be returned to it
346 
348  bool GetKeyFromPool(CPubKey &key, const OutputType type);
349 
364  bool ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
365 
376  bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal);
377 
378  bool TopUpChain(WalletBatch& batch, CHDChain& chain, unsigned int size);
379 public:
380  LegacyScriptPubKeyMan(WalletStorage& storage, int64_t keypool_size) : ScriptPubKeyMan(storage), m_keypool_size(keypool_size) {}
381 
383  isminetype IsMine(const CScript& script) const override;
384 
385  bool CheckDecryptionKey(const CKeyingMaterial& master_key) override;
386  bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
387 
388  util::Result<CTxDestination> GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool) override;
389  void KeepDestination(int64_t index, const OutputType& type) override;
390  void ReturnDestination(int64_t index, bool internal, const CTxDestination&) override;
391 
392  bool TopUp(unsigned int size = 0) override;
393 
394  std::vector<WalletDestination> MarkUnusedAddresses(const CScript& script) override;
395 
397  void UpgradeKeyMetadata();
398 
399  bool IsHDEnabled() const override;
400 
401  bool SetupGeneration(bool force = false) override;
402 
403  bool Upgrade(int prev_version, int new_version, bilingual_str& error) override;
404 
405  bool HavePrivateKeys() const override;
406 
407  void RewriteDB() override;
408 
409  std::optional<int64_t> GetOldestKeyPoolTime() const override;
410  size_t KeypoolCountExternalKeys() const;
411  unsigned int GetKeyPoolSize() const override;
412 
413  int64_t GetTimeFirstKey() const override;
414 
415  std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const override;
416 
417  bool CanGetAddresses(bool internal = false) const override;
418 
419  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const override;
420 
421  bool CanProvide(const CScript& script, SignatureData& sigdata) override;
422 
423  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const override;
424  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const override;
425  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;
426 
427  uint256 GetID() const override;
428 
429  // Map from Key ID to key metadata.
430  std::map<CKeyID, CKeyMetadata> mapKeyMetadata GUARDED_BY(cs_KeyStore);
431 
432  // Map from Script ID to key metadata (for watch-only keys).
433  std::map<CScriptID, CKeyMetadata> m_script_metadata GUARDED_BY(cs_KeyStore);
434 
436  bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
438  bool LoadKey(const CKey& key, const CPubKey &pubkey);
440  bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
442  bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid);
443  void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
445  bool LoadCScript(const CScript& redeemScript);
447  void LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &metadata);
448  void LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &metadata);
450  CPubKey GenerateNewKey(WalletBatch& batch, CHDChain& hd_chain, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
451 
452  /* Set the HD chain model (chain child index counters) and writes it to the database */
453  void AddHDChain(const CHDChain& chain);
455  void LoadHDChain(const CHDChain& chain);
456  const CHDChain& GetHDChain() const { return m_hd_chain; }
457  void AddInactiveHDChain(const CHDChain& chain);
458 
460  bool LoadWatchOnly(const CScript &dest);
462  bool HaveWatchOnly(const CScript &dest) const;
464  bool HaveWatchOnly() const;
466  bool RemoveWatchOnly(const CScript &dest);
467  bool AddWatchOnly(const CScript& dest, int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
468 
470  bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const;
471 
472  /* SigningProvider overrides */
473  bool HaveKey(const CKeyID &address) const override;
474  bool GetKey(const CKeyID &address, CKey& keyOut) const override;
475  bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override;
476  bool AddCScript(const CScript& redeemScript) override;
477  bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
478 
480  void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool);
481  bool NewKeyPool();
483 
484  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
485  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
486  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);
487  bool ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
488 
489  /* Returns true if the wallet can generate new keys */
490  bool CanGenerateKeys() const;
491 
492  /* Generates a new HD seed (will not be activated) */
494 
495  /* Derives a new HD seed (will not be activated) */
496  CPubKey DeriveNewSeed(const CKey& key);
497 
498  /* Set the current HD seed (will reset the chain child index counters)
499  Sets the seed's version based on the current wallet version (so the
500  caller must ensure the current wallet version is correct before calling
501  this function). */
502  void SetHDSeed(const CPubKey& key);
503 
510  void LearnRelatedScripts(const CPubKey& key, OutputType);
511 
516  void LearnAllRelatedScripts(const CPubKey& key);
517 
526  const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
527 
528  std::set<CKeyID> GetKeys() const override;
529  std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys() const override;
530 
535  std::unordered_set<CScript, SaltedSipHasher> GetNotMineScriptPubKeys() const;
536 
539  std::optional<MigrationData> MigrateToDescriptor();
541  bool DeleteRecords();
542 };
543 
546 {
547 private:
549 public:
550  explicit LegacySigningProvider(const LegacyScriptPubKeyMan& spk_man) : m_spk_man(spk_man) {}
551 
552  bool GetCScript(const CScriptID &scriptid, CScript& script) const override { return m_spk_man.GetCScript(scriptid, script); }
553  bool HaveCScript(const CScriptID &scriptid) const override { return m_spk_man.HaveCScript(scriptid); }
554  bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const override { return m_spk_man.GetPubKey(address, pubkey); }
555  bool GetKey(const CKeyID &address, CKey& key) const override { return false; }
556  bool HaveKey(const CKeyID &address) const override { return false; }
557  bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override { return m_spk_man.GetKeyOrigin(keyid, info); }
558 };
559 
561 {
562 private:
563  using ScriptPubKeyMap = std::map<CScript, int32_t>; // Map of scripts to descriptor range index
564  using PubKeyMap = std::map<CPubKey, int32_t>; // Map of pubkeys involved in scripts to descriptor range index
565  using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>;
566  using KeyMap = std::map<CKeyID, CKey>;
567 
568  ScriptPubKeyMap m_map_script_pub_keys GUARDED_BY(cs_desc_man);
569  PubKeyMap m_map_pubkeys GUARDED_BY(cs_desc_man);
570  int32_t m_max_cached_index = -1;
571 
572  KeyMap m_map_keys GUARDED_BY(cs_desc_man);
573  CryptedKeyMap m_map_crypted_keys GUARDED_BY(cs_desc_man);
574 
577 
579  int64_t m_keypool_size GUARDED_BY(cs_desc_man){DEFAULT_KEYPOOL_SIZE};
580 
581  bool AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
582 
584 
585  // Cached FlatSigningProviders to avoid regenerating them each time they are needed.
587  // Fetch the SigningProvider for the given script and optionally include private keys
588  std::unique_ptr<FlatSigningProvider> GetSigningProvider(const CScript& script, bool include_private = false) const;
589  // Fetch the SigningProvider for the given pubkey and always include private keys. This should only be called by signing code.
590  std::unique_ptr<FlatSigningProvider> GetSigningProvider(const CPubKey& pubkey) const;
591  // Fetch the SigningProvider for a given index and optionally include private keys. Called by the above functions.
592  std::unique_ptr<FlatSigningProvider> GetSigningProvider(int32_t index, bool include_private = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
593 
594 protected:
595  WalletDescriptor m_wallet_descriptor GUARDED_BY(cs_desc_man);
596 
598  bool TopUpWithDB(WalletBatch& batch, unsigned int size = 0);
599 
600 public:
601  DescriptorScriptPubKeyMan(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size)
602  : ScriptPubKeyMan(storage),
603  m_keypool_size(keypool_size),
604  m_wallet_descriptor(descriptor)
605  {}
606  DescriptorScriptPubKeyMan(WalletStorage& storage, int64_t keypool_size)
607  : ScriptPubKeyMan(storage),
608  m_keypool_size(keypool_size)
609  {}
610 
612 
614  isminetype IsMine(const CScript& script) const override;
615 
616  bool CheckDecryptionKey(const CKeyingMaterial& master_key) override;
617  bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
618 
619  util::Result<CTxDestination> GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool) override;
620  void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) override;
621 
622  // Tops up the descriptor cache and m_map_script_pub_keys. The cache is stored in the wallet file
623  // and is used to expand the descriptor in GetNewDestination. DescriptorScriptPubKeyMan relies
624  // more on ephemeral data than LegacyScriptPubKeyMan. For wallets using unhardened derivation
625  // (with or without private keys), the "keypool" is a single xpub.
626  bool TopUp(unsigned int size = 0) override;
627 
628  std::vector<WalletDestination> MarkUnusedAddresses(const CScript& script) override;
629 
630  bool IsHDEnabled() const override;
631 
633  bool SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal);
634 
635  bool HavePrivateKeys() const override;
636 
637  std::optional<int64_t> GetOldestKeyPoolTime() const override;
638  unsigned int GetKeyPoolSize() const override;
639 
640  int64_t GetTimeFirstKey() const override;
641 
642  std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const override;
643 
644  bool CanGetAddresses(bool internal = false) const override;
645 
646  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const override;
647 
648  bool CanProvide(const CScript& script, SignatureData& sigdata) override;
649 
650  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const override;
651  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const override;
652  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;
653 
654  uint256 GetID() const override;
655 
656  void SetCache(const DescriptorCache& cache);
657 
658  bool AddKey(const CKeyID& key_id, const CKey& key);
659  bool AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key);
660 
661  bool HasWalletDescriptor(const WalletDescriptor& desc) const;
662  void UpdateWalletDescriptor(WalletDescriptor& descriptor);
663  bool CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error);
664  void AddDescriptorKey(const CKey& key, const CPubKey &pubkey);
665  void WriteDescriptor();
666 
668  std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys() const override;
669  std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys(int32_t minimum_index) const;
670  int32_t GetEndRange() const;
671 
672  bool GetDescriptorString(std::string& out, const bool priv) const;
673 
674  void UpgradeDescriptorCache();
675 };
676 
679 {
681  std::vector<std::pair<std::string, int64_t>> watch_descs;
682  std::vector<std::pair<std::string, int64_t>> solvable_descs;
683  std::vector<std::unique_ptr<DescriptorScriptPubKeyMan>> desc_spkms;
684  std::shared_ptr<CWallet> watchonly_wallet{nullptr};
685  std::shared_ptr<CWallet> solvable_wallet{nullptr};
686 };
687 
688 } // namespace wallet
689 
690 #endif // BITCOIN_WALLET_SCRIPTPUBKEYMAN_H
int64_t GetTimeFirstKey() const override
virtual std::string GetDisplayName() const =0
bool GetCScript(const CScriptID &scriptid, CScript &script) const override
bool AddWatchOnlyInMem(const CScript &dest)
virtual SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Sign a message with the given script.
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
static const std::string sighash
Definition: sighash.json.h:3
bool CheckDecryptionKey(const CKeyingMaterial &master_key) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
std::map< CKeyID, CPubKey > WatchKeyMap
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
virtual uint256 GetID() const
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
bool GetKey(const CKeyID &address, CKey &key) const override
std::vector< WalletDestination > MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used Affects all keys up to and including the one determined by provid...
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
bool SetupDescriptorGeneration(WalletBatch &batch, const CExtKey &master_key, OutputType addr_type, bool internal)
Setup descriptors based on the given CExtkey.
bool CheckDecryptionKey(const CKeyingMaterial &master_key) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
void UpgradeKeyMetadata()
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
std::vector< WalletDestination > MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used Affects all keys up to and including the one determined by provid...
const CHDChain & GetHDChain() const
bool Upgrade(int prev_version, int new_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const override
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
Adds script and derivation path information to a PSBT, and optionally signs it.
virtual WalletDatabase & GetDatabase() const =0
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
isminetype IsMine(const CScript &script) const override
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
Bilingual messages:
Definition: translation.h:18
std::map< int64_t, CKeyID > m_index_to_reserved_key
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
unsigned int GetKeyPoolSize() const override
virtual bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch)
RecursiveMutex cs_KeyStore
bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const override
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
Like TopUp() but adds keys for inactive HD chains.
SigningResult
Definition: message.h:43
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
bool AddCScript(const CScript &redeemScript) override
std::optional< MigrationData > MigrateToDescriptor()
Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this Legac...
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
Definition: key.h:210
bool CanGetAddresses(bool internal=false) const override
struct containing information needed for migrating legacy wallets to descriptor wallets ...
std::vector< std::pair< std::string, int64_t > > solvable_descs
std::map< CKeyID, CKey > KeyMap
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
DescriptorScriptPubKeyMan(WalletStorage &storage, int64_t keypool_size)
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
virtual bool CheckDecryptionKey(const CKeyingMaterial &master_key)
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
std::map< CKeyID, std::pair< CPubKey, std::vector< unsigned char > >> CryptedKeyMap
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
bool AddWatchOnly(const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
std::vector< std::pair< std::string, int64_t > > watch_descs
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Adds a key to the store, and saves it to disk.
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
void UpdateWalletDescriptor(WalletDescriptor &descriptor)
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
void SetHDSeed(const CPubKey &key)
bool DeleteRecords()
Delete all the records ofthis LegacyScriptPubKeyMan from disk.
A version of CTransaction with the PSBT format.
Definition: psbt.h:946
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
Access to the wallet database.
Definition: walletdb.h:190
A key from a CWallet&#39;s keypool.
bool GetKey(const CKeyID &address, CKey &keyOut) const override
boost::signals2::signal< void(const ScriptPubKeyMan *spkm, int64_t new_birth_time)> NotifyFirstKeyTimeChanged
Birth time changed.
void Unserialize(Stream &s)
bool AddKey(const CKeyID &key_id, const CKey &key)
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
virtual bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const
Creates new signatures and adds them to the transaction.
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
virtual bool IsLocked() const =0
virtual bool CanProvide(const CScript &script, SignatureData &sigdata)
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
unsigned int GetKeyPoolSize() const override
bool IsHDEnabled() const override
std::set< CScript > WatchOnlySet
std::map< CPubKey, int32_t > PubKeyMap
OutputType
Definition: outputtype.h:17
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
virtual std::optional< int64_t > GetOldestKeyPoolTime() const
int64_t m_keypool_size GUARDED_BY(cs_KeyStore)
Number of pre-generated keys/scripts (part of the look-ahead process, used to detect payments) ...
bool CanGetAddresses(bool internal=false) const override
void SetCache(const DescriptorCache &cache)
virtual isminetype IsMine(const CScript &script) const
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool HaveKey(const CKeyID &address) const override
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
virtual std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
ScriptPubKeyMan(WalletStorage &storage)
static constexpr int64_t UNKNOWN_TIME
Constant representing an unknown spkm creation time.
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
std::set< CKeyID > GetKeys() const override
bool HavePrivateKeys() const override
virtual bool CanSupportFeature(enum WalletFeature) const =0
CPubKey vchPubKey
The public key.
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr)=0
void RewriteDB() override
The action to do when the DB needs rewrite.
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
virtual bool HasEncryptionKeys() const =0
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
std::optional< int64_t > GetOldestKeyPoolTime() const override
Wraps a LegacyScriptPubKeyMan so that it can be returned in a new unique_ptr.
bool HaveKey(const CKeyID &address) const override
void AddHDChain(const CHDChain &chain)
virtual std::vector< WalletDestination > MarkUnusedAddresses(const CScript &script)
Mark unused addresses as being used Affects all keys up to and including the one determined by provid...
An encapsulated public key.
Definition: pubkey.h:33
Fillable signing provider that keeps keys in an address->secret map.
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: types.h:40
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:15
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
isminetype IsMine(const CScript &script) const override
void ReturnDestination(int64_t index, bool internal, const CTxDestination &) override
WalletBatch *encrypted_batch GUARDED_BY(cs_KeyStore)
ScriptPubKeyMap m_map_script_pub_keys GUARDED_BY(cs_desc_man)
std::map< CScript, int32_t > ScriptPubKeyMap
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
virtual bool IsHDEnabled() const
util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool) override
LegacySigningProvider(const LegacyScriptPubKeyMan &spk_man)
virtual std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const
static const std::unordered_set< OutputType > LEGACY_OUTPUT_TYPES
OutputTypes supported by the LegacyScriptPubKeyMan.
std::optional< int64_t > GetOldestKeyPoolTime() const override
std::unordered_set< CScript, SaltedSipHasher > GetNotMineScriptPubKeys() const
Retrieves scripts that were imported by bugs into the legacy spkm and are simply invalid, such as a sh(sh(pkh())) script, or not watched.
virtual void TopUpCallback(const std::set< CScript > &, ScriptPubKeyMan *)=0
Callback function for after TopUp completes containing any scripts that were added by a SPKMan...
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
uint256 GetID() const override
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, bool checksum_valid)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) ...
Descriptor with some wallet metadata.
Definition: walletutil.h:84
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)
virtual bool HavePrivateKeys() const
bool HaveCScript(const CScriptID &scriptid) const override
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
virtual void KeepDestination(int64_t index, const OutputType &type)
virtual unsigned int GetKeyPoolSize() const
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:131
virtual void RewriteDB()
The action to do when the DB needs rewrite.
virtual bool CanGetAddresses(bool internal=false) const
256-bit opaque blob.
Definition: uint256.h:106
CPubKey DeriveNewSeed(const CKey &key)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
bool TopUpChain(WalletBatch &batch, CHDChain &chain, unsigned int size)
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
void WalletLogPrintf(const char *fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
virtual bool WithEncryptionKey(std::function< bool(const CKeyingMaterial &)> cb) const =0
Pass the encryption key to cb().
An interface to be implemented by keystores that support signing.
util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool) override
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
const LegacyScriptPubKeyMan & m_spk_man
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool error(const char *fmt, const Args &... args)
Definition: logging.h:267
const CChainParams & Params()
Return the currently selected parameters.
Cache for single descriptor&#39;s derived extended pubkeys.
Definition: descriptor.h:19
bool GetDescriptorString(std::string &out, const bool priv) const
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
virtual util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool)
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
std::map< CKeyID, std::pair< CPubKey, std::vector< unsigned char > >> CryptedKeyMap
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
std::map< int32_t, FlatSigningProvider > m_map_signing_providers
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
TransactionError
Definition: error.h:22
std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
virtual bool HaveCScript(const CScriptID &hash) const override
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
void Serialize(Stream &s) const
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
void AddInactiveHDChain(const CHDChain &chain)
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:582
A mutable version of CTransaction.
Definition: transaction.h:377
CPubKey GenerateNewKey(WalletBatch &batch, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Generate a new key.
bool GetKeyFromPool(CPubKey &key, const OutputType type)
Fetches a key from the keypool.
int64_t m_keypool_size GUARDED_BY(cs_desc_man)
Number of pre-generated keys/scripts (part of the look-ahead process, used to detect payments) ...
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
void KeepDestination(int64_t index, const OutputType &type) override
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
bool TopUp(unsigned int size=0) override
Fills internal address pool.
std::vector< CKeyPool > MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Marks all keys in the keypool up to and including the provided key as used.
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
Adds script and derivation path information to a PSBT, and optionally signs it.
virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr)
An encapsulated private key.
Definition: key.h:32
std::map< CKeyID, int64_t > m_pool_key_to_index
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
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
Adds script and derivation path information to a PSBT, and optionally signs it.
virtual int64_t GetTimeFirstKey() const
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
virtual bool TopUp(unsigned int size=0)
Fills internal address pool.
virtual std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
#define LogPrintf(...)
Definition: logging.h:245
virtual util::Result< CTxDestination > GetNewDestination(const OutputType type)
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:97
std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
virtual ~WalletStorage()=default
virtual bool Upgrade(int prev_version, int new_version, bilingual_str &error)
Upgrades the wallet to the specified version.
bool TopUpWithDB(WalletBatch &batch, unsigned int size=0)
Same as &#39;TopUp&#39; but designed for use within a batch transaction context.
virtual bool SetupGeneration(bool force=false)
Sets up the key generation stuff, i.e.
const std::map< CKeyID, int64_t > & GetAllReserveKeys() const
bool HasWalletDescriptor(const WalletDescriptor &desc) const
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
An instance of this class represents one database.
Definition: db.h:123
int64_t GetTimeFirstKey() const override
bool TopUp(unsigned int size=0) override
Fills internal address pool.
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:62
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::vector< std::unique_ptr< DescriptorScriptPubKeyMan > > desc_spkms
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
WalletStorage & m_storage
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.