forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 7
/
walletload_tests.cpp
368 lines (309 loc) · 16.4 KB
/
walletload_tests.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright (c) 2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.
#include <test/util/logging.h>
#include <test/util/setup_common.h>
#include <wallet/test/util.h>
#include <wallet/wallet.h>
#include <boost/test/unit_test.hpp>
namespace wallet {
BOOST_AUTO_TEST_SUITE(walletload_tests)
class DummyDescriptor final : public Descriptor
{
private:
std::string desc;
public:
explicit DummyDescriptor(const std::string& descriptor) : desc(descriptor){};
~DummyDescriptor() = default;
std::string ToString(bool compat_format) const override { return desc; }
std::optional<OutputType> GetOutputType() const override { return OutputType::UNKNOWN; }
bool IsRange() const override { return false; }
bool IsSolvable() const override { return false; }
bool IsSingleType() const override { return true; }
bool ToPrivateString(const SigningProvider& provider, std::string& out) const override { return false; }
bool ToNormalizedString(const SigningProvider& provider, std::string& out, const DescriptorCache* cache = nullptr) const override { return false; }
bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const override { return false; };
bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const override { return false; }
void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const override {}
std::optional<int64_t> ScriptSize() const override { return {}; }
std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
};
BOOST_FIXTURE_TEST_CASE(wallet_load_descriptors, TestingSetup)
{
std::unique_ptr<WalletDatabase> database = CreateMockableWalletDatabase();
{
// Write unknown active descriptor
WalletBatch batch(*database, false);
std::string unknown_desc = "trx(tpubD6NzVbkrYhZ4Y4S7m6Y5s9GD8FqEMBy56AGphZXuagajudVZEnYyBahZMgHNCTJc2at82YX6s8JiL1Lohu5A3v1Ur76qguNH4QVQ7qYrBQx/86'/1'/0'/0/*)#8pn8tzdt";
WalletDescriptor wallet_descriptor(std::make_shared<DummyDescriptor>(unknown_desc), 0, 0, 0, 0);
BOOST_CHECK(batch.WriteDescriptor(uint256(), wallet_descriptor));
BOOST_CHECK(batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(OutputType::UNKNOWN), uint256(), false));
}
{
// Now try to load the wallet and verify the error.
const std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(database)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::UNKNOWN_DESCRIPTOR);
}
// Test 2
// Now write a valid descriptor with an invalid ID.
// As the software produces another ID for the descriptor, the loading process must be aborted.
database = CreateMockableWalletDatabase();
// Verify the error
bool found = false;
DebugLogHelper logHelper("The descriptor ID calculated by the wallet differs from the one in DB", [&](const std::string* s) {
found = true;
return false;
});
{
// Write valid descriptor with invalid ID
WalletBatch batch(*database, false);
std::string desc = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
WalletDescriptor wallet_descriptor(std::make_shared<DummyDescriptor>(desc), 0, 0, 0, 0);
BOOST_CHECK(batch.WriteDescriptor(uint256::ONE, wallet_descriptor));
}
{
// Now try to load the wallet and verify the error.
const std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(database)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT);
BOOST_CHECK(found); // The error must be logged
}
}
bool HasAnyRecordOfType(WalletDatabase& db, const std::string& key)
{
std::unique_ptr<DatabaseBatch> batch = db.MakeBatch(false);
BOOST_CHECK(batch);
std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
BOOST_CHECK(cursor);
while (true) {
DataStream ssKey{};
DataStream ssValue{};
DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
assert(status != DatabaseCursor::Status::FAIL);
if (status == DatabaseCursor::Status::DONE) break;
std::string type;
ssKey >> type;
if (type == key) return true;
}
return false;
}
template<typename... Args>
SerializeData MakeSerializeData(const Args&... args)
{
DataStream s{};
SerializeMany(s, args...);
return {s.begin(), s.end()};
}
BOOST_FIXTURE_TEST_CASE(wallet_load_ckey, TestingSetup)
{
SerializeData ckey_record_key;
SerializeData ckey_record_value;
MockableData records;
{
// Context setup.
// Create and encrypt legacy wallet
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase()));
LOCK(wallet->cs_wallet);
auto legacy_spkm = wallet->GetOrCreateLegacyScriptPubKeyMan();
BOOST_CHECK(legacy_spkm->SetupGeneration(true));
// Retrieve a key
CTxDestination dest = *Assert(legacy_spkm->GetNewDestination(OutputType::LEGACY));
CKeyID key_id = GetKeyForDestination(*legacy_spkm, dest);
CKey first_key;
BOOST_CHECK(legacy_spkm->GetKey(key_id, first_key));
// Encrypt the wallet
BOOST_CHECK(wallet->EncryptWallet("encrypt"));
wallet->Flush();
// Store a copy of all the records
records = GetMockableDatabase(*wallet).m_records;
// Get the record for the retrieved key
ckey_record_key = MakeSerializeData(DBKeys::CRYPTED_KEY, first_key.GetPubKey());
ckey_record_value = records.at(ckey_record_key);
}
{
// First test case:
// Erase all the crypted keys from db and unlock the wallet.
// The wallet will only re-write the crypted keys to db if any checksum is missing at load time.
// So, if any 'ckey' record re-appears on db, then the checksums were not properly calculated, and we are re-writing
// the records every time that 'CWallet::Unlock' gets called, which is not good.
// Load the wallet and check that is encrypted
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
BOOST_CHECK(wallet->IsCrypted());
BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY));
// Now delete all records and check that the 'Unlock' function doesn't re-write them
BOOST_CHECK(wallet->GetLegacyScriptPubKeyMan()->DeleteRecords());
BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY));
BOOST_CHECK(wallet->Unlock("encrypt"));
BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY));
}
{
// Second test case:
// Verify that loading up a 'ckey' with no checksum triggers a complete re-write of the crypted keys.
// Cut off the 32 byte checksum from a ckey record
records[ckey_record_key].resize(ckey_record_value.size() - 32);
// Load the wallet and check that is encrypted
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
BOOST_CHECK(wallet->IsCrypted());
BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY));
// Now delete all ckey records and check that the 'Unlock' function re-writes them
// (this is because the wallet, at load time, found a ckey record with no checksum)
BOOST_CHECK(wallet->GetLegacyScriptPubKeyMan()->DeleteRecords());
BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY));
BOOST_CHECK(wallet->Unlock("encrypt"));
BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY));
}
{
// Third test case:
// Verify that loading up a 'ckey' with an invalid checksum throws an error.
// Cut off the 32 byte checksum from a ckey record
records[ckey_record_key].resize(ckey_record_value.size() - 32);
// Fill in the checksum space with 0s
records[ckey_record_key].resize(ckey_record_value.size());
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT);
}
{
// Fourth test case:
// Verify that loading up a 'ckey' with an invalid pubkey throws an error
CPubKey invalid_key;
BOOST_CHECK(!invalid_key.IsValid());
SerializeData key = MakeSerializeData(DBKeys::CRYPTED_KEY, invalid_key);
records[key] = ckey_record_value;
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT);
}
}
BOOST_FIXTURE_TEST_CASE(wallet_load_verif_crypted_blsct, TestingSetup)
{
// The test duplicates the db so each case has its own db instance.
int NUMBER_OF_TESTS = 5;
std::vector<std::unique_ptr<WalletDatabase>> dbs;
blsct::PrivateKey viewKey, spendKey, tokenKey;
blsct::DoublePublicKey dest;
auto get_db = [](std::vector<std::unique_ptr<WalletDatabase>>& dbs) {
std::unique_ptr<WalletDatabase> db = std::move(dbs.back());
dbs.pop_back();
return db;
};
{ // Context setup.
// Create and encrypt blsct wallet
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase()));
wallet->InitWalletFlags(wallet::WALLET_FLAG_BLSCT);
LOCK(wallet->cs_wallet);
auto blsct_km = wallet->GetOrCreateBLSCTKeyMan();
BOOST_CHECK(blsct_km->SetupGeneration({}, blsct::IMPORT_MASTER_KEY, true));
// Get the keys in the wallet before encryption
auto masterKeysMetadata = blsct_km->GetHDChain();
blsct::SubAddress recvAddress = blsct_km->GetSubAddress();
dest = recvAddress.GetKeys();
viewKey = blsct_km->viewKey;
BOOST_CHECK(viewKey.IsValid());
BOOST_CHECK(blsct_km->GetKey(masterKeysMetadata.spend_id, spendKey));
BOOST_CHECK(blsct_km->GetKey(masterKeysMetadata.token_id, tokenKey));
// Encrypt the wallet and duplicate database
BOOST_CHECK(wallet->EncryptWallet("encrypt"));
wallet->Flush();
for (int i = 0; i < NUMBER_OF_TESTS; i++) {
dbs.emplace_back(DuplicateMockDatabase(wallet->GetDatabase()));
}
}
{
// First test case:
// Erase all the crypted keys from db and unlock the wallet.
// The wallet will only re-write the crypted keys to db if any checksum is missing at load time.
// So, if any 'cblsctkey' record re-appears on db, then the checksums were not properly calculated, and we are re-writing
// the records every time that 'CWallet::Unlock' gets called, which is not good.
// Load the wallet and check that is encrypted
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", get_db(dbs)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
BOOST_CHECK(wallet->IsCrypted());
BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_BLSCTKEY));
// Now delete all records and check that the 'Unlock' function doesn't re-write them
BOOST_CHECK(wallet->GetBLSCTKeyMan()->DeleteRecords());
BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_BLSCTKEY));
BOOST_CHECK(wallet->Unlock("encrypt"));
BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_BLSCTKEY));
}
{
// Second test case:
// Verify that loading up a 'cblsctkey' with no checksum triggers a complete re-write of the crypted keys.
std::unique_ptr<WalletDatabase> db = get_db(dbs);
{
std::unique_ptr<DatabaseBatch> batch = db->MakeBatch(false);
std::pair<std::vector<unsigned char>, uint256> value;
BOOST_CHECK(batch->Read(std::make_pair(DBKeys::CRYPTED_BLSCTKEY, spendKey.GetPublicKey()), value));
const auto key = std::make_pair(DBKeys::CRYPTED_BLSCTKEY, spendKey.GetPublicKey());
BOOST_CHECK(batch->Write(key, value.first, /*fOverwrite=*/true));
}
// Load the wallet and check that is encrypted
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(db)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
BOOST_CHECK(wallet->IsCrypted());
BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_BLSCTKEY));
// Now delete all cblsctkey records and check that the 'Unlock' function re-writes them
// (this is because the wallet, at load time, found a cblsctkey record with no checksum)
BOOST_CHECK(wallet->GetBLSCTKeyMan()->DeleteKeys());
BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_BLSCTKEY));
BOOST_CHECK(wallet->Unlock("encrypt"));
BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_BLSCTKEY));
}
{
// Third test case:
// Verify that loading up a 'cblsctkey' with an invalid checksum throws an error.
std::unique_ptr<WalletDatabase> db = get_db(dbs);
{
std::unique_ptr<DatabaseBatch> batch = db->MakeBatch(false);
std::vector<unsigned char> crypted_data;
BOOST_CHECK(batch->Read(std::make_pair(DBKeys::CRYPTED_BLSCTKEY, spendKey.GetPublicKey()), crypted_data));
// Write an invalid checksum
std::pair<std::vector<unsigned char>, uint256> value = std::make_pair(crypted_data, uint256::ONE);
const auto key = std::make_pair(DBKeys::CRYPTED_BLSCTKEY, spendKey.GetPublicKey());
BOOST_CHECK(batch->Write(key, value, /*fOverwrite=*/true));
}
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(db)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT);
}
{
// Fourth test case:
// Verify that loading up a 'cblsctkey' with an invalid pubkey throws an error
std::unique_ptr<WalletDatabase> db = get_db(dbs);
{
CPubKey invalid_key;
BOOST_CHECK(!invalid_key.IsValid());
const auto key = std::make_pair(DBKeys::CRYPTED_KEY, invalid_key);
std::pair<std::vector<unsigned char>, uint256> value;
BOOST_CHECK(db->MakeBatch(false)->Write(key, value, /*fOverwrite=*/true));
}
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(db)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT);
}
{
// Fifth test case:
// Verify that keys and addresses are not re-generated after encryption
std::unique_ptr<WalletDatabase> db = get_db(dbs);
std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(db)));
BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
blsct::PrivateKey viewKey2, spendKey2, tokenKey2;
auto blsct_km = wallet->GetBLSCTKeyMan();
BOOST_CHECK(blsct_km != nullptr);
// Get the keys in the wallet before encryption
auto masterKeysMetadata = blsct_km->GetHDChain();
blsct::SubAddress recvAddress = blsct_km->GetSubAddress();
blsct::DoublePublicKey dest2 = recvAddress.GetKeys();
viewKey2 = blsct_km->viewKey;
BOOST_CHECK(viewKey.IsValid());
BOOST_CHECK(!blsct_km->GetKey(masterKeysMetadata.spend_id, spendKey2));
BOOST_CHECK(!blsct_km->GetKey(masterKeysMetadata.token_id, tokenKey2));
BOOST_CHECK(wallet->Unlock("encrypt"));
BOOST_CHECK(blsct_km->GetKey(masterKeysMetadata.spend_id, spendKey2));
BOOST_CHECK(blsct_km->GetKey(masterKeysMetadata.token_id, tokenKey2));
BOOST_CHECK(dest == dest2);
BOOST_CHECK(viewKey == viewKey2);
BOOST_CHECK(spendKey == spendKey2);
BOOST_CHECK(tokenKey == tokenKey2);
}
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace wallet