Bitcoin Core 28.99.0
P2P Digital Currency
walletdb.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2022 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 <script/sign.h>
10#include <wallet/db.h>
11#include <wallet/walletutil.h>
12#include <key.h>
13
14#include <stdint.h>
15#include <string>
16#include <vector>
17
18class CScript;
19class uint160;
20class uint256;
21struct CBlockLocator;
22
23namespace wallet {
24class CKeyPool;
25class CMasterKey;
26class CWallet;
27class CWalletTx;
28struct WalletContext;
29
42static const bool DEFAULT_FLUSHWALLET = true;
43
47enum class DBErrors : int
48{
49 LOAD_OK = 0,
50 NEED_RESCAN = 1,
51 NEED_REWRITE = 2,
54 TOO_NEW = 5,
56 LOAD_FAIL = 7,
58 CORRUPT = 9,
59};
60
61namespace DBKeys {
62extern const std::string ACENTRY;
63extern const std::string ACTIVEEXTERNALSPK;
64extern const std::string ACTIVEINTERNALSPK;
65extern const std::string BESTBLOCK;
66extern const std::string BESTBLOCK_NOMERKLE;
67extern const std::string CRYPTED_KEY;
68extern const std::string CSCRIPT;
69extern const std::string DEFAULTKEY;
70extern const std::string DESTDATA;
71extern const std::string FLAGS;
72extern const std::string HDCHAIN;
73extern const std::string KEY;
74extern const std::string KEYMETA;
75extern const std::string LOCKED_UTXO;
76extern const std::string MASTER_KEY;
77extern const std::string MINVERSION;
78extern const std::string NAME;
79extern const std::string OLD_KEY;
80extern const std::string ORDERPOSNEXT;
81extern const std::string POOL;
82extern const std::string PURPOSE;
83extern const std::string SETTINGS;
84extern const std::string TX;
85extern const std::string VERSION;
86extern const std::string WALLETDESCRIPTOR;
87extern const std::string WALLETDESCRIPTORCKEY;
88extern const std::string WALLETDESCRIPTORKEY;
89extern const std::string WATCHMETA;
90extern const std::string WATCHS;
91
92// Keys in this set pertain only to the legacy wallet (LegacyScriptPubKeyMan) and are removed during migration from legacy to descriptors.
93extern const std::unordered_set<std::string> LEGACY_TYPES;
94} // namespace DBKeys
95
96/* simple HD chain data model */
98{
99public:
103 int64_t m_next_external_index{0}; // Next index in the keypool to be used. Memory only.
104 int64_t m_next_internal_index{0}; // Next index in the keypool to be used. Memory only.
105
106 static const int VERSION_HD_BASE = 1;
107 static const int VERSION_HD_CHAIN_SPLIT = 2;
110
112
114 {
115 READWRITE(obj.nVersion, obj.nExternalChainCounter, obj.seed_id);
116 if (obj.nVersion >= VERSION_HD_CHAIN_SPLIT) {
117 READWRITE(obj.nInternalChainCounter);
118 }
119 }
120
121 void SetNull()
122 {
127 }
128
129 bool operator==(const CHDChain& chain) const
130 {
131 return seed_id == chain.seed_id;
132 }
133};
134
136{
137public:
138 static const int VERSION_BASIC=1;
139 static const int VERSION_WITH_HDDATA=10;
140 static const int VERSION_WITH_KEY_ORIGIN = 12;
143 int64_t nCreateTime; // 0 means unknown
144 std::string hdKeypath; //optional HD/bip32 keypath. Still used to determine whether a key is a seed. Also kept for backwards compatibility
145 CKeyID hd_seed_id; //id of the HD seed used to derive this key
146 KeyOriginInfo key_origin; // Key origin info with path and fingerprint
147 bool has_key_origin = false;
148
150 {
151 SetNull();
152 }
153 explicit CKeyMetadata(int64_t nCreateTime_)
154 {
155 SetNull();
156 nCreateTime = nCreateTime_;
157 }
158
160 {
161 READWRITE(obj.nVersion, obj.nCreateTime);
162 if (obj.nVersion >= VERSION_WITH_HDDATA) {
163 READWRITE(obj.hdKeypath, obj.hd_seed_id);
164 }
165 if (obj.nVersion >= VERSION_WITH_KEY_ORIGIN)
166 {
167 READWRITE(obj.key_origin);
168 READWRITE(obj.has_key_origin);
169 }
170 }
171
172 void SetNull()
173 {
175 nCreateTime = 0;
176 hdKeypath.clear();
179 has_key_origin = false;
180 }
181};
182
184{
185 std::function<void()> on_commit, on_abort;
186};
187
196{
197private:
198 template <typename K, typename T>
199 bool WriteIC(const K& key, const T& value, bool fOverwrite = true)
200 {
201 if (!m_batch->Write(key, value, fOverwrite)) {
202 return false;
203 }
205 if (m_database.nUpdateCounter % 1000 == 0) {
206 m_batch->Flush();
207 }
208 return true;
209 }
210
211 template <typename K>
212 bool EraseIC(const K& key)
213 {
214 if (!m_batch->Erase(key)) {
215 return false;
216 }
218 if (m_database.nUpdateCounter % 1000 == 0) {
219 m_batch->Flush();
220 }
221 return true;
222 }
223
224public:
225 explicit WalletBatch(WalletDatabase &database, bool _fFlushOnClose = true) :
226 m_batch(database.MakeBatch(_fFlushOnClose)),
227 m_database(database)
228 {
229 }
230 WalletBatch(const WalletBatch&) = delete;
232
233 bool WriteName(const std::string& strAddress, const std::string& strName);
234 bool EraseName(const std::string& strAddress);
235
236 bool WritePurpose(const std::string& strAddress, const std::string& purpose);
237 bool ErasePurpose(const std::string& strAddress);
238
239 bool WriteTx(const CWalletTx& wtx);
240 bool EraseTx(uint256 hash);
241
242 bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite);
243 bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta);
244 bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta);
245 bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey);
246
247 bool WriteCScript(const uint160& hash, const CScript& redeemScript);
248
249 bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta);
250 bool EraseWatchOnly(const CScript &script);
251
252 bool WriteBestBlock(const CBlockLocator& locator);
253 bool ReadBestBlock(CBlockLocator& locator);
254
255 // Returns true if wallet stores encryption keys
256 bool IsEncrypted();
257
258 bool WriteOrderPosNext(int64_t nOrderPosNext);
259
260 bool ReadPool(int64_t nPool, CKeyPool& keypool);
261 bool WritePool(int64_t nPool, const CKeyPool& keypool);
262 bool ErasePool(int64_t nPool);
263
264 bool WriteMinVersion(int nVersion);
265
266 bool WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey);
267 bool WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret);
268 bool WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor);
269 bool WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index);
270 bool WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
271 bool WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
272 bool WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache);
273
274 bool WriteLockedUTXO(const COutPoint& output);
275 bool EraseLockedUTXO(const COutPoint& output);
276
277 bool WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent);
278 bool WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request);
279 bool EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id);
280 bool EraseAddressData(const CTxDestination& dest);
281
282 bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal);
283 bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal);
284
285 DBErrors LoadWallet(CWallet* pwallet);
286
288 bool WriteHDChain(const CHDChain& chain);
289
291 bool EraseRecords(const std::unordered_set<std::string>& types);
292
293 bool WriteWalletFlags(const uint64_t flags);
295 bool TxnBegin();
297 bool TxnCommit();
299 bool TxnAbort();
300 bool HasActiveTxn() { return m_batch->HasActiveTxn(); }
301
303 void RegisterTxnListener(const DbTxnListener& l);
304
305private:
306 std::unique_ptr<DatabaseBatch> m_batch;
308
309 // External functions listening to the current db txn outcome.
310 // Listeners are cleared at the end of the transaction.
311 std::vector<DbTxnListener> m_txn_listeners;
312};
313
326bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func);
327
330
331bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
332bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
333bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
334bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr);
335} // namespace wallet
336
337#endif // BITCOIN_WALLET_WALLETDB_H
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:140
int flags
Definition: bitcoin-tx.cpp:536
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
An encapsulated public key.
Definition: pubkey.h:34
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
Cache for single descriptor's derived extended pubkeys.
Definition: descriptor.h:19
constexpr void SetNull()
Definition: uint256.h:55
160-bit opaque blob.
Definition: uint256.h:178
256-bit opaque blob.
Definition: uint256.h:190
SERIALIZE_METHODS(CHDChain, obj)
Definition: walletdb.h:113
void SetNull()
Definition: walletdb.h:121
uint32_t nInternalChainCounter
Definition: walletdb.h:101
static const int VERSION_HD_BASE
Definition: walletdb.h:106
uint32_t nExternalChainCounter
Definition: walletdb.h:100
int64_t m_next_external_index
Definition: walletdb.h:103
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:107
CKeyID seed_id
seed hash160
Definition: walletdb.h:102
bool operator==(const CHDChain &chain) const
Definition: walletdb.h:129
int64_t m_next_internal_index
Definition: walletdb.h:104
static const int CURRENT_VERSION
Definition: walletdb.h:108
static const int VERSION_WITH_KEY_ORIGIN
Definition: walletdb.h:140
SERIALIZE_METHODS(CKeyMetadata, obj)
Definition: walletdb.h:159
std::string hdKeypath
Definition: walletdb.h:144
CKeyMetadata(int64_t nCreateTime_)
Definition: walletdb.h:153
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:147
KeyOriginInfo key_origin
Definition: walletdb.h:146
static const int VERSION_BASIC
Definition: walletdb.h:138
static const int VERSION_WITH_HDDATA
Definition: walletdb.h:139
static const int CURRENT_VERSION
Definition: walletdb.h:141
A key from a CWallet's keypool.
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
Definition: crypter.h:35
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:300
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:177
Access to the wallet database.
Definition: walletdb.h:196
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:258
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1361
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:270
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:79
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:1160
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:178
void RegisterTxnListener(const DbTxnListener &l)
Registers db txn callback functions.
Definition: walletdb.cpp:1374
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:184
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition: walletdb.cpp:284
bool EraseTx(uint256 hash)
Definition: walletdb.cpp:101
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:1326
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:152
std::vector< DbTxnListener > m_txn_listeners
Definition: walletdb.h:311
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:221
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:162
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1343
bool WriteAddressPreviouslySpent(const CTxDestination &dest, bool previously_spent)
Definition: walletdb.cpp:1303
bool EraseAddressReceiveRequest(const CTxDestination &dest, const std::string &id)
Definition: walletdb.cpp:1314
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1348
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:74
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:86
WalletBatch & operator=(const WalletBatch &)=delete
std::unique_ptr< DatabaseBatch > m_batch
Definition: walletdb.h:306
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
Definition: walletdb.cpp:1336
WalletBatch(const WalletBatch &)=delete
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:1331
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:106
bool WriteDescriptorLastHardenedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:277
bool WriteIC(const K &key, const T &value, bool fOverwrite=true)
Definition: walletdb.h:199
bool EraseAddressData(const CTxDestination &dest)
Definition: walletdb.cpp:1319
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:201
WalletDatabase & m_database
Definition: walletdb.h:307
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:96
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:111
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:206
bool EraseIC(const K &key)
Definition: walletdb.h:212
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:126
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:91
bool EraseLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:311
WalletBatch(WalletDatabase &database, bool _fFlushOnClose=true)
Definition: walletdb.h:225
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:263
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:249
bool WriteLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:306
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:226
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
Definition: walletdb.cpp:232
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:211
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:238
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:157
bool WriteAddressReceiveRequest(const CTxDestination &dest, const std::string &id, const std::string &receive_request)
Definition: walletdb.cpp:1309
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:216
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:170
An instance of this class represents one database.
Definition: db.h:131
virtual void IncrementUpdateCounter()=0
std::atomic< unsigned int > nUpdateCounter
Definition: db.h:175
Descriptor with some wallet metadata.
Definition: walletutil.h:85
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
CPrivKey is a serialized private key, with all parameters included (SIZE bytes)
Definition: key.h:23
const std::string NAME
Definition: walletdb.cpp:52
const std::string BESTBLOCK
Definition: walletdb.cpp:40
const std::string WALLETDESCRIPTORCKEY
Definition: walletdb.cpp:63
const std::string WATCHS
Definition: walletdb.cpp:66
const std::string POOL
Definition: walletdb.cpp:55
const std::string MINVERSION
Definition: walletdb.cpp:51
const std::string WATCHMETA
Definition: walletdb.cpp:65
const std::string DEFAULTKEY
Definition: walletdb.cpp:43
const std::string OLD_KEY
Definition: walletdb.cpp:53
const std::string WALLETDESCRIPTORKEY
Definition: walletdb.cpp:64
const std::string ACENTRY
Definition: walletdb.cpp:36
const std::string ACTIVEEXTERNALSPK
Definition: walletdb.cpp:37
const std::string TX
Definition: walletdb.cpp:58
const std::string KEY
Definition: walletdb.cpp:48
const std::string CRYPTED_KEY
Definition: walletdb.cpp:41
const std::string DESTDATA
Definition: walletdb.cpp:44
const std::string CSCRIPT
Definition: walletdb.cpp:42
const std::unordered_set< std::string > LEGACY_TYPES
Definition: walletdb.cpp:67
const std::string SETTINGS
Definition: walletdb.cpp:57
const std::string BESTBLOCK_NOMERKLE
Definition: walletdb.cpp:39
const std::string LOCKED_UTXO
Definition: walletdb.cpp:49
const std::string ACTIVEINTERNALSPK
Definition: walletdb.cpp:38
const std::string HDCHAIN
Definition: walletdb.cpp:46
const std::string ORDERPOSNEXT
Definition: walletdb.cpp:54
const std::string FLAGS
Definition: walletdb.cpp:45
const std::string VERSION
Definition: walletdb.cpp:59
const std::string MASTER_KEY
Definition: walletdb.cpp:50
const std::string KEYMETA
Definition: walletdb.cpp:47
const std::string PURPOSE
Definition: walletdb.cpp:56
const std::string WALLETDESCRIPTOR
Definition: walletdb.cpp:60
bool LoadKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:316
void MaybeCompactWalletDB(WalletContext &context)
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
Definition: walletdb.cpp:1276
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Definition: walletdb.cpp:1247
bool LoadCryptedKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:382
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:48
@ EXTERNAL_SIGNER_SUPPORT_REQUIRED
bool LoadEncryptionKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:421
bool LoadHDChain(CWallet *pwallet, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:448
static const bool DEFAULT_FLUSHWALLET
Overview of wallet database classes:
Definition: walletdb.h:42
#define READWRITE(...)
Definition: serialize.h:156
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:124
void clear()
Definition: keyorigin.h:42
std::function< void()> on_commit
Definition: walletdb.h:185
std::function< void()> on_abort
Definition: walletdb.h:185
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:36