Bitcoin Core  0.21.1
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules
scriptpubkeyman.h
Go to the documentation of this file.
1 // Copyright (c) 2019-2020 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 <psbt.h>
9 #include <script/descriptor.h>
10 #include <script/signingprovider.h>
11 #include <script/standard.h>
12 #include <util/error.h>
13 #include <util/message.h>
14 #include <wallet/crypter.h>
15 #include <wallet/ismine.h>
16 #include <wallet/walletdb.h>
17 #include <wallet/walletutil.h>
18 
19 #include <boost/signals2/signal.hpp>
20 
21 #include <unordered_map>
22 
23 enum class OutputType;
24 struct bilingual_str;
25 
26 // Wallet storage things that ScriptPubKeyMans need in order to be able to store things to the wallet database.
27 // It provides access to things that are part of the entire wallet and not specific to a ScriptPubKeyMan such as
28 // wallet flags, wallet version, encryption keys, encryption status, and the database itself. This allows a
29 // ScriptPubKeyMan to have callbacks into CWallet without causing a circular dependency.
30 // WalletStorage should be the same for all ScriptPubKeyMans of a wallet.
32 {
33 public:
34  virtual ~WalletStorage() = default;
35  virtual const std::string GetDisplayName() const = 0;
36  virtual WalletDatabase& GetDatabase() const = 0;
37  virtual bool IsWalletFlagSet(uint64_t) const = 0;
38  virtual void UnsetBlankWalletFlag(WalletBatch&) = 0;
39  virtual bool CanSupportFeature(enum WalletFeature) const = 0;
40  virtual void SetMinVersion(enum WalletFeature, WalletBatch* = nullptr) = 0;
41  virtual const CKeyingMaterial& GetEncryptionKey() const = 0;
42  virtual bool HasEncryptionKeys() const = 0;
43  virtual bool IsLocked() const = 0;
44 };
45 
47 static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
48 
49 std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider);
50 
100 class CKeyPool
101 {
102 public:
104  int64_t nTime;
108  bool fInternal;
111 
112  CKeyPool();
113  CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
114 
115  template<typename Stream>
116  void Serialize(Stream& s) const
117  {
118  int nVersion = s.GetVersion();
119  if (!(s.GetType() & SER_GETHASH)) {
120  s << nVersion;
121  }
122  s << nTime << vchPubKey << fInternal << m_pre_split;
123  }
124 
125  template<typename Stream>
126  void Unserialize(Stream& s)
127  {
128  int nVersion = s.GetVersion();
129  if (!(s.GetType() & SER_GETHASH)) {
130  s >> nVersion;
131  }
132  s >> nTime >> vchPubKey;
133  try {
134  s >> fInternal;
135  } catch (std::ios_base::failure&) {
136  /* flag as external address if we can't read the internal boolean
137  (this will be the case for any wallet before the HD chain split version) */
138  fInternal = false;
139  }
140  try {
141  s >> m_pre_split;
142  } catch (std::ios_base::failure&) {
143  /* flag as postsplit address if we can't read the m_pre_split boolean
144  (this will be the case for any wallet that upgrades to HD chain split) */
145  m_pre_split = false;
146  }
147  }
148 };
149 
151 {
152 public:
154 
155  size_t operator()(const CKeyID& id) const
156  {
157  return id.GetUint64(0);
158  }
159 };
160 
161 /*
162  * A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet.
163  * It contains the scripts and keys related to the scriptPubKeys it manages.
164  * A ScriptPubKeyMan will be able to give out scriptPubKeys to be used, as well as marking
165  * when a scriptPubKey has been used. It also handles when and how to store a scriptPubKey
166  * and its related scripts and keys, including encryption.
167  */
169 {
170 protected:
172 
173 public:
174  ScriptPubKeyMan(WalletStorage& storage) : m_storage(storage) {}
175  virtual ~ScriptPubKeyMan() {};
176  virtual bool GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error) { return false; }
177  virtual isminetype IsMine(const CScript& script) const { return ISMINE_NO; }
178 
180  virtual bool CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys = false) { return false; }
181  virtual bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) { return false; }
182 
183  virtual bool GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool) { return false; }
184  virtual void KeepDestination(int64_t index, const OutputType& type) {}
185  virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) {}
186 
191  virtual bool TopUp(unsigned int size = 0) { return false; }
192 
194  virtual void MarkUnusedAddresses(const CScript& script) {}
195 
200  virtual bool SetupGeneration(bool force = false) { return false; }
201 
202  /* Returns true if HD is enabled */
203  virtual bool IsHDEnabled() const { return false; }
204 
205  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
206  virtual bool CanGetAddresses(bool internal = false) const { return false; }
207 
209  virtual bool Upgrade(int prev_version, int new_version, bilingual_str& error) { return false; }
210 
211  virtual bool HavePrivateKeys() const { return false; }
212 
214  virtual void RewriteDB() {}
215 
216  virtual int64_t GetOldestKeyPoolTime() const { return GetTime(); }
217 
218  virtual size_t KeypoolCountExternalKeys() const { return 0; }
219  virtual unsigned int GetKeyPoolSize() const { return 0; }
220 
221  virtual int64_t GetTimeFirstKey() const { return 0; }
222 
223  virtual std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const { return nullptr; }
224 
225  virtual std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const { return nullptr; }
226 
230  virtual bool CanProvide(const CScript& script, SignatureData& sigdata) { return false; }
231 
233  virtual bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const { return false; }
235  virtual SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const { return SigningResult::SIGNING_FAILED; };
237  virtual TransactionError FillPSBT(PartiallySignedTransaction& psbt, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false, int* n_signed = nullptr) const { return TransactionError::INVALID_PSBT; }
238 
239  virtual uint256 GetID() const { return uint256(); }
240 
241  virtual void SetInternal(bool internal) {}
242 
244  template<typename... Params>
245  void WalletLogPrintf(std::string fmt, Params... parameters) const {
246  LogPrintf(("%s " + fmt).c_str(), m_storage.GetDisplayName(), parameters...);
247  };
248 
250  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
251 
253  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
254 };
255 
257 {
258 private:
261 
262  using WatchOnlySet = std::set<CScript>;
263  using WatchKeyMap = std::map<CKeyID, CPubKey>;
264 
265  WalletBatch *encrypted_batch GUARDED_BY(cs_KeyStore) = nullptr;
266 
267  using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>;
268 
269  CryptedKeyMap mapCryptedKeys GUARDED_BY(cs_KeyStore);
270  WatchOnlySet setWatchOnly GUARDED_BY(cs_KeyStore);
271  WatchKeyMap mapWatchKeys GUARDED_BY(cs_KeyStore);
272 
273  int64_t nTimeFirstKey GUARDED_BY(cs_KeyStore) = 0;
274 
275  bool AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey);
276  bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
277 
289  bool AddWatchOnlyInMem(const CScript &dest);
291  bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
292 
294  bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
295 
296  void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch);
297 
299  bool AddCScriptWithDB(WalletBatch& batch, const CScript& script);
300 
302  bool AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info);
303 
304  /* the HD chain data model (external chain counters) */
306  std::unordered_map<CKeyID, CHDChain, KeyIDHasher> m_inactive_hd_chains;
307 
308  /* HD derive new child key (on internal or external chain) */
309  void DeriveNewChildKey(WalletBatch& batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
310 
311  std::set<int64_t> setInternalKeyPool GUARDED_BY(cs_KeyStore);
312  std::set<int64_t> setExternalKeyPool GUARDED_BY(cs_KeyStore);
313  std::set<int64_t> set_pre_split_keypool GUARDED_BY(cs_KeyStore);
314  int64_t m_max_keypool_index GUARDED_BY(cs_KeyStore) = 0;
316  // Tracks keypool indexes to CKeyIDs of keys that have been taken out of the keypool but may be returned to it
317  std::map<int64_t, CKeyID> m_index_to_reserved_key;
318 
320  bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal = false);
321 
336  bool ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
337 
348  bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal);
349 
350 public:
352 
353  bool GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error) override;
354  isminetype IsMine(const CScript& script) const override;
355 
356  bool CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys = false) override;
357  bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
358 
359  bool GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool) override;
360  void KeepDestination(int64_t index, const OutputType& type) override;
361  void ReturnDestination(int64_t index, bool internal, const CTxDestination&) override;
362 
363  bool TopUp(unsigned int size = 0) override;
364 
365  void MarkUnusedAddresses(const CScript& script) override;
366 
368  void UpgradeKeyMetadata();
369 
370  bool IsHDEnabled() const override;
371 
372  bool SetupGeneration(bool force = false) override;
373 
374  bool Upgrade(int prev_version, int new_version, bilingual_str& error) override;
375 
376  bool HavePrivateKeys() const override;
377 
378  void RewriteDB() override;
379 
380  int64_t GetOldestKeyPoolTime() const override;
381  size_t KeypoolCountExternalKeys() const override;
382  unsigned int GetKeyPoolSize() const override;
383 
384  int64_t GetTimeFirstKey() const override;
385 
386  std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const override;
387 
388  bool CanGetAddresses(bool internal = false) const override;
389 
390  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const override;
391 
392  bool CanProvide(const CScript& script, SignatureData& sigdata) override;
393 
394  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const override;
395  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const override;
396  TransactionError FillPSBT(PartiallySignedTransaction& psbt, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false, int* n_signed = nullptr) const override;
397 
398  uint256 GetID() const override;
399 
400  void SetInternal(bool internal) override;
401 
402  // Map from Key ID to key metadata.
403  std::map<CKeyID, CKeyMetadata> mapKeyMetadata GUARDED_BY(cs_KeyStore);
404 
405  // Map from Script ID to key metadata (for watch-only keys).
406  std::map<CScriptID, CKeyMetadata> m_script_metadata GUARDED_BY(cs_KeyStore);
407 
409  bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
411  bool LoadKey(const CKey& key, const CPubKey &pubkey);
413  bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
415  bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid);
416  void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
418  bool LoadCScript(const CScript& redeemScript);
420  void LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &metadata);
421  void LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &metadata);
423  CPubKey GenerateNewKey(WalletBatch& batch, CHDChain& hd_chain, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
424 
425  /* Set the HD chain model (chain child index counters) and writes it to the database */
426  void AddHDChain(const CHDChain& chain);
428  void LoadHDChain(const CHDChain& chain);
429  const CHDChain& GetHDChain() const { return m_hd_chain; }
430  void AddInactiveHDChain(const CHDChain& chain);
431 
433  bool LoadWatchOnly(const CScript &dest);
435  bool HaveWatchOnly(const CScript &dest) const;
437  bool HaveWatchOnly() const;
439  bool RemoveWatchOnly(const CScript &dest);
440  bool AddWatchOnly(const CScript& dest, int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
441 
443  bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const;
444 
445  /* SigningProvider overrides */
446  bool HaveKey(const CKeyID &address) const override;
447  bool GetKey(const CKeyID &address, CKey& keyOut) const override;
448  bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override;
449  bool AddCScript(const CScript& redeemScript) override;
450  bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
451 
453  void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool);
454  bool NewKeyPool();
456 
457  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
458  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
459  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);
460  bool ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
461 
462  /* Returns true if the wallet can generate new keys */
463  bool CanGenerateKeys() const;
464 
465  /* Generates a new HD seed (will not be activated) */
466  CPubKey GenerateNewSeed();
467 
468  /* Derives a new HD seed (will not be activated) */
469  CPubKey DeriveNewSeed(const CKey& key);
470 
471  /* Set the current HD seed (will reset the chain child index counters)
472  Sets the seed's version based on the current wallet version (so the
473  caller must ensure the current wallet version is correct before calling
474  this function). */
475  void SetHDSeed(const CPubKey& key);
476 
483  void LearnRelatedScripts(const CPubKey& key, OutputType);
484 
489  void LearnAllRelatedScripts(const CPubKey& key);
490 
494  void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
495  const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
496 
497  std::set<CKeyID> GetKeys() const override;
498 };
499 
502 {
503 private:
505 public:
506  LegacySigningProvider(const LegacyScriptPubKeyMan& spk_man) : m_spk_man(spk_man) {}
507 
508  bool GetCScript(const CScriptID &scriptid, CScript& script) const override { return m_spk_man.GetCScript(scriptid, script); }
509  bool HaveCScript(const CScriptID &scriptid) const override { return m_spk_man.HaveCScript(scriptid); }
510  bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const override { return m_spk_man.GetPubKey(address, pubkey); }
511  bool GetKey(const CKeyID &address, CKey& key) const override { return false; }
512  bool HaveKey(const CKeyID &address) const override { return false; }
513  bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override { return m_spk_man.GetKeyOrigin(keyid, info); }
514 };
515 
517 {
518 private:
519  WalletDescriptor m_wallet_descriptor GUARDED_BY(cs_desc_man);
520 
521  using ScriptPubKeyMap = std::map<CScript, int32_t>; // Map of scripts to descriptor range index
522  using PubKeyMap = std::map<CPubKey, int32_t>; // Map of pubkeys involved in scripts to descriptor range index
523  using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>;
524  using KeyMap = std::map<CKeyID, CKey>;
525 
526  ScriptPubKeyMap m_map_script_pub_keys GUARDED_BY(cs_desc_man);
527  PubKeyMap m_map_pubkeys GUARDED_BY(cs_desc_man);
528  int32_t m_max_cached_index = -1;
529 
530  bool m_internal = false;
531 
532  KeyMap m_map_keys GUARDED_BY(cs_desc_man);
533  CryptedKeyMap m_map_crypted_keys GUARDED_BY(cs_desc_man);
534 
537 
538  bool AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
539 
541 
542  // Fetch the SigningProvider for the given script and optionally include private keys
543  std::unique_ptr<FlatSigningProvider> GetSigningProvider(const CScript& script, bool include_private = false) const;
544  // Fetch the SigningProvider for the given pubkey and always include private keys. This should only be called by signing code.
545  std::unique_ptr<FlatSigningProvider> GetSigningProvider(const CPubKey& pubkey) const;
546  // Fetch the SigningProvider for a given index and optionally include private keys. Called by the above functions.
547  std::unique_ptr<FlatSigningProvider> GetSigningProvider(int32_t index, bool include_private = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man);
548 
549 public:
551  : ScriptPubKeyMan(storage),
552  m_wallet_descriptor(descriptor)
553  {}
554  DescriptorScriptPubKeyMan(WalletStorage& storage, bool internal)
555  : ScriptPubKeyMan(storage),
556  m_internal(internal)
557  {}
558 
560 
561  bool GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error) override;
562  isminetype IsMine(const CScript& script) const override;
563 
564  bool CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys = false) override;
565  bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
566 
567  bool GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool) override;
568  void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) override;
569 
570  // Tops up the descriptor cache and m_map_script_pub_keys. The cache is stored in the wallet file
571  // and is used to expand the descriptor in GetNewDestination. DescriptorScriptPubKeyMan relies
572  // more on ephemeral data than LegacyScriptPubKeyMan. For wallets using unhardened derivation
573  // (with or without private keys), the "keypool" is a single xpub.
574  bool TopUp(unsigned int size = 0) override;
575 
576  void MarkUnusedAddresses(const CScript& script) override;
577 
578  bool IsHDEnabled() const override;
579 
581  bool SetupDescriptorGeneration(const CExtKey& master_key, OutputType addr_type);
582 
583  bool HavePrivateKeys() const override;
584 
585  int64_t GetOldestKeyPoolTime() const override;
586  size_t KeypoolCountExternalKeys() const override;
587  unsigned int GetKeyPoolSize() const override;
588 
589  int64_t GetTimeFirstKey() const override;
590 
591  std::unique_ptr<CKeyMetadata> GetMetadata(const CTxDestination& dest) const override;
592 
593  bool CanGetAddresses(bool internal = false) const override;
594 
595  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const override;
596 
597  bool CanProvide(const CScript& script, SignatureData& sigdata) override;
598 
599  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const override;
600  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const override;
601  TransactionError FillPSBT(PartiallySignedTransaction& psbt, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false, int* n_signed = nullptr) const override;
602 
603  uint256 GetID() const override;
604 
605  void SetInternal(bool internal) override;
606 
607  void SetCache(const DescriptorCache& cache);
608 
609  bool AddKey(const CKeyID& key_id, const CKey& key);
610  bool AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key);
611 
612  bool HasWalletDescriptor(const WalletDescriptor& desc) const;
613  void AddDescriptorKey(const CKey& key, const CPubKey &pubkey);
614  void WriteDescriptor();
615 
617  const std::vector<CScript> GetScriptPubKeys() const;
618 };
619 
620 #endif // BITCOIN_WALLET_SCRIPTPUBKEYMAN_H
void ReturnDestination(int64_t index, bool internal, const CTxDestination &) override
std::unordered_map< CKeyID, CHDChain, KeyIDHasher > m_inactive_hd_chains
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) ...
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
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.
void KeepDestination(int64_t index, const OutputType &type) override
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
const LegacyScriptPubKeyMan & m_spk_man
virtual uint256 GetID() const
void RewriteDB() override
The action to do when the DB needs rewrite.
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
virtual const CKeyingMaterial & GetEncryptionKey() const =0
bool GetCScript(const CScriptID &scriptid, CScript &script) const override
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
TransactionError FillPSBT(PartiallySignedTransaction &psbt, int sighash_type=1, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const override
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
bool Upgrade(int prev_version, int new_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Marks all keys in the keypool up to and including reserve_key as used.
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
virtual int64_t GetTimeFirstKey() const
void SetInternal(bool internal) override
virtual const std::string GetDisplayName() const =0
A UTXO entry.
Definition: coins.h:30
Bilingual messages:
Definition: translation.h:16
isminetype IsMine(const CScript &script) const override
virtual ~ScriptPubKeyMan()
RecursiveMutex cs_KeyStore
uint256 GetID() const override
static void LogPrintf(const char *fmt, const Args &...args)
Definition: logging.h:166
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
SigningResult
Definition: message.h:42
int64_t GetOldestKeyPoolTime() const override
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
Definition: key.h:144
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const override
const std::vector< CScript > GetScriptPubKeys() const
size_t operator()(const CKeyID &id) const
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr)=0
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
std::set< CScript > WatchOnlySet
DescriptorScriptPubKeyMan(WalletStorage &storage, bool internal)
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:61
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
bool SetupDescriptorGeneration(const CExtKey &master_key, OutputType addr_type)
Setup descriptors based on the given CExtkey.
unsigned int GetKeyPoolSize() const override
bool CanGetAddresses(bool internal=false) const override
virtual void RewriteDB()
The action to do when the DB needs rewrite.
bool HasWalletDescriptor(const WalletDescriptor &desc) const
bool GetKey(const CKeyID &address, CKey &key) const override
uint256 GetID() const override
bool HaveKey(const CKeyID &address) const override
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
A version of CTransaction with the PSBT format.
Definition: psbt.h:390
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
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)
CPubKey GenerateNewKey(WalletBatch &batch, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Generate a new key.
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
const WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
virtual WalletDatabase & GetDatabase() const =0
virtual bool IsWalletFlagSet(uint64_t) const =0
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
OutputType
Definition: outputtype.h:17
void Unserialize(Stream &s)
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:14
bool IsHDEnabled() const override
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
void AddInactiveHDChain(const CHDChain &chain)
Access to the wallet database.
Definition: walletdb.h:177
TransactionError FillPSBT(PartiallySignedTransaction &psbt, int sighash_type=1, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
virtual bool IsHDEnabled() const
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
int64_t GetOldestKeyPoolTime() const override
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
virtual void KeepDestination(int64_t index, const OutputType &type)
unsigned int GetKeyPoolSize() const override
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
Like TopUp() but adds keys for inactive HD chains.
bool IsHDEnabled() const override
virtual bool CanProvide(const CScript &script, SignatureData &sigdata)
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
bool error(const char *fmt, const Args &...args)
Definition: system.h:52
size_t KeypoolCountExternalKeys() const override
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
virtual int64_t GetOldestKeyPoolTime() const
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
ScriptPubKeyMan(WalletStorage &storage)
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
virtual bool Upgrade(int prev_version, int new_version, bilingual_str &error)
Upgrades the wallet to the specified version.
virtual bool CanGetAddresses(bool internal=false) const
bool AddWatchOnlyInMem(const CScript &dest)
virtual isminetype IsMine(const CScript &script) const
virtual ~WalletStorage()=default
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
CKeyPool()
Definition: wallet.cpp:4154
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
bool TopUp(unsigned int size=0) override
Fills internal address pool.
An encapsulated public key.
Definition: pubkey.h:31
std::map< CKeyID, CPubKey > WatchKeyMap
Fillable signing provider that keeps keys in an address->secret map.
virtual void MarkUnusedAddresses(const CScript &script)
Mark unused addresses as being used.
Wraps a LegacyScriptPubKeyMan so that it can be returned in a new unique_ptr.
LegacySigningProvider(const LegacyScriptPubKeyMan &spk_man)
void SetHDSeed(const CPubKey &key)
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
std::map< CScript, int32_t > ScriptPubKeyMap
virtual bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false)
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
bool GetKey(const CKeyID &address, CKey &keyOut) const override
isminetype
IsMine() return codes.
Definition: ismine.h:18
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
WalletDescriptor m_wallet_descriptor GUARDED_BY(cs_desc_man)
Descriptor with some wallet metadata.
Definition: walletutil.h:72
bool AddKey(const CKeyID &key_id, const CKey &key)
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal=false)
Fetches a key from the keypool.
virtual bool IsLocked() const =0
virtual TransactionError FillPSBT(PartiallySignedTransaction &psbt, int sighash_type=1, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr) const
Adds script and derivation path information to a PSBT, and optionally signs it.
bool HavePrivateKeys() const override
std::map< int64_t, CKeyID > m_index_to_reserved_key
bool AddCScript(const CScript &redeemScript) override
int64_t GetTimeFirstKey() const override
const std::map< CKeyID, int64_t > & GetAllReserveKeys() const
virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr)
256-bit opaque blob.
Definition: uint256.h:124
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
CPubKey vchPubKey
The public key.
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
virtual bool CanSupportFeature(enum WalletFeature) const =0
const CHDChain & GetHDChain() const
void SetCache(const DescriptorCache &cache)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
virtual unsigned int GetKeyPoolSize() const
virtual SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Sign a message with the given script.
std::map< CKeyID, std::pair< CPubKey, std::vector< unsigned char >>> CryptedKeyMap
An interface to be implemented by keystores that support signing.
virtual std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
WalletBatch *encrypted_batch GUARDED_BY(cs_KeyStore)
virtual bool TopUp(unsigned int size=0)
Fills internal address pool.
const CChainParams & Params()
Return the currently selected parameters.
Cache for single descriptor's derived extended pubkeys.
Definition: descriptor.h:19
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
bool HaveKey(const CKeyID &address) const override
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
std::map< CPubKey, int32_t > PubKeyMap
void AddHDChain(const CHDChain &chain)
bool HaveCScript(const CScriptID &scriptid) const override
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:21
virtual bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch)
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
virtual void SetInternal(bool internal)
bool CanGetAddresses(bool internal=false) const override
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
void Serialize(Stream &s) const
void WalletLogPrintf(std::string fmt, Params...parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
TransactionError
Definition: error.h:22
virtual bool HaveCScript(const CScriptID &hash) const override
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...
void UpgradeKeyMetadata()
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
CPubKey DeriveNewSeed(const CKey &key)
int64_t GetTimeFirstKey() const override
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:88
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
virtual bool HasEncryptionKeys() const =0
A mutable version of CTransaction.
Definition: transaction.h:353
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
virtual std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
void SetInternal(bool internal) override
bool HavePrivateKeys() const override
std::map< CKeyID, CKey > KeyMap
std::map< CKeyID, std::pair< CPubKey, std::vector< unsigned char >>> CryptedKeyMap
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
An encapsulated private key.
Definition: key.h:27
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
virtual bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool)
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool TopUp(unsigned int size=0) override
Fills internal address pool.
virtual bool HavePrivateKeys() const
WalletStorage & m_storage
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:214
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
virtual bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error)
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:25
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
virtual bool SetupGeneration(bool force=false)
Sets up the key generation stuff, i.e.
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
size_t KeypoolCountExternalKeys() const override
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
std::set< CKeyID > GetKeys() const override
virtual size_t KeypoolCountExternalKeys() const
isminetype IsMine(const CScript &script) const override
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
virtual bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, std::string > &input_errors) const
Creates new signatures and adds them to the transaction.
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
std::map< CKeyID, int64_t > m_pool_key_to_index
A key from a CWallet's keypool.
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
An instance of this class represents one database.
Definition: db.h:104