wallet_tests.cpp raw
1 // Copyright (c) 2012-present 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 #include <wallet/wallet.h>
6
7 #include <cstdint>
8 #include <future>
9 #include <memory>
10 #include <vector>
11
12 #include <addresstype.h>
13 #include <interfaces/chain.h>
14 #include <key_io.h>
15 #include <node/blockstorage.h>
16 #include <node/types.h>
17 #include <policy/policy.h>
18 #include <rpc/server.h>
19 #include <script/solver.h>
20 #include <test/util/common.h>
21 #include <test/util/logging.h>
22 #include <test/util/random.h>
23 #include <test/util/setup_common.h>
24 #include <util/translation.h>
25 #include <validation.h>
26 #include <validationinterface.h>
27 #include <wallet/coincontrol.h>
28 #include <wallet/context.h>
29 #include <wallet/receive.h>
30 #include <wallet/spend.h>
31 #include <wallet/test/util.h>
32 #include <wallet/test/wallet_test_fixture.h>
33
34 #include <boost/test/unit_test.hpp>
35 #include <univalue.h>
36
37 using node::MAX_BLOCKFILE_SIZE;
38
39 namespace wallet {
40
41 // Ensure that fee levels defined in the wallet are at least as high
42 // as the default levels for node policy.
43 static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
44 static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
45
46 BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
47
48 static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
49 {
50 CMutableTransaction mtx;
51 mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
52 mtx.vin.push_back({CTxIn{from.GetHash(), index}});
53 FillableSigningProvider keystore;
54 keystore.AddKey(key);
55 std::map<COutPoint, Coin> coins;
56 coins[mtx.vin[0].prevout].out = from.vout[index];
57 std::map<int, bilingual_str> input_errors;
58 BOOST_CHECK(SignTransaction(mtx, &keystore, coins, {.sighash_type = SIGHASH_ALL}, input_errors));
59 return mtx;
60 }
61
62 static void AddKey(CWallet& wallet, const CKey& key)
63 {
64 LOCK(wallet.cs_wallet);
65 FlatSigningProvider provider;
66 std::string error;
67 auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
68 assert(descs.size() == 1);
69 auto& desc = descs.at(0);
70 WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
71 Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
72 }
73
74 BOOST_FIXTURE_TEST_CASE(update_non_range_descriptor, TestingSetup)
75 {
76 CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
77 {
78 LOCK(wallet.cs_wallet);
79 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
80 auto key{GenerateRandomKey()};
81 auto desc_str{"combo(" + EncodeSecret(key) + ")"};
82 FlatSigningProvider provider;
83 std::string error;
84 auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
85 auto& desc{descs.at(0)};
86 WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
87 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
88 // Wallet should update the non-range descriptor successfully
89 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
90 }
91 }
92
93 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
94 {
95 // Cap last block file size, and mine new block in a new block file.
96 CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
97 WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
98 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
99 CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
100
101 // Verify ScanForWalletTransactions fails to read an unknown start block.
102 {
103 CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
104 {
105 LOCK(wallet.cs_wallet);
106 LOCK(Assert(m_node.chainman)->GetMutex());
107 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
108 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
109 }
110 AddKey(wallet, coinbaseKey);
111 WalletRescanReserver reserver(wallet);
112 reserver.reserve();
113 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
114 BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
115 BOOST_CHECK(result.last_failed_block.IsNull());
116 BOOST_CHECK(result.last_scanned_block.IsNull());
117 BOOST_CHECK(!result.last_scanned_height);
118 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
119 }
120
121 // Verify ScanForWalletTransactions picks up transactions in both the old
122 // and new block files.
123 {
124 CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
125 {
126 LOCK(wallet.cs_wallet);
127 LOCK(Assert(m_node.chainman)->GetMutex());
128 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
129 wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
130 }
131 AddKey(wallet, coinbaseKey);
132 WalletRescanReserver reserver(wallet);
133 std::chrono::steady_clock::time_point fake_time;
134 reserver.setNow([&] { fake_time += 60s; return fake_time; });
135 reserver.reserve();
136
137 {
138 CBlockLocator locator;
139 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
140 BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
141 }
142
143 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/true);
144 BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS);
145 BOOST_CHECK(result.last_failed_block.IsNull());
146 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
147 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
148 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
149
150 {
151 CBlockLocator locator;
152 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
153 BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
154 }
155 }
156
157 // Prune the older block file.
158 int file_number;
159 {
160 LOCK(cs_main);
161 file_number = oldTip->GetBlockPos().nFile;
162 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
163 }
164 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
165
166 // Verify ScanForWalletTransactions only picks transactions in the new block
167 // file.
168 {
169 CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
170 {
171 LOCK(wallet.cs_wallet);
172 LOCK(Assert(m_node.chainman)->GetMutex());
173 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
174 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
175 }
176 AddKey(wallet, coinbaseKey);
177 WalletRescanReserver reserver(wallet);
178 reserver.reserve();
179 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/false);
180 BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
181 BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash());
182 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
183 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
184 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
185 }
186
187 // Prune the remaining block file.
188 {
189 LOCK(cs_main);
190 file_number = newTip->GetBlockPos().nFile;
191 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
192 }
193 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
194
195 // Verify ScanForWalletTransactions scans no blocks.
196 {
197 CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
198 {
199 LOCK(wallet.cs_wallet);
200 LOCK(Assert(m_node.chainman)->GetMutex());
201 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
202 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
203 }
204 AddKey(wallet, coinbaseKey);
205 WalletRescanReserver reserver(wallet);
206 reserver.reserve();
207 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/false);
208 BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
209 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
210 BOOST_CHECK(result.last_scanned_block.IsNull());
211 BOOST_CHECK(!result.last_scanned_height);
212 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
213 }
214 }
215
216 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_abort, TestChain100Setup)
217 {
218 CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
219 uint256 genesis_hash;
220 {
221 LOCK(wallet.cs_wallet);
222 LOCK(Assert(m_node.chainman)->GetMutex());
223 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
224 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
225 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
226 }
227
228 // An abort requested while no rescan is held is stale and must
229 // not cancel a later scan.
230 wallet.AbortRescan();
231 WalletRescanReserver reserver(wallet);
232 BOOST_CHECK(reserver.reserve());
233 BOOST_CHECK(!wallet.IsAbortingRescan());
234
235 // An abort requested after the reservation but before the scan starts
236 // (e.g. while importdescriptors is still deriving keys) must cancel the
237 // scan.
238 wallet.AbortRescan();
239 CWallet::ScanResult result = wallet.ScanForWalletTransactions(genesis_hash, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
240 BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::USER_ABORT);
241 BOOST_CHECK(result.last_scanned_block.IsNull());
242 BOOST_CHECK(!result.last_scanned_height);
243 BOOST_CHECK(result.last_failed_block.IsNull());
244 }
245
246 // This test verifies that wallet settings can be added and removed
247 // concurrently, ensuring no race conditions occur during either process.
248 BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
249 {
250 auto chain = m_node.chain.get();
251 const auto NUM_WALLETS{5};
252
253 // Since we're counting the number of wallets, ensure we start without any.
254 BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
255
256 const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
257 std::vector<std::thread> threads;
258 threads.reserve(NUM_WALLETS);
259 for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
260 for (auto& t : threads) t.join();
261
262 auto wallets = chain->getRwSetting("wallet");
263 BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
264 };
265
266 // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
267 check_concurrent_wallet([&chain](int i) {
268 Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
269 },
270 /*num_expected_wallets=*/NUM_WALLETS);
271
272 // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
273 check_concurrent_wallet([&chain](int i) {
274 Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
275 },
276 /*num_expected_wallets=*/0);
277 }
278
279 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, std::chrono::seconds mock_time, int64_t blockTime)
280 {
281 CMutableTransaction tx;
282 TxState state = TxStateInactive{};
283 tx.nLockTime = lockTime;
284 FakeNodeClock clock{mock_time};
285 CBlockIndex* block = nullptr;
286 if (blockTime > 0) {
287 LOCK(cs_main);
288 auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
289 assert(inserted.second);
290 const uint256& hash = inserted.first->first;
291 block = &inserted.first->second;
292 block->nTime = blockTime;
293 block->phashBlock = &hash;
294 state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
295 }
296 return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
297 // Assign wtx.m_state to simplify test and avoid the need to simulate
298 // reorg events. Without this, AddToWallet asserts false when the same
299 // transaction is confirmed in different blocks.
300 wtx.m_state = state;
301 return true;
302 })->nTimeSmart;
303 }
304
305 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
306 // expanded to cover more corner cases of smart time logic.
307 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
308 {
309 // New transaction should use clock time if lower than block time.
310 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100s, 120), 100);
311
312 // Test that updating existing transaction does not change smart time.
313 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200s, 220), 100);
314
315 // New transaction should use clock time if there's no block time.
316 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300s, 0), 300);
317
318 // New transaction should use block time if lower than clock time.
319 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420s, 400), 400);
320
321 // New transaction should use latest entry time if higher than
322 // min(block time, clock time).
323 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500s, 390), 400);
324
325 // If there are future entries, new transaction should use time of the
326 // newest entry that is no more than 300 seconds ahead of the clock time.
327 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50s, 600), 300);
328 }
329
330 void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
331 {
332 node::NodeContext node;
333 auto chain{interfaces::MakeChain(node)};
334 DatabaseOptions options;
335 options.require_format = format;
336 DatabaseStatus status;
337 bilingual_str error;
338 std::vector<bilingual_str> warnings;
339 auto database{MakeWalletDatabase(name, options, status, error)};
340 auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
341 BOOST_CHECK_EQUAL(wallet->PopulateWalletFromDB(error, warnings), DBErrors::LOAD_OK);
342 WITH_LOCK(wallet->cs_wallet, f(wallet));
343 }
344
345 BOOST_FIXTURE_TEST_CASE(LoadReceiveRequests, TestingSetup)
346 {
347 for (DatabaseFormat format : DATABASE_FORMATS) {
348 const std::string name{strprintf("receive-requests-%i", format)};
349 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
350 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
351 WalletBatch batch{wallet->GetDatabase()};
352 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
353 BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
354 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
355 BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
356 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
357 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
358 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
359 });
360 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
361 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
362 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
363 auto requests = wallet->GetAddressReceiveRequests();
364 auto erequests = {"val_rr11", "val_rr20"};
365 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
366 RunWithinTxn(wallet->GetDatabase(), /*process_desc=*/"test", [](WalletBatch& batch){
367 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
368 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
369 return true;
370 });
371 });
372 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
373 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
374 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
375 auto requests = wallet->GetAddressReceiveRequests();
376 auto erequests = {"val_rr11"};
377 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
378 });
379 }
380 }
381
382 class ListCoinsTestingSetup : public TestChain100Setup
383 {
384 public:
385 ListCoinsTestingSetup()
386 {
387 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
388 wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
389 }
390
391 ~ListCoinsTestingSetup()
392 {
393 wallet.reset();
394 }
395
396 CWalletTx& AddTx(CRecipient recipient)
397 {
398 CTransactionRef tx;
399 CCoinControl dummy;
400 {
401 auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
402 BOOST_CHECK(res);
403 tx = res->tx;
404 }
405 wallet->CommitTransaction(tx);
406 CMutableTransaction blocktx;
407 {
408 LOCK(wallet->cs_wallet);
409 blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
410 }
411 CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
412
413 LOCK(wallet->cs_wallet);
414 LOCK(Assert(m_node.chainman)->GetMutex());
415 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
416 auto it = wallet->mapWallet.find(tx->GetHash());
417 BOOST_CHECK(it != wallet->mapWallet.end());
418 it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
419 return it->second;
420 }
421
422 std::unique_ptr<CWallet> wallet;
423 };
424
425 BOOST_FIXTURE_TEST_CASE(ListCoinsTest, ListCoinsTestingSetup)
426 {
427 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
428
429 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
430 // address.
431 std::map<CTxDestination, std::vector<COutput>> list;
432 {
433 LOCK(wallet->cs_wallet);
434 list = ListCoins(*wallet);
435 }
436 BOOST_CHECK_EQUAL(list.size(), 1U);
437 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
438 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
439
440 // Check initial balance from one mature coinbase transaction.
441 BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
442
443 // Add a transaction creating a change address, and confirm ListCoins still
444 // returns the coin associated with the change address underneath the
445 // coinbaseKey pubkey, even though the change address has a different
446 // pubkey.
447 AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
448 {
449 LOCK(wallet->cs_wallet);
450 list = ListCoins(*wallet);
451 }
452 BOOST_CHECK_EQUAL(list.size(), 1U);
453 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
454 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
455
456 // Lock both coins. Confirm number of available coins drops to 0.
457 {
458 LOCK(wallet->cs_wallet);
459 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 2U);
460 }
461 for (const auto& group : list) {
462 for (const auto& coin : group.second) {
463 LOCK(wallet->cs_wallet);
464 wallet->LockCoin(coin.outpoint, /*persist=*/false);
465 }
466 }
467 {
468 LOCK(wallet->cs_wallet);
469 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 0U);
470 }
471 // Confirm ListCoins still returns same result as before, despite coins
472 // being locked.
473 {
474 LOCK(wallet->cs_wallet);
475 list = ListCoins(*wallet);
476 }
477 BOOST_CHECK_EQUAL(list.size(), 1U);
478 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
479 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
480 }
481
482 void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
483 std::map<OutputType, size_t>& expected_coins_sizes)
484 {
485 LOCK(context.wallet->cs_wallet);
486 util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
487 CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
488 CoinFilterParams filter;
489 filter.skip_locked = false;
490 CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
491 // Lock outputs so they are not spent in follow-up transactions
492 for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i}, /*persist=*/false);
493 for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
494 }
495
496 BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
497 {
498 std::map<OutputType, size_t> expected_coins_sizes;
499 for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
500
501 // Verify our wallet has one usable coinbase UTXO before starting
502 // This UTXO is a P2PK, so it should show up in the Other bucket
503 expected_coins_sizes[OutputType::UNKNOWN] = 1U;
504 CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
505 BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
506 BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
507
508 // We will create a self transfer for each of the OutputTypes and
509 // verify it is put in the correct bucket after running GetAvailablecoins
510 //
511 // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
512 // 1. One UTXO as the recipient
513 // 2. One UTXO from the change, due to payment address matching logic
514
515 for (const auto& out_type : OUTPUT_TYPES) {
516 if (out_type == OutputType::UNKNOWN) continue;
517 expected_coins_sizes[out_type] = 2U;
518 TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
519 }
520 }
521
522 BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
523 {
524 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
525 LOCK(wallet->cs_wallet);
526 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
527 wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
528 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
529 }
530
531 // Explicit calculation which is used to test the wallet constant
532 // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
533 static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
534 {
535 // Generate ephemeral valid pubkey
536 CKey key = GenerateRandomKey();
537 CPubKey pubkey = key.GetPubKey();
538
539 // Generate pubkey hash
540 uint160 key_hash(Hash160(pubkey));
541
542 // Create inner-script to enter into keystore. Key hash can't be 0...
543 CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
544
545 // Create outer P2SH script for the output
546 uint160 script_id(Hash160(inner_script));
547 CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
548
549 // Add inner-script to key store and key to watchonly
550 FillableSigningProvider keystore;
551 keystore.AddCScript(inner_script);
552 keystore.AddKeyPubKey(key, pubkey);
553
554 // Fill in dummy signatures for fee calculation.
555 SignatureData sig_data;
556
557 if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
558 // We're hand-feeding it correct arguments; shouldn't happen
559 assert(false);
560 }
561
562 CTxIn tx_in;
563 UpdateInput(tx_in, sig_data);
564 return (size_t)GetVirtualTransactionInputSize(tx_in);
565 }
566
567 BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup)
568 {
569 BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
570 BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
571 }
572
573 bool malformed_descriptor(std::ios_base::failure e)
574 {
575 std::string s(e.what());
576 return s.find("Missing checksum") != std::string::npos;
577 }
578
579 BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
580 {
581 std::vector<unsigned char> malformed_record;
582 VectorWriter vw{malformed_record, 0};
583 vw << std::string("notadescriptor");
584 vw << uint64_t{0};
585 vw << int32_t{0};
586 vw << int32_t{0};
587 vw << int32_t{1};
588
589 SpanReader vr{malformed_record};
590 WalletDescriptor w_desc;
591 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
592 }
593
594 //! Test CWallet::CreateNew() and its behavior handling potential race
595 //! conditions if it's called the same time an incoming transaction shows up in
596 //! the mempool or a new block.
597 //!
598 //! It isn't possible to verify there aren't race condition in every case, so
599 //! this test just checks two specific cases and ensures that timing of
600 //! notifications in these cases doesn't prevent the wallet from detecting
601 //! transactions.
602 //!
603 //! In the first case, block and mempool transactions are created before the
604 //! wallet is loaded, but notifications about these transactions are delayed
605 //! until after it is loaded. The notifications are superfluous in this case, so
606 //! the test verifies the transactions are detected before they arrive.
607 //!
608 //! In the second case, block and mempool transactions are created after the
609 //! wallet rescan and notifications are immediately synced, to verify the wallet
610 //! must already have a handler in place for them, and there's no gap after
611 //! rescanning where new transactions in new blocks could be lost.
612 BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
613 {
614 m_args.ForceSetArg("-unsafesqlitesync", "1");
615 // Create new wallet with known key and unload it.
616 WalletContext context;
617 context.args = &m_args;
618 context.chain = m_node.chain.get();
619 auto wallet = TestCreateWallet(context);
620 CKey key = GenerateRandomKey();
621 AddKey(*wallet, key);
622 TestUnloadWallet(std::move(wallet));
623
624
625 // Add log hook to detect AddToWallet events from rescans, blockConnected,
626 // and transactionAddedToMempool notifications
627 int addtx_count = 0;
628 DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
629 if (s) ++addtx_count;
630 return false;
631 });
632
633
634 bool rescan_completed = false;
635 DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
636 if (s) rescan_completed = true;
637 return false;
638 });
639
640
641 // Block the queue to prevent the wallet receiving blockConnected and
642 // transactionAddedToMempool notifications, and create block and mempool
643 // transactions paying to the wallet
644 std::promise<void> promise;
645 m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
646 promise.get_future().wait();
647 });
648 std::string error;
649 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
650 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
651 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
652 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
653 BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, node::TxBroadcast::MEMPOOL_NO_BROADCAST, error));
654
655
656 // Reload wallet and make sure new transactions are detected despite events
657 // being blocked
658 // Loading will also ask for current mempool transactions
659 wallet = TestLoadWallet(context);
660 BOOST_CHECK(rescan_completed);
661 // AddToWallet events for block_tx and mempool_tx (x2)
662 BOOST_CHECK_EQUAL(addtx_count, 3);
663 {
664 LOCK(wallet->cs_wallet);
665 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
666 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
667 }
668
669
670 // Unblock notification queue and make sure stale blockConnected and
671 // transactionAddedToMempool events are processed
672 promise.set_value();
673 m_node.validation_signals->SyncWithValidationInterfaceQueue();
674 // AddToWallet events for block_tx and mempool_tx events are counted a
675 // second time as the notification queue is processed
676 BOOST_CHECK_EQUAL(addtx_count, 5);
677
678
679 TestUnloadWallet(std::move(wallet));
680
681
682 // Load wallet again, this time creating new block and mempool transactions
683 // paying to the wallet as the wallet finishes loading and syncing the
684 // queue so the events have to be handled immediately. Releasing the wallet
685 // lock during the sync is a little artificial but is needed to avoid a
686 // deadlock during the sync and simulates a new block notification happening
687 // as soon as possible.
688 addtx_count = 0;
689 auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
690 BOOST_CHECK(rescan_completed);
691 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
692 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
693 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
694 mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
695 BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, node::TxBroadcast::MEMPOOL_NO_BROADCAST, error));
696 m_node.validation_signals->SyncWithValidationInterfaceQueue();
697 });
698 wallet = TestLoadWallet(context);
699 // Since mempool transactions are requested at the end of loading, there will
700 // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
701 BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
702 {
703 LOCK(wallet->cs_wallet);
704 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
705 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
706 }
707
708
709 TestUnloadWallet(std::move(wallet));
710 }
711
712 BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
713 {
714 WalletContext context;
715 context.args = &m_args;
716 auto wallet = TestCreateWallet(context);
717 BOOST_CHECK(wallet);
718 WaitForDeleteWallet(std::move(wallet));
719 }
720
721 BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
722 {
723 m_args.ForceSetArg("-unsafesqlitesync", "1");
724 WalletContext context;
725 context.args = &m_args;
726 context.chain = m_node.chain.get();
727 auto wallet = TestCreateWallet(context);
728 CKey key = GenerateRandomKey();
729 AddKey(*wallet, key);
730
731 std::string error;
732 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
733 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
734 CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
735
736 m_node.validation_signals->SyncWithValidationInterfaceQueue();
737
738 {
739 auto block_hash = block_tx.GetHash();
740 auto prev_tx = m_coinbase_txns[0];
741
742 LOCK(wallet->cs_wallet);
743 BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
744 BOOST_CHECK(wallet->mapWallet.contains(block_hash));
745
746 std::vector<Txid> vHashIn{ block_hash };
747 BOOST_CHECK(wallet->RemoveTxs(vHashIn));
748
749 BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
750 BOOST_CHECK(!wallet->mapWallet.contains(block_hash));
751 }
752
753 TestUnloadWallet(std::move(wallet));
754 }
755
756 BOOST_AUTO_TEST_SUITE_END()
757 } // namespace wallet
758