Branch data Line data Source code
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 : :
18 : : class CScript;
19 : : class uint160;
20 : : class uint256;
21 : : struct CBlockLocator;
22 : :
23 : : namespace wallet {
24 : : class CKeyPool;
25 : : class CMasterKey;
26 : : class CWallet;
27 : : class CWalletTx;
28 : : struct WalletContext;
29 : :
30 : : /**
31 : : * Overview of wallet database classes:
32 : : *
33 : : * - WalletBatch is an abstract modifier object for the wallet database, and encapsulates a database
34 : : * batch update as well as methods to act on the database. It should be agnostic to the database implementation.
35 : : *
36 : : * The following classes are implementation specific:
37 : : * - BerkeleyEnvironment is an environment in which the database exists.
38 : : * - BerkeleyDatabase represents a wallet database.
39 : : * - BerkeleyBatch is a low-level database batch update.
40 : : */
41 : :
42 : : static const bool DEFAULT_FLUSHWALLET = true;
43 : :
44 : : /** Error statuses for the wallet database.
45 : : * Values are in order of severity. When multiple errors occur, the most severe (highest value) will be returned.
46 : : */
47 : : enum class DBErrors : int
48 : : {
49 : : LOAD_OK = 0,
50 : : NEED_RESCAN = 1,
51 : : NEED_REWRITE = 2,
52 : : EXTERNAL_SIGNER_SUPPORT_REQUIRED = 3,
53 : : NONCRITICAL_ERROR = 4,
54 : : TOO_NEW = 5,
55 : : UNKNOWN_DESCRIPTOR = 6,
56 : : LOAD_FAIL = 7,
57 : : UNEXPECTED_LEGACY_ENTRY = 8,
58 : : CORRUPT = 9,
59 : : };
60 : :
61 : : namespace DBKeys {
62 : : extern const std::string ACENTRY;
63 : : extern const std::string ACTIVEEXTERNALSPK;
64 : : extern const std::string ACTIVEINTERNALSPK;
65 : : extern const std::string BESTBLOCK;
66 : : extern const std::string BESTBLOCK_NOMERKLE;
67 : : extern const std::string CRYPTED_KEY;
68 : : extern const std::string CSCRIPT;
69 : : extern const std::string DEFAULTKEY;
70 : : extern const std::string DESTDATA;
71 : : extern const std::string FLAGS;
72 : : extern const std::string HDCHAIN;
73 : : extern const std::string KEY;
74 : : extern const std::string KEYMETA;
75 : : extern const std::string LOCKED_UTXO;
76 : : extern const std::string MASTER_KEY;
77 : : extern const std::string MINVERSION;
78 : : extern const std::string NAME;
79 : : extern const std::string OLD_KEY;
80 : : extern const std::string ORDERPOSNEXT;
81 : : extern const std::string POOL;
82 : : extern const std::string PURPOSE;
83 : : extern const std::string SETTINGS;
84 : : extern const std::string TX;
85 : : extern const std::string VERSION;
86 : : extern const std::string WALLETDESCRIPTOR;
87 : : extern const std::string WALLETDESCRIPTORCKEY;
88 : : extern const std::string WALLETDESCRIPTORKEY;
89 : : extern const std::string WATCHMETA;
90 : : extern 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.
93 : : extern const std::unordered_set<std::string> LEGACY_TYPES;
94 : : } // namespace DBKeys
95 : :
96 : : /* simple HD chain data model */
97 : : class CHDChain
98 : : {
99 : : public:
100 : : uint32_t nExternalChainCounter;
101 : : uint32_t nInternalChainCounter;
102 : : CKeyID seed_id; //!< seed hash160
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;
108 : : static const int CURRENT_VERSION = VERSION_HD_CHAIN_SPLIT;
109 : : int nVersion;
110 : :
111 : 24705 : CHDChain() { SetNull(); }
112 : :
113 : 68886 : SERIALIZE_METHODS(CHDChain, obj)
114 : : {
115 : 34443 : READWRITE(obj.nVersion, obj.nExternalChainCounter, obj.seed_id);
116 [ + + ]: 34443 : if (obj.nVersion >= VERSION_HD_CHAIN_SPLIT) {
117 : 32423 : READWRITE(obj.nInternalChainCounter);
118 : : }
119 : 34443 : }
120 : :
121 : 24705 : void SetNull()
122 : : {
123 : 24705 : nVersion = CHDChain::CURRENT_VERSION;
124 : 24705 : nExternalChainCounter = 0;
125 : 24705 : nInternalChainCounter = 0;
126 : 24705 : seed_id.SetNull();
127 : : }
128 : :
129 : 56004 : bool operator==(const CHDChain& chain) const
130 : : {
131 [ + + + + : 56004 : return seed_id == chain.seed_id;
+ + ]
132 : : }
133 : : };
134 : :
135 : 482604 : class CKeyMetadata
136 : : {
137 : : public:
138 : : static const int VERSION_BASIC=1;
139 : : static const int VERSION_WITH_HDDATA=10;
140 : : static const int VERSION_WITH_KEY_ORIGIN = 12;
141 : : static const int CURRENT_VERSION=VERSION_WITH_KEY_ORIGIN;
142 : : int nVersion;
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; //!< Whether the key_origin is useful
148 : :
149 : 392425 : CKeyMetadata()
150 : 392425 : {
151 : 392425 : SetNull();
152 : 392425 : }
153 : 34457 : explicit CKeyMetadata(int64_t nCreateTime_)
154 : 34457 : {
155 : 34457 : SetNull();
156 : 34457 : nCreateTime = nCreateTime_;
157 : 34457 : }
158 : :
159 : 128164 : SERIALIZE_METHODS(CKeyMetadata, obj)
160 : : {
161 : 64082 : READWRITE(obj.nVersion, obj.nCreateTime);
162 [ + - ]: 64082 : if (obj.nVersion >= VERSION_WITH_HDDATA) {
163 : 64082 : READWRITE(obj.hdKeypath, obj.hd_seed_id);
164 : : }
165 [ + + ]: 64082 : if (obj.nVersion >= VERSION_WITH_KEY_ORIGIN)
166 : : {
167 : 63903 : READWRITE(obj.key_origin);
168 : 63903 : READWRITE(obj.has_key_origin);
169 : : }
170 : 64082 : }
171 : :
172 : 426882 : void SetNull()
173 : : {
174 : 426882 : nVersion = CKeyMetadata::CURRENT_VERSION;
175 : 426882 : nCreateTime = 0;
176 : 426882 : hdKeypath.clear();
177 : 426882 : hd_seed_id.SetNull();
178 : 426882 : key_origin.clear();
179 : 426882 : has_key_origin = false;
180 : 426882 : }
181 : : };
182 : :
183 : : /** Access to the wallet database.
184 : : * Opens the database and provides read and write access to it. Each read and write is its own transaction.
185 : : * Multiple operation transactions can be started using TxnBegin() and committed using TxnCommit()
186 : : * Otherwise the transaction will be committed when the object goes out of scope.
187 : : * Optionally (on by default) it will flush to disk on close.
188 : : * Every 1000 writes will automatically trigger a flush to disk.
189 : : */
190 [ - - # # : 259490 : class WalletBatch
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
+ + - + -
+ - + - +
- - - + -
+ - - + -
+ + - + -
- + - - +
- ][ + + +
+ - + - +
- + + - +
- - - +
- ][ - - -
- - + - +
- + + - -
- - - -
- ]
191 : : {
192 : : private:
193 : : template <typename K, typename T>
194 : 487950 : bool WriteIC(const K& key, const T& value, bool fOverwrite = true)
195 : : {
196 [ + + ]: 487950 : if (!m_batch->Write(key, value, fOverwrite)) {
197 : : return false;
198 : : }
199 : 480992 : m_database.IncrementUpdateCounter();
200 [ + + ]: 480992 : if (m_database.nUpdateCounter % 1000 == 0) {
201 : 45366 : m_batch->Flush();
202 : : }
203 : : return true;
204 : : }
205 : :
206 : : template <typename K>
207 : 21518 : bool EraseIC(const K& key)
208 : : {
209 [ + - ]: 21518 : if (!m_batch->Erase(key)) {
210 : : return false;
211 : : }
212 : 21518 : m_database.IncrementUpdateCounter();
213 [ + + ]: 21518 : if (m_database.nUpdateCounter % 1000 == 0) {
214 : 5054 : m_batch->Flush();
215 : : }
216 : : return true;
217 : : }
218 : :
219 : : public:
220 : 259493 : explicit WalletBatch(WalletDatabase &database, bool _fFlushOnClose = true) :
221 [ + - - - : 259493 : m_batch(database.MakeBatch(_fFlushOnClose)),
- - # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - ][ - -
+ - + - +
- + - + -
+ - + - +
- - - + -
+ - + - -
- + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - +
- + + - -
+ - + - +
- + - + -
- - + - +
- + - ][ -
- - - - -
- - - - +
- + - + -
+ - - - +
- + - + -
- - - - +
- + - -
- ]
222 [ + - + - ]: 259490 : m_database(database)
[ + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - - -
+ - + - +
- + - - -
+ - - - +
- + - + -
+ - # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
+ - + - +
- + - + -
- - + - +
- + - +
- ][ - - -
- - - - -
- - - - +
- + - + -
+ - + - +
- + - + -
- - + - -
- - - - -
+ - + - +
- - - ]
223 : : {
224 : 110 : }
225 : : WalletBatch(const WalletBatch&) = delete;
226 : : WalletBatch& operator=(const WalletBatch&) = delete;
227 : :
228 : : bool WriteName(const std::string& strAddress, const std::string& strName);
229 : : bool EraseName(const std::string& strAddress);
230 : :
231 : : bool WritePurpose(const std::string& strAddress, const std::string& purpose);
232 : : bool ErasePurpose(const std::string& strAddress);
233 : :
234 : : bool WriteTx(const CWalletTx& wtx);
235 : : bool EraseTx(uint256 hash);
236 : :
237 : : bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite);
238 : : bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta);
239 : : bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta);
240 : : bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey);
241 : :
242 : : bool WriteCScript(const uint160& hash, const CScript& redeemScript);
243 : :
244 : : bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta);
245 : : bool EraseWatchOnly(const CScript &script);
246 : :
247 : : bool WriteBestBlock(const CBlockLocator& locator);
248 : : bool ReadBestBlock(CBlockLocator& locator);
249 : :
250 : : // Returns true if wallet stores encryption keys
251 : : bool IsEncrypted();
252 : :
253 : : bool WriteOrderPosNext(int64_t nOrderPosNext);
254 : :
255 : : bool ReadPool(int64_t nPool, CKeyPool& keypool);
256 : : bool WritePool(int64_t nPool, const CKeyPool& keypool);
257 : : bool ErasePool(int64_t nPool);
258 : :
259 : : bool WriteMinVersion(int nVersion);
260 : :
261 : : bool WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey);
262 : : bool WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret);
263 : : bool WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor);
264 : : bool WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index);
265 : : bool WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
266 : : bool WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
267 : : bool WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache);
268 : :
269 : : bool WriteLockedUTXO(const COutPoint& output);
270 : : bool EraseLockedUTXO(const COutPoint& output);
271 : :
272 : : bool WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent);
273 : : bool WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request);
274 : : bool EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id);
275 : : bool EraseAddressData(const CTxDestination& dest);
276 : :
277 : : bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal);
278 : : bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal);
279 : :
280 : : DBErrors LoadWallet(CWallet* pwallet);
281 : :
282 : : //! write the hdchain model (external chain child index counter)
283 : : bool WriteHDChain(const CHDChain& chain);
284 : :
285 : : //! Delete records of the given types
286 : : bool EraseRecords(const std::unordered_set<std::string>& types);
287 : :
288 : : bool WriteWalletFlags(const uint64_t flags);
289 : : //! Begin a new transaction
290 : : bool TxnBegin();
291 : : //! Commit current transaction
292 : : bool TxnCommit();
293 : : //! Abort current transaction
294 : : bool TxnAbort();
295 : : private:
296 : : std::unique_ptr<DatabaseBatch> m_batch;
297 : : WalletDatabase& m_database;
298 : : };
299 : :
300 : : /**
301 : : * Executes the provided function 'func' within a database transaction context.
302 : : *
303 : : * This function ensures that all db modifications performed within 'func()' are
304 : : * atomically committed to the db at the end of the process. And, in case of a
305 : : * failure during execution, all performed changes are rolled back.
306 : : *
307 : : * @param database The db connection instance to perform the transaction on.
308 : : * @param process_desc A description of the process being executed, used for logging purposes in the event of a failure.
309 : : * @param func The function to be executed within the db txn context. It returns a boolean indicating whether to commit or roll back the txn.
310 : : * @return true if the db txn executed successfully, false otherwise.
311 : : */
312 : : bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func);
313 : :
314 : : //! Compacts BDB state so that wallet.dat is self-contained (if there are changes)
315 : : void MaybeCompactWalletDB(WalletContext& context);
316 : :
317 : : bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
318 : : bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
319 : : bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
320 : : bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr);
321 : : } // namespace wallet
322 : :
323 : : #endif // BITCOIN_WALLET_WALLETDB_H
|