Bitcoin Core  31.0.0
P2P Digital Currency
walletdb.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-present The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_WALLET_WALLETDB_H
7 #define BITCOIN_WALLET_WALLETDB_H
8 
9 #include <key.h>
11 #include <script/sign.h>
12 #include <wallet/db.h>
13 #include <wallet/walletutil.h>
14 
15 #include <cstdint>
16 #include <string>
17 #include <vector>
18 
19 class CScript;
20 class uint160;
21 class uint256;
22 struct CBlockLocator;
23 
24 namespace wallet {
25 class CMasterKey;
26 class CWallet;
27 class CWalletTx;
28 struct WalletContext;
29 
30 // Logs information about the database, including available engines, features, and other capabilities
31 void LogDBInfo();
32 
43 enum class DBErrors : int
44 {
45  LOAD_OK = 0,
46  NEED_RESCAN = 1,
47  NEED_REWRITE = 2,
50  TOO_NEW = 5,
52  LOAD_FAIL = 7,
54  LEGACY_WALLET = 9,
55  CORRUPT = 10,
56 };
57 
58 namespace DBKeys {
59 extern const std::string ACENTRY;
60 extern const std::string ACTIVEEXTERNALSPK;
61 extern const std::string ACTIVEINTERNALSPK;
62 extern const std::string BESTBLOCK;
63 extern const std::string BESTBLOCK_NOMERKLE;
64 extern const std::string CRYPTED_KEY;
65 extern const std::string CSCRIPT;
66 extern const std::string DEFAULTKEY;
67 extern const std::string DESTDATA;
68 extern const std::string FLAGS;
69 extern const std::string HDCHAIN;
70 extern const std::string KEY;
71 extern const std::string KEYMETA;
72 extern const std::string LOCKED_UTXO;
73 extern const std::string MASTER_KEY;
74 extern const std::string MINVERSION;
75 extern const std::string NAME;
76 extern const std::string OLD_KEY;
77 extern const std::string ORDERPOSNEXT;
78 extern const std::string POOL;
79 extern const std::string PURPOSE;
80 extern const std::string SETTINGS;
81 extern const std::string TX;
82 extern const std::string VERSION;
83 extern const std::string WALLETDESCRIPTOR;
84 extern const std::string WALLETDESCRIPTORCKEY;
85 extern const std::string WALLETDESCRIPTORKEY;
86 extern const std::string WATCHMETA;
87 extern const std::string WATCHS;
88 
89 // Keys in this set pertain only to the legacy wallet (LegacyScriptPubKeyMan) and are removed during migration from legacy to descriptors.
90 extern const std::unordered_set<std::string> LEGACY_TYPES;
91 } // namespace DBKeys
92 
93 /* simple HD chain data model */
94 class CHDChain
95 {
96 public:
100  int64_t m_next_external_index{0}; // Next index in the keypool to be used. Memory only.
101  int64_t m_next_internal_index{0}; // Next index in the keypool to be used. Memory only.
102 
103  static const int VERSION_HD_BASE = 1;
104  static const int VERSION_HD_CHAIN_SPLIT = 2;
106  int nVersion;
107 
108  CHDChain() { SetNull(); }
109 
111  {
112  READWRITE(obj.nVersion, obj.nExternalChainCounter, obj.seed_id);
113  if (obj.nVersion >= VERSION_HD_CHAIN_SPLIT) {
114  READWRITE(obj.nInternalChainCounter);
115  }
116  }
117 
118  void SetNull()
119  {
123  seed_id.SetNull();
124  }
125 
126  bool operator==(const CHDChain& chain) const
127  {
128  return seed_id == chain.seed_id;
129  }
130 };
131 
133 {
134 public:
135  static const int VERSION_BASIC=1;
136  static const int VERSION_WITH_HDDATA=10;
137  static const int VERSION_WITH_KEY_ORIGIN = 12;
139  int nVersion;
140  int64_t nCreateTime; // 0 means unknown
141  std::string hdKeypath; //optional HD/bip32 keypath. Still used to determine whether a key is a seed. Also kept for backwards compatibility
142  CKeyID hd_seed_id; //id of the HD seed used to derive this key
143  KeyOriginInfo key_origin; // Key origin info with path and fingerprint
144  bool has_key_origin = false;
145 
147  {
148  SetNull();
149  }
150  explicit CKeyMetadata(int64_t nCreateTime_)
151  {
152  SetNull();
153  nCreateTime = nCreateTime_;
154  }
155 
157  {
158  READWRITE(obj.nVersion, obj.nCreateTime);
159  if (obj.nVersion >= VERSION_WITH_HDDATA) {
160  READWRITE(obj.hdKeypath, obj.hd_seed_id);
161  }
162  if (obj.nVersion >= VERSION_WITH_KEY_ORIGIN)
163  {
164  READWRITE(obj.key_origin);
165  READWRITE(obj.has_key_origin);
166  }
167  }
168 
169  void SetNull()
170  {
172  nCreateTime = 0;
173  hdKeypath.clear();
175  key_origin.clear();
176  has_key_origin = false;
177  }
178 };
179 
181 {
182  std::function<void()> on_commit, on_abort;
183 };
184 
193 {
194 private:
195  template <typename K, typename T>
196  bool WriteIC(const K& key, const T& value, bool fOverwrite = true)
197  {
198  if (!m_batch->Write(key, value, fOverwrite)) {
199  return false;
200  }
201  return true;
202  }
203 
204  template <typename K>
205  bool EraseIC(const K& key)
206  {
207  if (!m_batch->Erase(key)) {
208  return false;
209  }
210  return true;
211  }
212 
213 public:
214  explicit WalletBatch(WalletDatabase &database) :
215  m_batch(database.MakeBatch())
216  {
217  }
218  WalletBatch(const WalletBatch&) = delete;
219  WalletBatch& operator=(const WalletBatch&) = delete;
220 
221  bool WriteName(const std::string& strAddress, const std::string& strName);
222  bool EraseName(const std::string& strAddress);
223 
224  bool WritePurpose(const std::string& strAddress, const std::string& purpose);
225  bool ErasePurpose(const std::string& strAddress);
226 
227  bool WriteTx(const CWalletTx& wtx);
228  bool EraseTx(Txid hash);
229 
230  bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, bool overwrite);
231  bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta);
232  bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta);
233  bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey);
234  bool EraseMasterKey(unsigned int id);
235 
236  bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta);
237  bool EraseWatchOnly(const CScript &script);
238 
239  bool WriteBestBlock(const CBlockLocator& locator);
240  bool ReadBestBlock(CBlockLocator& locator);
241 
242  // Returns true if wallet stores encryption keys
243  bool IsEncrypted();
244 
245  bool WriteOrderPosNext(int64_t nOrderPosNext);
246 
247  bool WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey);
248  bool WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret);
249  bool WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor);
250  bool WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index);
251  bool WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
252  bool WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
253  bool WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache);
254 
255  bool WriteLockedUTXO(const COutPoint& output);
256  bool EraseLockedUTXO(const COutPoint& output);
257 
258  bool WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent);
259  bool WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request);
260  bool EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id);
261  bool EraseAddressData(const CTxDestination& dest);
262 
263  bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal);
264  bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal);
265 
266  DBErrors LoadWallet(CWallet* pwallet);
267 
269  bool WriteVersion(int client_version) { return m_batch->Write(DBKeys::VERSION, CLIENT_VERSION); }
270 
272  bool EraseRecords(const std::unordered_set<std::string>& types);
273 
274  bool WriteWalletFlags(uint64_t flags);
276  bool TxnBegin();
278  bool TxnCommit();
280  bool TxnAbort();
281  bool HasActiveTxn() { return m_batch->HasActiveTxn(); }
282 
284  void RegisterTxnListener(const DbTxnListener& l);
285 
286 private:
287  std::unique_ptr<DatabaseBatch> m_batch;
288 
289  // External functions listening to the current db txn outcome.
290  // Listeners are cleared at the end of the transaction.
291  std::vector<DbTxnListener> m_txn_listeners;
292 };
293 
306 bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func);
307 
308 bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
309 bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
310 bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
311 bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr);
312 
316 } // namespace wallet
317 
318 #endif // BITCOIN_WALLET_WALLETDB_H
const std::string MASTER_KEY
Definition: walletdb.cpp:46
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
Definition: crypter.h:34
std::function< void()> on_abort
Definition: walletdb.h:182
const std::string BESTBLOCK_NOMERKLE
Definition: walletdb.cpp:35
const std::string SETTINGS
Definition: walletdb.cpp:53
const std::string CRYPTED_KEY
Definition: walletdb.cpp:37
bool EraseAddressData(const CTxDestination &dest)
Definition: walletdb.cpp:1242
const std::string NAME
Definition: walletdb.cpp:48
const std::string HDCHAIN
Definition: walletdb.cpp:42
void SetNull()
Definition: walletdb.h:118
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:144
const std::string ACENTRY
Definition: walletdb.cpp:32
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:116
const std::string VERSION
Definition: walletdb.cpp:55
const std::string DESTDATA
Definition: walletdb.cpp:40
CKeyMetadata(int64_t nCreateTime_)
Definition: walletdb.h:150
DBErrors
Overview of wallet database classes:
Definition: walletdb.h:43
const std::string WALLETDESCRIPTORCKEY
Definition: walletdb.cpp:59
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition: walletdb.cpp:260
const std::string BESTBLOCK
Definition: walletdb.cpp:36
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:225
uint32_t nExternalChainCounter
Definition: walletdb.h:97
int64_t m_next_internal_index
Definition: walletdb.h:101
bool WriteAddressReceiveRequest(const CTxDestination &dest, const std::string &id, const std::string &receive_request)
Definition: walletdb.cpp:1232
const std::string WALLETDESCRIPTOR
Definition: walletdb.cpp:56
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:151
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1279
bool LoadHDChain(CWallet *pwallet, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:421
const std::string KEY
Definition: walletdb.cpp:44
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:169
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:125
std::function< void()> on_commit
Definition: walletdb.h:182
bool WriteLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:282
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, bool overwrite)
Definition: walletdb.cpp:108
Access to the wallet database.
Definition: walletdb.h:192
const std::string CSCRIPT
Definition: walletdb.cpp:38
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:200
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:183
const std::string PURPOSE
Definition: walletdb.cpp:52
const std::string MINVERSION
Definition: walletdb.cpp:47
std::unique_ptr< DatabaseBatch > m_batch
Definition: walletdb.h:287
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:234
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:217
const std::string WALLETDESCRIPTORKEY
Definition: walletdb.cpp:60
RAII class that provides access to a WalletDatabase.
Definition: db.h:50
const std::unordered_set< std::string > LEGACY_TYPES
Definition: walletdb.cpp:63
int64_t m_next_external_index
Definition: walletdb.h:100
void clear()
Definition: keyorigin.h:42
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:177
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
CPrivKey is a serialized private key, with all parameters included (SIZE bytes)
Definition: key.h:24
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:194
const std::string WATCHMETA
Definition: walletdb.cpp:61
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:81
bool LoadEncryptionKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:394
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:1103
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:161
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1266
KeyOriginInfo key_origin
Definition: walletdb.h:143
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:205
static const int VERSION_WITH_HDDATA
Definition: walletdb.h:136
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:239
bool WriteAddressPreviouslySpent(const CTxDestination &dest, bool previously_spent)
Definition: walletdb.cpp:1226
bool LoadCryptedKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:355
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:132
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:98
std::string hdKeypath
Definition: walletdb.h:141
static const int VERSION_WITH_KEY_ORIGIN
Definition: walletdb.h:137
An encapsulated public key.
Definition: pubkey.h:33
const std::string POOL
Definition: walletdb.cpp:51
bool EraseTx(Txid hash)
Definition: walletdb.cpp:103
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
Definition: walletdb.cpp:1254
void RegisterTxnListener(const DbTxnListener &l)
Registers db txn callback functions.
Definition: walletdb.cpp:1292
static const int CURRENT_VERSION
Definition: walletdb.h:138
uint32_t nInternalChainCounter
Definition: walletdb.h:98
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:309
bool HasLegacyRecords(CWallet &wallet)
Returns true if there are any DBKeys::LEGACY_TYPES record in the wallet db.
Definition: walletdb.cpp:506
std::vector< DbTxnListener > m_txn_listeners
Definition: walletdb.h:291
static const int VERSION_BASIC
Definition: walletdb.h:135
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
const std::string FLAGS
Definition: walletdb.cpp:41
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:93
Descriptor with some wallet metadata.
Definition: walletutil.h:63
SERIALIZE_METHODS(CHDChain, obj)
Definition: walletdb.h:110
const std::string ACTIVEINTERNALSPK
Definition: walletdb.cpp:34
const std::string KEYMETA
Definition: walletdb.cpp:43
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:246
int flags
Definition: bitcoin-tx.cpp:529
256-bit opaque blob.
Definition: uint256.h:195
bool LoadKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:292
bool EraseIC(const K &key)
Definition: walletdb.h:205
const std::string ACTIVEEXTERNALSPK
Definition: walletdb.cpp:33
constexpr void SetNull()
Definition: uint256.h:55
bool WriteVersion(int client_version)
Write the given client_version.
Definition: walletdb.h:269
Cache for single descriptor&#39;s derived extended pubkeys.
Definition: descriptor.h:19
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
bool EraseAddressReceiveRequest(const CTxDestination &dest, const std::string &id)
Definition: walletdb.cpp:1237
bool WriteWalletFlags(uint64_t flags)
Definition: walletdb.cpp:1249
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
WalletBatch(WalletDatabase &database)
Definition: walletdb.h:214
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1261
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:113
const std::string LOCKED_UTXO
Definition: walletdb.cpp:45
160-bit opaque blob.
Definition: uint256.h:183
SERIALIZE_METHODS(CKeyMetadata, obj)
Definition: walletdb.h:156
static const int VERSION_HD_BASE
Definition: walletdb.h:103
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:76
bool WriteIC(const K &key, const T &value, bool fOverwrite=true)
Definition: walletdb.h:196
const std::string DEFAULTKEY
Definition: walletdb.cpp:39
bool operator==(const CHDChain &chain) const
Definition: walletdb.h:126
bool EraseLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:287
void LogDBInfo()
Definition: walletdb.cpp:66
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
Definition: walletdb.cpp:211
const std::string ORDERPOSNEXT
Definition: walletdb.cpp:50
#define READWRITE(...)
Definition: serialize.h:145
static const int CURRENT_VERSION
Definition: walletdb.h:105
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Definition: walletdb.cpp:1197
static const int CLIENT_VERSION
Definition: clientversion.h:26
const std::string WATCHS
Definition: walletdb.cpp:62
bool EraseMasterKey(unsigned int id)
Definition: walletdb.cpp:156
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:88
CKeyID seed_id
seed hash160
Definition: walletdb.h:99
WalletBatch & operator=(const WalletBatch &)=delete
An instance of this class represents one database.
Definition: db.h:129
const std::string OLD_KEY
Definition: walletdb.cpp:49
const std::string TX
Definition: walletdb.cpp:54
bool WriteDescriptorLastHardenedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:253
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:104