Bitcoin Core 32.99.0
P2P Digital Currency
wallet_tests.cpp
Go to the documentation of this file.
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/scan.h>
6#include <wallet/wallet.h>
7
8#include <array>
9#include <cstddef>
10#include <cstdint>
11#include <future>
12#include <limits>
13#include <memory>
14#include <optional>
15#include <string>
16#include <utility>
17#include <vector>
18
19#include <addresstype.h>
20#include <blockfilter.h>
21#include <chain.h>
24#include <interfaces/chain.h>
25#include <key_io.h>
26#include <logging.h>
27#include <node/blockstorage.h>
28#include <node/types.h>
29#include <policy/policy.h>
30#include <rpc/server.h>
31#include <script/descriptor.h>
32#include <script/solver.h>
33#include <test/util/common.h>
34#include <test/util/logging.h>
35#include <test/util/random.h>
37#include <util/byte_units.h>
38#include <util/translation.h>
39#include <validation.h>
40#include <validationinterface.h>
41#include <wallet/coincontrol.h>
42#include <wallet/context.h>
43#include <wallet/imports.h>
44#include <wallet/receive.h>
45#include <wallet/spend.h>
46#include <wallet/test/util.h>
48
49#include <boost/test/unit_test.hpp>
50#include <univalue.h>
51
53
54namespace wallet {
55
56// Ensure that fee levels defined in the wallet are at least as high
57// as the default levels for node policy.
58static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
59static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
60
61BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
62
63static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
64{
66 mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
67 mtx.vin.push_back({CTxIn{from.GetHash(), index}});
69 keystore.AddKey(key);
70 std::map<COutPoint, Coin> coins;
71 coins[mtx.vin[0].prevout].out = from.vout[index];
72 std::map<int, bilingual_str> input_errors;
73 BOOST_CHECK(SignTransaction(mtx, &keystore, coins, {.sighash_type = SIGHASH_ALL}, input_errors));
74 return mtx;
75}
76
77static void AddKey(CWallet& wallet, const CKey& key)
78{
79 LOCK(wallet.cs_wallet);
81 std::string error;
82 auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
83 assert(descs.size() == 1);
84 auto& desc = descs.at(0);
85 WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
86 Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
87}
88
89BOOST_AUTO_TEST_CASE(reject_invalid_descriptor_ranges)
90{
91 const int height{*Assert(m_node.chain->getHeight())};
92 {
93 LOCK(m_wallet.cs_wallet);
94 m_wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
95 m_wallet.SetLastBlockProcessed(height, m_node.chain->getBlockHash(height));
96 }
97
98 CExtKey ext_key;
99 ext_key.SetSeed(std::array<std::byte, 32>{});
100 const std::string descriptor_without_checksum{"wpkh(" + EncodeExtKey(ext_key) + "/*)"};
101 const std::string descriptor{descriptor_without_checksum + "#" + GetDescriptorChecksum(descriptor_without_checksum)};
102
103 const std::array invalid_ranges{
104 std::pair{std::pair<int64_t, int64_t>{2, 1}, "Range specified as [begin,end] must not have begin after end"},
105 std::pair{std::pair<int64_t, int64_t>{-1, 10}, "Range should be greater or equal than 0"},
106 std::pair{std::pair<int64_t, int64_t>{0, 1'000'000}, "Range is too large"},
107 std::pair{std::pair<int64_t, int64_t>{0, std::numeric_limits<int64_t>::max()}, "End of range is too high"},
108 std::pair{std::pair<int64_t, int64_t>{0, 1LL << 31}, "End of range is too high"},
109 };
110
111 for (const auto& [range, expected_error] : invalid_ranges) {
112 std::vector requests{ImportDescriptorRequest{
113 .descriptor = descriptor,
114 .label = {},
115 .timestamp = 0,
116 .active = false,
117 .internal = std::nullopt,
118 .range = range,
119 .next_index = std::nullopt,
120 }};
121 const auto results{ProcessDescriptorsImport(m_wallet, requests)};
122 BOOST_REQUIRE_EQUAL(results.size(), 1U);
123 BOOST_REQUIRE(results.front().error.has_value());
124 BOOST_CHECK(results.front().error->wallet_error.code == WalletErrorCode::InvalidParameter);
125 BOOST_CHECK_EQUAL(results.front().error->wallet_error.message.original, expected_error);
126 BOOST_CHECK(!results.front().error->is_general_error);
127 }
128}
129
130BOOST_FIXTURE_TEST_CASE(update_non_range_descriptor, TestingSetup)
131{
133 {
134 LOCK(wallet.cs_wallet);
135 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
136 auto key{GenerateRandomKey()};
137 auto desc_str{"combo(" + EncodeSecret(key) + ")"};
139 std::string error;
140 auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
141 auto& desc{descs.at(0)};
142 WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
143 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
144 // Wallet should update the non-range descriptor successfully
145 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
146 }
147}
148
149BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
150{
151 // Cap last block file size, and mine new block in a new block file.
152 CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
153 WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
154 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
155 CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
156
157 // Verify Scan fails to read an unknown start block.
158 {
160 {
161 LOCK(wallet.cs_wallet);
162 LOCK(Assert(m_node.chainman)->GetMutex());
163 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
164 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
165 }
166 AddKey(wallet, coinbaseKey);
168 reserver.reserve();
169 ScanResult result = wallet.Scanner().Scan(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
174 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
175 }
176
177 // Verify Scan picks up transactions in both the old
178 // and new block files.
179 {
181 {
182 LOCK(wallet.cs_wallet);
183 LOCK(Assert(m_node.chainman)->GetMutex());
184 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
185 wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
186 }
187 AddKey(wallet, coinbaseKey);
189 std::chrono::steady_clock::time_point fake_time;
190 reserver.setNow([&] { fake_time += 60s; return fake_time; });
191 reserver.reserve();
192
193 {
194 CBlockLocator locator;
195 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
196 BOOST_REQUIRE(!locator.IsNull());
197 BOOST_CHECK(locator.vHave.front() == newTip->GetBlockHash());
198 }
199
200 ScanResult result = wallet.Scanner().Scan(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/true);
203 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
204 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
205 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
206
207 {
208 CBlockLocator locator;
209 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
210 BOOST_REQUIRE(!locator.IsNull());
211 BOOST_CHECK(locator.vHave.front() == newTip->GetBlockHash());
212 }
213 }
214
215 // Prune the older block file.
216 int file_number;
217 {
218 LOCK(cs_main);
219 file_number = oldTip->GetBlockPos().nFile;
220 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
221 }
222 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
223
224 // Verify Scan only picks transactions in the new block
225 // file.
226 {
228 {
229 LOCK(wallet.cs_wallet);
230 LOCK(Assert(m_node.chainman)->GetMutex());
231 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
232 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
233 }
234 AddKey(wallet, coinbaseKey);
236 reserver.reserve();
237 ScanResult result = wallet.Scanner().Scan(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/false);
240 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
241 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
242 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
243 }
244
245 // Prune the remaining block file.
246 {
247 LOCK(cs_main);
248 file_number = newTip->GetBlockPos().nFile;
249 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
250 }
251 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
252
253 // Verify Scan scans no blocks.
254 {
256 {
257 LOCK(wallet.cs_wallet);
258 LOCK(Assert(m_node.chainman)->GetMutex());
259 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
260 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
261 }
262 AddKey(wallet, coinbaseKey);
264 reserver.reserve();
265 ScanResult result = wallet.Scanner().Scan(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/false);
267 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
270 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
271 }
272}
273
274BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_reorged_block, TestChain100Setup)
275{
276 BOOST_REQUIRE(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1_MiB, /*f_memory=*/true));
278 BOOST_REQUIRE(filter_index.Init());
279 filter_index.Sync();
280
281 // Reorg the tip out of the active chain: invalidate it, then mine a
282 // longer replacement branch paying a script unrelated to the wallets
283 // below.
284 CBlockIndex* stale_block = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
285 const uint256 stale_hash{stale_block->GetBlockHash()};
286 const int stale_height{stale_block->nHeight};
288 BOOST_REQUIRE(m_node.chainman->ActiveChainstate().InvalidateBlock(state, stale_block));
289 const CScript replacement_script{GetScriptForRawPubKey(GenerateRandomKey().GetPubKey())};
290 CreateAndProcessBlock({}, replacement_script);
291 CreateAndProcessBlock({}, replacement_script);
292 BOOST_REQUIRE(filter_index.BlockUntilSyncedToCurrentChain());
293 {
294 LOCK(Assert(m_node.chainman)->GetMutex());
295 BOOST_REQUIRE(!m_node.chainman->ActiveChain().Contains(*stale_block));
296 BOOST_REQUIRE_EQUAL(m_node.chainman->ActiveChain().Height(), stale_height + 1);
297 }
298
299 {
300 BlockFilter filter;
301 BOOST_REQUIRE(filter_index.LookupFilter(stale_block, filter));
302 }
303
304 // Test wallet whose scripts do not match the stale block's filter.
305 {
307 {
308 LOCK(wallet.cs_wallet);
309 LOCK(Assert(m_node.chainman)->GetMutex());
310 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
311 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
312 }
314 reserver.reserve();
315 ScanResult result = wallet.Scanner().Scan(stale_hash, stale_height, /*max_height=*/{}, reserver, /*save_progress=*/false);
318 BOOST_CHECK_EQUAL(result.last_scanned_block, stale_hash);
319 BOOST_CHECK_EQUAL(*result.last_scanned_height, stale_height);
320 }
321
322 // Test wallet whose scripts do match the stale block's filter.
323 {
325 {
326 LOCK(wallet.cs_wallet);
327 LOCK(Assert(m_node.chainman)->GetMutex());
328 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
329 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
330 }
331 AddKey(wallet, coinbaseKey); // the stale block's coinbase pays coinbaseKey
333 reserver.reserve();
334 ScanResult result = wallet.Scanner().Scan(stale_hash, stale_height, /*max_height=*/{}, reserver, /*save_progress=*/false);
336 BOOST_CHECK_EQUAL(result.last_failed_block, stale_hash);
339 BOOST_CHECK(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.empty()));
340 }
341
342 // Prune the stale block's file — the block is now not active AND unreadable.
343 int file_number;
344 {
345 LOCK(cs_main);
346 file_number = stale_block->GetBlockPos().nFile;
347 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
348 }
349 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
350
351 {
353 {
354 LOCK(wallet.cs_wallet);
355 LOCK(Assert(m_node.chainman)->GetMutex());
356 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
357 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
358 }
359 AddKey(wallet, coinbaseKey);
361 reserver.reserve();
362 ScanResult result = wallet.Scanner().Scan(stale_hash, stale_height, /*max_height=*/{}, reserver, /*save_progress=*/false);
364 BOOST_CHECK_EQUAL(result.last_failed_block, stale_hash);
367 BOOST_CHECK(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.empty()));
368 }
369
370 filter_index.Stop();
372}
373
374BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_abort, TestChain100Setup)
375{
377 uint256 genesis_hash;
378 {
379 LOCK(wallet.cs_wallet);
380 LOCK(Assert(m_node.chainman)->GetMutex());
381 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
382 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
383 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
384 }
385
386 // An abort requested while no rescan is held is stale and must
387 // not cancel a later scan.
388 wallet.Scanner().Abort();
390 BOOST_CHECK(reserver.reserve());
391 BOOST_CHECK(!wallet.Scanner().IsAborting());
392
393 // An abort requested after the reservation but before the scan starts
394 // (e.g. while importdescriptors is still deriving keys) must cancel the
395 // scan.
396 wallet.Scanner().Abort();
397 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
402}
403
404BOOST_FIXTURE_TEST_CASE(wallet_rescan_reserver, TestingSetup)
405{
407
408 // No scan in progress: accessors report idle state.
409 BOOST_CHECK(!wallet.Scanner().IsScanning());
410 BOOST_CHECK(wallet.Scanner().ScanningDuration() == SteadyClock::duration{});
411 BOOST_CHECK_EQUAL(wallet.Scanner().ScanningProgress(), 0.0);
412
413 {
414 WalletRescanReserver first_reserver(wallet);
415 BOOST_CHECK(first_reserver.reserve());
416 BOOST_CHECK(first_reserver.isReserved());
417 BOOST_CHECK(wallet.Scanner().IsScanning());
418 BOOST_CHECK(!wallet.Scanner().IsScanningWithPassphrase());
419 BOOST_CHECK_EQUAL(wallet.Scanner().ScanningProgress(), 0.0);
420
421 // Only one reservation can be held at a time.
422 WalletRescanReserver second_reserver(wallet);
423 BOOST_CHECK(!second_reserver.reserve());
424 BOOST_CHECK(!second_reserver.isReserved());
425 }
426 // Destroying the reserver (RAII) clears the scanning state.
427 BOOST_CHECK(!wallet.Scanner().IsScanning());
428
429 {
430 WalletRescanReserver passphrase_reserver(wallet);
431 BOOST_CHECK(passphrase_reserver.reserve(/*with_passphrase=*/true));
432 BOOST_CHECK(wallet.Scanner().IsScanningWithPassphrase());
433 }
434 BOOST_CHECK(!wallet.Scanner().IsScanningWithPassphrase());
435}
436
437BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_bounded, TestChain100Setup)
438{
439 uint256 genesis_hash, max_hash, tip_hash;
440 int max_height, tip_height;
441 {
442 LOCK(Assert(m_node.chainman)->GetMutex());
443 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
444 tip_height = m_node.chainman->ActiveChain().Height();
445 tip_hash = m_node.chainman->ActiveChain().Tip()->GetBlockHash();
446 max_height = tip_height - 2;
447 max_hash = m_node.chainman->ActiveChain()[max_height]->GetBlockHash();
448 }
449
450 // A scan with max_height set stops exactly at max_height and does not
451 // sync any blocks beyond it.
452 {
454 {
455 LOCK(wallet.cs_wallet);
456 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
457 wallet.SetLastBlockProcessed(tip_height, tip_hash);
458 }
459 AddKey(wallet, coinbaseKey);
461 reserver.reserve();
462 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, max_height, reserver, /*save_progress=*/false);
465 BOOST_CHECK_EQUAL(result.last_scanned_block, max_hash);
466 BOOST_CHECK_EQUAL(*result.last_scanned_height, max_height);
467 // One coinbase per block from height 1 through max_height.
468 BOOST_CHECK_EQUAL(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.size()), static_cast<size_t>(max_height));
469 }
470
471 // A single-block range (start == max_height == tip) scans exactly that
472 // block.
473 {
475 {
476 LOCK(wallet.cs_wallet);
477 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
478 wallet.SetLastBlockProcessed(tip_height, tip_hash);
479 }
480 AddKey(wallet, coinbaseKey);
482 reserver.reserve();
483 ScanResult result = wallet.Scanner().Scan(tip_hash, tip_height, tip_height, reserver, /*save_progress=*/false);
486 BOOST_CHECK_EQUAL(result.last_scanned_block, tip_hash);
487 BOOST_CHECK_EQUAL(*result.last_scanned_height, tip_height);
488 BOOST_CHECK_EQUAL(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.size()), 1U);
489 }
490}
491
492BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_tip_extension, TestChain100Setup)
493{
495 uint256 genesis_hash;
496 int start_tip_height{0};
497 {
498 LOCK(wallet.cs_wallet);
499 LOCK(Assert(m_node.chainman)->GetMutex());
500 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
501 start_tip_height = m_node.chainman->ActiveChain().Height();
502 wallet.SetLastBlockProcessed(start_tip_height, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
503 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
504 }
505 AddKey(wallet, coinbaseKey);
506
507 // Connect a block while the scan is running (the handler fires on the
508 // scanning thread as the scan starts) and advance the wallet's tip, as
509 // the blockConnected notification would. The scan must pick up the new
510 // tip instead of stopping at the height it started with.
511 uint256 new_tip_hash;
512 bool extended{false};
513 auto handler = wallet.ShowProgress.connect([&](const std::string&, int) {
514 if (extended) return;
515 extended = true;
516 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
517 LOCK(wallet.cs_wallet);
518 LOCK(Assert(m_node.chainman)->GetMutex());
519 const CBlockIndex* new_tip = m_node.chainman->ActiveChain().Tip();
520 new_tip_hash = new_tip->GetBlockHash();
521 wallet.SetLastBlockProcessed(new_tip->nHeight, new_tip_hash);
522 });
523
525 reserver.reserve();
526 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
527 handler.disconnect();
529 BOOST_CHECK_EQUAL(result.last_scanned_block, new_tip_hash);
530 BOOST_CHECK_EQUAL(*result.last_scanned_height, start_tip_height + 1);
531}
532
533BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_no_progress_saved, TestChain100Setup)
534{
536 uint256 genesis_hash, tip_hash;
537 int max_height;
538 {
539 LOCK(wallet.cs_wallet);
540 LOCK(Assert(m_node.chainman)->GetMutex());
541 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
542 tip_hash = m_node.chainman->ActiveChain().Tip()->GetBlockHash();
543 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), tip_hash);
544 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
545 max_height = m_node.chainman->ActiveChain().Height() - 2;
546 }
547 AddKey(wallet, coinbaseKey);
548
550 // Advance the clock on every call so that every scanned block would be
551 // eligible for a progress write if save_progress were set.
552 std::chrono::steady_clock::time_point fake_time;
553 reserver.setNow([&] { fake_time += 60s; return fake_time; });
554 reserver.reserve();
555
556 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, max_height, reserver, /*save_progress=*/false);
558
559 // With save_progress=false the scan must not touch the wallet's best
560 // block record: it still points at the tip written when the descriptor
561 // was added, not at any block the scan visited.
562 CBlockLocator locator;
563 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
564 BOOST_CHECK(!locator.IsNull());
565 BOOST_CHECK_EQUAL(locator.vHave.front(), tip_hash);
566}
567
569{
570 // Cap last block file size, and mine new block in a new block file.
571 CBlockIndex* old_tip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
572 WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(old_tip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
573 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
574 CBlockIndex* new_tip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
575
576 // Prune the older block file.
577 int file_number;
578 {
579 LOCK(cs_main);
580 file_number = old_tip->GetBlockPos().nFile;
581 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
582 }
583 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
584
586 {
587 LOCK(wallet.cs_wallet);
588 LOCK(Assert(m_node.chainman)->GetMutex());
589 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
590 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
591 }
592 AddKey(wallet, coinbaseKey);
594 reserver.reserve();
595
596 // Blocks before the prune point cannot be read: the returned timestamp
597 // is moved past the last unreadable block, telling the caller from when
598 // the rescan is actually complete.
599 const int64_t genesis_time{WITH_LOCK(::cs_main, return m_node.chainman->ActiveChain().Genesis()->GetBlockTime())};
600 BOOST_CHECK_EQUAL(wallet.Scanner().ScanFromTime(genesis_time, reserver),
601 WITH_LOCK(::cs_main, return old_tip->GetBlockTimeMax()) + TIMESTAMP_WINDOW + 1);
602
603 bool scan_logged{false};
604 DebugLogHelper scan_check{"Rescan started from block", [&](const std::string* s) {
605 if (s) scan_logged = true;
606 return false;
607 }};
608 // A timestamp past the tip requires no scanning and is returned unchanged.
609 const int64_t future_time{WITH_LOCK(::cs_main, return new_tip->GetBlockTimeMax()) + TIMESTAMP_WINDOW + 1};
610 BOOST_CHECK(!scan_logged);
611 BOOST_CHECK_EQUAL(wallet.Scanner().ScanFromTime(future_time, reserver), future_time);
612}
613
614BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_missing_filter, TestChain100Setup)
615{
616 // Enable the block filter index but do not sync it: no filters are
617 // available, so the scan must inspect every block rather than treat
618 // the missing filters as misses and skip blocks.
619 BOOST_REQUIRE(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1_MiB, /*f_memory=*/true));
621 BOOST_REQUIRE(filter_index.Init());
622
623 {
625 uint256 genesis_hash, tip_hash;
626 int tip_height;
627 {
628 LOCK(wallet.cs_wallet);
629 LOCK(Assert(m_node.chainman)->GetMutex());
630 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
631 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
632 tip_height = m_node.chainman->ActiveChain().Height();
633 auto tip{m_node.chainman->ActiveChain().Tip()};
634 tip_hash = tip->GetBlockHash();
635 wallet.SetLastBlockProcessed(tip_height, tip_hash);
636 BlockFilter filter;
637 BOOST_REQUIRE(!filter_index.LookupFilter(tip, filter));
638 }
639 AddKey(wallet, coinbaseKey);
641 reserver.reserve();
642 bool fast_scan_logged{false};
643 DebugLogHelper scan_check{"fast variant using block filters", [&](const std::string* s) {
644 if (s) fast_scan_logged = true;
645 return false;
646 }};
647 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
648 BOOST_REQUIRE(fast_scan_logged);
651 BOOST_CHECK_EQUAL(result.last_scanned_block, tip_hash);
652 BOOST_CHECK_EQUAL(*result.last_scanned_height, tip_height);
653 // One coinbase per block from height 1 through the tip.
654 BOOST_CHECK_EQUAL(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.size()), static_cast<size_t>(tip_height));
655 }
656
657 filter_index.Stop();
659}
660
664BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_attach_chain, TestChain100Setup)
665{
666 // Do not wait for sqlite to flush data to disk to improve performance
667 m_args.ForceSetArg("-unsafesqlitesync", "1");
668
669 // Create a wallet owning the coinbases, and unload it at the current tip.
670 WalletContext context;
671 context.args = &m_args;
672 context.chain = m_node.chain.get();
673 auto wallet = TestCreateWallet(context);
674 AddKey(*wallet, coinbaseKey);
675 TestUnloadWallet(std::move(wallet));
676
677 // Extend the chain while the wallet is not loaded.
678 constexpr int NEW_BLOCKS{5};
679 for (int i = 0; i < NEW_BLOCKS; ++i) {
680 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
681 }
682
683 int tip_height;
684 uint256 tip_hash;
685 {
686 LOCK(Assert(m_node.chainman)->GetMutex());
687 tip_height = m_node.chainman->ActiveChain().Height();
688 tip_hash = m_node.chainman->ActiveChain().Tip()->GetBlockHash();
689 }
690
691 // Loading the wallet must rescan the extension from the recorded best
692 // block and find its coinbases.
693 wallet = TestLoadWallet(context);
694 {
695 LOCK(wallet->cs_wallet);
696 BOOST_CHECK_EQUAL(wallet->GetLastBlockHeight(), tip_height);
697 BOOST_CHECK_EQUAL(wallet->GetLastBlockHash(), tip_hash);
698 // The extension's coinbases plus the one of the recorded best block:
699 // the load rescan starts mid-chain, at that block inclusive.
700 BOOST_CHECK_EQUAL(wallet->mapWallet.size(), static_cast<size_t>(NEW_BLOCKS + 1));
701 }
702 TestUnloadWallet(std::move(wallet));
703}
704
705// This test verifies that wallet settings can be added and removed
706// concurrently, ensuring no race conditions occur during either process.
707BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
708{
709 auto chain = m_node.chain.get();
710 const auto NUM_WALLETS{5};
711
712 // Since we're counting the number of wallets, ensure we start without any.
713 BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
714
715 const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
716 std::vector<std::thread> threads;
717 threads.reserve(NUM_WALLETS);
718 for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
719 for (auto& t : threads) t.join();
720
721 auto wallets = chain->getRwSetting("wallet");
722 BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
723 };
724
725 // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
726 check_concurrent_wallet([&chain](int i) {
727 Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
728 },
729 /*num_expected_wallets=*/NUM_WALLETS);
730
731 // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
732 check_concurrent_wallet([&chain](int i) {
733 Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
734 },
735 /*num_expected_wallets=*/0);
736}
737
738static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, std::chrono::seconds mock_time, int64_t blockTime)
739{
741 TxState state = TxStateInactive{};
742 tx.nLockTime = lockTime;
743 FakeNodeClock clock{mock_time};
744 CBlockIndex* block = nullptr;
745 if (blockTime > 0) {
746 LOCK(cs_main);
747 auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
748 assert(inserted.second);
749 const uint256& hash = inserted.first->first;
750 block = &inserted.first->second;
751 block->nTime = blockTime;
752 block->phashBlock = &hash;
753 state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
754 }
755 return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
756 // Assign wtx.m_state to simplify test and avoid the need to simulate
757 // reorg events. Without this, AddToWallet asserts false when the same
758 // transaction is confirmed in different blocks.
759 wtx.m_state = state;
760 return true;
761 })->nTimeSmart;
762}
763
764// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
765// expanded to cover more corner cases of smart time logic.
766BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
767{
768 // New transaction should use clock time if lower than block time.
769 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100s, 120), 100);
770
771 // Test that updating existing transaction does not change smart time.
772 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200s, 220), 100);
773
774 // New transaction should use clock time if there's no block time.
775 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300s, 0), 300);
776
777 // New transaction should use block time if lower than clock time.
778 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420s, 400), 400);
779
780 // New transaction should use latest entry time if higher than
781 // min(block time, clock time).
782 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500s, 390), 400);
783
784 // If there are future entries, new transaction should use time of the
785 // newest entry that is no more than 300 seconds ahead of the clock time.
786 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50s, 600), 300);
787}
788
789void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
790{
792 auto chain{interfaces::MakeChain(node)};
793 DatabaseOptions options;
794 options.require_format = format;
795 DatabaseStatus status;
796 bilingual_str error;
797 std::vector<bilingual_str> warnings;
798 auto database{MakeWalletDatabase(name, options, status, error)};
799 auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
800 BOOST_CHECK_EQUAL(wallet->PopulateWalletFromDB(error, warnings), DBErrors::LOAD_OK);
801 WITH_LOCK(wallet->cs_wallet, f(wallet));
802}
803
805{
807 const std::string name{strprintf("receive-requests-%i", format)};
808 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
809 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
810 WalletBatch batch{wallet->GetDatabase()};
811 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
812 BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
813 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
814 BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
815 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
816 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
817 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
818 });
819 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
820 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
821 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
822 auto requests = wallet->GetAddressReceiveRequests();
823 auto erequests = {"val_rr11", "val_rr20"};
824 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
825 RunWithinTxn(wallet->GetDatabase(), /*process_desc=*/"test", [](WalletBatch& batch){
826 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
827 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
828 return true;
829 });
830 });
831 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
832 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
833 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
834 auto requests = wallet->GetAddressReceiveRequests();
835 auto erequests = {"val_rr11"};
836 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
837 });
838 }
839}
840
842{
843public:
845 {
846 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
847 wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
848 }
849
851 {
852 wallet.reset();
853 }
854
856 {
858 CCoinControl dummy;
859 {
860 auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
861 BOOST_CHECK(res);
862 tx = res->tx;
863 }
864 wallet->CommitTransaction(tx);
865 CMutableTransaction blocktx;
866 {
867 LOCK(wallet->cs_wallet);
868 blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).GetTx());
869 }
870 CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
871
872 LOCK(wallet->cs_wallet);
873 LOCK(Assert(m_node.chainman)->GetMutex());
874 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
875 auto it = wallet->mapWallet.find(tx->GetHash());
876 BOOST_CHECK(it != wallet->mapWallet.end());
877 it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
878 return it->second;
879 }
880
881 std::unique_ptr<CWallet> wallet;
882};
883
885{
886 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
887
888 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
889 // address.
890 std::map<CTxDestination, std::vector<COutput>> list;
891 {
892 LOCK(wallet->cs_wallet);
893 list = ListCoins(*wallet);
894 }
895 BOOST_CHECK_EQUAL(list.size(), 1U);
896 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
897 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
898
899 // Check initial balance from one mature coinbase transaction.
900 BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
901
902 // Add a transaction creating a change address, and confirm ListCoins still
903 // returns the coin associated with the change address underneath the
904 // coinbaseKey pubkey, even though the change address has a different
905 // pubkey.
906 AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
907 {
908 LOCK(wallet->cs_wallet);
909 list = ListCoins(*wallet);
910 }
911 BOOST_CHECK_EQUAL(list.size(), 1U);
912 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
913 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
914
915 // Lock both coins. Confirm number of available coins drops to 0.
916 {
917 LOCK(wallet->cs_wallet);
918 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 2U);
919 }
920 for (const auto& group : list) {
921 for (const auto& coin : group.second) {
922 LOCK(wallet->cs_wallet);
923 wallet->LockCoin(coin.outpoint, /*persist=*/false);
924 }
925 }
926 {
927 LOCK(wallet->cs_wallet);
928 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 0U);
929 }
930 // Confirm ListCoins still returns same result as before, despite coins
931 // being locked.
932 {
933 LOCK(wallet->cs_wallet);
934 list = ListCoins(*wallet);
935 }
936 BOOST_CHECK_EQUAL(list.size(), 1U);
937 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
938 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
939}
940
941void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
942 std::map<OutputType, size_t>& expected_coins_sizes)
943{
944 LOCK(context.wallet->cs_wallet);
945 util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
946 CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
947 CoinFilterParams filter;
948 filter.skip_locked = false;
949 CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
950 // Lock outputs so they are not spent in follow-up transactions
951 for (uint32_t i = 0; i < wtx.GetTx()->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i}, /*persist=*/false);
952 for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
953}
954
955BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
956{
957 std::map<OutputType, size_t> expected_coins_sizes;
958 for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
959
960 // Verify our wallet has one usable coinbase UTXO before starting
961 // This UTXO is a P2PK, so it should show up in the Other bucket
962 expected_coins_sizes[OutputType::UNKNOWN] = 1U;
963 CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
964 BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
965 BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
966
967 // We will create a self transfer for each of the OutputTypes and
968 // verify it is put in the correct bucket after running GetAvailablecoins
969 //
970 // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
971 // 1. One UTXO as the recipient
972 // 2. One UTXO from the change, due to payment address matching logic
973
974 for (const auto& out_type : OUTPUT_TYPES) {
975 if (out_type == OutputType::UNKNOWN) continue;
976 expected_coins_sizes[out_type] = 2U;
977 TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
978 }
979}
980
982{
983 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
984 LOCK(wallet->cs_wallet);
985 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
987 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
988}
989
990// Explicit calculation which is used to test the wallet constant
991// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
992static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
993{
994 // Generate ephemeral valid pubkey
995 CKey key = GenerateRandomKey();
996 CPubKey pubkey = key.GetPubKey();
997
998 // Generate pubkey hash
999 uint160 key_hash(Hash160(pubkey));
1000
1001 // Create inner-script to enter into keystore. Key hash can't be 0...
1002 CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
1003
1004 // Create outer P2SH script for the output
1005 uint160 script_id(Hash160(inner_script));
1006 CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
1007
1008 // Add inner-script to key store and key to watchonly
1009 FillableSigningProvider keystore;
1010 keystore.AddCScript(inner_script);
1011 keystore.AddKeyPubKey(key, pubkey);
1012
1013 // Fill in dummy signatures for fee calculation.
1014 SignatureData sig_data;
1015
1016 if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
1017 // We're hand-feeding it correct arguments; shouldn't happen
1018 assert(false);
1019 }
1020
1021 CTxIn tx_in;
1022 UpdateInput(tx_in, sig_data);
1023 return (size_t)GetVirtualTransactionInputSize(tx_in);
1024}
1025
1027{
1030}
1031
1032bool malformed_descriptor(std::ios_base::failure e)
1033{
1034 std::string s(e.what());
1035 return s.find("Missing checksum") != std::string::npos;
1036}
1037
1039{
1040 std::vector<unsigned char> malformed_record;
1041 VectorWriter vw{malformed_record, 0};
1042 vw << std::string("notadescriptor");
1043 vw << uint64_t{0};
1044 vw << int32_t{0};
1045 vw << int32_t{0};
1046 vw << int32_t{1};
1047
1048 SpanReader vr{malformed_record};
1049 std::optional<WalletDescriptor> w_desc;
1050 BOOST_CHECK_EXCEPTION(w_desc.emplace(WalletDescriptor::FromStream(deserialize, vr)), std::ios_base::failure, malformed_descriptor);
1051}
1052
1072{
1073 m_args.ForceSetArg("-unsafesqlitesync", "1");
1074 // Create new wallet with known key and unload it.
1075 WalletContext context;
1076 context.args = &m_args;
1077 context.chain = m_node.chain.get();
1078 auto wallet = TestCreateWallet(context);
1079 CKey key = GenerateRandomKey();
1080 AddKey(*wallet, key);
1081 TestUnloadWallet(std::move(wallet));
1082
1083
1084 // Add log hook to detect AddToWallet events from rescans, blockConnected,
1085 // and transactionAddedToMempool notifications
1086 int addtx_count = 0;
1087 DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
1088 if (s) ++addtx_count;
1089 return false;
1090 });
1091
1092
1093 bool rescan_completed = false;
1094 DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
1095 if (s) rescan_completed = true;
1096 return false;
1097 });
1098
1099
1100 // Block the queue to prevent the wallet receiving blockConnected and
1101 // transactionAddedToMempool notifications, and create block and mempool
1102 // transactions paying to the wallet
1103 std::promise<void> promise;
1104 m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
1105 promise.get_future().wait();
1106 });
1107 std::string error;
1108 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1109 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1110 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1111 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1113
1114
1115 // Reload wallet and make sure new transactions are detected despite events
1116 // being blocked
1117 // Loading will also ask for current mempool transactions
1118 wallet = TestLoadWallet(context);
1119 BOOST_CHECK(rescan_completed);
1120 // AddToWallet events for block_tx and mempool_tx (x2)
1121 BOOST_CHECK_EQUAL(addtx_count, 3);
1122 {
1123 LOCK(wallet->cs_wallet);
1124 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
1125 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
1126 }
1127
1128
1129 // Unblock notification queue and make sure stale blockConnected and
1130 // transactionAddedToMempool events are processed
1131 promise.set_value();
1132 m_node.validation_signals->SyncWithValidationInterfaceQueue();
1133 // AddToWallet events for block_tx and mempool_tx events are counted a
1134 // second time as the notification queue is processed
1135 BOOST_CHECK_EQUAL(addtx_count, 5);
1136
1137
1138 TestUnloadWallet(std::move(wallet));
1139
1140
1141 // Load wallet again, this time creating new block and mempool transactions
1142 // paying to the wallet as the wallet finishes loading and syncing the
1143 // queue so the events have to be handled immediately. Releasing the wallet
1144 // lock during the sync is a little artificial but is needed to avoid a
1145 // deadlock during the sync and simulates a new block notification happening
1146 // as soon as possible.
1147 addtx_count = 0;
1148 auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
1149 BOOST_CHECK(rescan_completed);
1150 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1151 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1152 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1153 mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1155 m_node.validation_signals->SyncWithValidationInterfaceQueue();
1156 });
1157 wallet = TestLoadWallet(context);
1158 // Since mempool transactions are requested at the end of loading, there will
1159 // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
1160 BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
1161 {
1162 LOCK(wallet->cs_wallet);
1163 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
1164 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
1165 }
1166
1167
1168 TestUnloadWallet(std::move(wallet));
1169}
1170
1172{
1173 WalletContext context;
1174 context.args = &m_args;
1175 auto wallet = TestCreateWallet(context);
1177 WaitForDeleteWallet(std::move(wallet));
1178}
1179
1181{
1182 m_args.ForceSetArg("-unsafesqlitesync", "1");
1183 WalletContext context;
1184 context.args = &m_args;
1185 context.chain = m_node.chain.get();
1186 auto wallet = TestCreateWallet(context);
1187 CKey key = GenerateRandomKey();
1188 AddKey(*wallet, key);
1189
1190 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1191 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1192 CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
1193
1194 m_node.validation_signals->SyncWithValidationInterfaceQueue();
1195
1196 {
1197 auto block_hash = block_tx.GetHash();
1198 auto prev_tx = m_coinbase_txns[0];
1199
1200 LOCK(wallet->cs_wallet);
1201 BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
1202 BOOST_CHECK(wallet->mapWallet.contains(block_hash));
1203
1204 std::vector<Txid> vHashIn{ block_hash };
1205 BOOST_CHECK(wallet->RemoveTxs(vHashIn));
1206
1207 BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
1208 BOOST_CHECK(!wallet->mapWallet.contains(block_hash));
1209 }
1210
1211 TestUnloadWallet(std::move(wallet));
1212}
1213
1215} // namespace wallet
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
node::NodeContext m_node
Definition: bitcoin-gui.cpp:48
bool DestroyBlockFilterIndex(BlockFilterType filter_type)
Destroy the block filter index with the given type.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
bool InitBlockFilterIndex(std::function< std::unique_ptr< interfaces::Chain >()> make_chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:37
#define Assert(val)
Identity function.
Definition: check.h:116
Complete block filter struct as defined in BIP 157.
Definition: blockfilter.h:116
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
uint32_t nTime
Definition: chain.h:142
uint256 GetBlockHash() const
Definition: chain.h:198
int64_t GetBlockTimeMax() const
Definition: chain.h:226
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:163
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:97
An encapsulated private key.
Definition: key.h:40
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
An encapsulated public key.
Definition: pubkey.h:40
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:287
An input of a transaction.
Definition: transaction.h:63
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:950
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1196
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:54
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
virtual bool AddCScript(const CScript &redeemScript)
virtual bool AddKey(const CKey &key)
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:83
constexpr bool IsNull() const
Definition: uint256.h:50
constexpr unsigned char * end()
Definition: uint256.h:102
constexpr unsigned char * begin()
Definition: uint256.h:101
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
Coin Control Features.
Definition: coincontrol.h:83
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:313
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:194
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:390
CTransactionRef GetTx() const
Definition: transaction.h:351
CWalletTx & AddTx(CRecipient recipient)
std::unique_ptr< CWallet > wallet
Access to the wallet database.
Definition: walletdb.h:197
Descriptor with some wallet metadata.
Definition: walletutil.h:64
RAII object to check and reserve a wallet rescan.
Definition: scan.h:37
bool isReserved() const
Definition: scan.cpp:49
void setNow(NowFn now)
Definition: scan.h:52
bool reserve(bool with_passphrase=false)
Definition: scan.cpp:40
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:408
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:100
BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value")
BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"})
@ SIGHASH_ALL
Definition: interpreter.h:32
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:354
std::string EncodeExtKey(const CExtKey &key)
Definition: key_io.cpp:284
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:232
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: messages.h:21
@ MEMPOOL_NO_BROADCAST
Add the transaction to the mempool, but don't broadcast to anybody.
constexpr unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:124
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:146
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase()
Definition: util.cpp:121
void TestLoadWallet(const std::string &name, DatabaseFormat format, std::function< void(std::shared_ptr< CWallet >)> f)
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, std::optional< unsigned int > change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:1442
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:140
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Definition: walletdb.cpp:1228
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:81
BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
std::vector< ImportResult > ProcessDescriptorsImport(CWallet &wallet, std::vector< ImportDescriptorRequest > &requests)
Definition: imports.cpp:222
DatabaseFormat
Definition: db.h:163
bool AddWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Add wallet name to persistent configuration so it will be loaded on startup.
Definition: wallet.cpp:101
bool RemoveWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Remove wallet name from persistent configuration so it will not be loaded on startup.
Definition: wallet.cpp:114
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:228
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
Definition: util.cpp:22
constexpr CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:127
void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
Definition: util.cpp:98
static void AddTx(CWallet &wallet)
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2759
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
Definition: spend.cpp:544
BOOST_AUTO_TEST_CASE(bnb_test)
constexpr DatabaseFormat DATABASE_FORMATS[]
Definition: util.h:28
static void AddKey(CWallet &wallet, const CKey &key)
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context)
Definition: util.cpp:76
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse, bool include_nonmempool)
Definition: receive.cpp:245
std::shared_ptr< CWallet > TestCreateWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context, uint64_t create_flags)
Definition: util.cpp:52
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, std::chrono::seconds mock_time, int64_t blockTime)
bool malformed_descriptor(std::ios_base::failure e)
constexpr CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:113
std::shared_ptr< CWallet > CreateWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:334
void TestCoinsResult(ListCoinsTest &context, OutputType out_type, CAmount amount, std::map< OutputType, size_t > &expected_coins_sizes)
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:30
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
Definition: wallet.cpp:266
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
DatabaseStatus
Definition: db.h:180
is a home for public enum and struct type definitions that are used internally by node code,...
#define BOOST_CHECK(expr)
Definition: object.cpp:16
OutputType
Definition: outputtype.h:18
constexpr auto OUTPUT_TYPES
Definition: outputtype.h:26
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:405
constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
Definition: policy.h:48
constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: policy.h:70
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:418
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:417
uint256 GetRandHash() noexcept
Generate a random uint256.
Definition: random.h:463
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:1198
const char * name
Definition: rest.cpp:71
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
@ OP_EQUAL
Definition: script.h:147
constexpr deserialize_type deserialize
Definition: serialize.h:52
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:745
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:918
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:1004
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:238
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:1003
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:213
Basic testing setup.
Definition: setup_common.h:58
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:117
std::vector< uint256 > vHave
Definition: block.h:127
bool IsNull() const
Definition: block.h:145
Definition: key.h:232
void SetSeed(std::span< const std::byte > seed)
Definition: key.cpp:381
A mutable version of CTransaction.
Definition: transaction.h:372
std::vector< CTxOut > vout
Definition: transaction.h:374
std::vector< CTxIn > vin
Definition: transaction.h:373
int32_t nFile
Definition: flatfile.h:16
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:139
Testing setup that configures a complete environment.
Definition: setup_common.h:115
Bilingual messages:
Definition: translation.h:24
NodeContext struct containing references to chain state and connection state.
Definition: context.h:59
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:97
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:76
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:80
COutputs available for spending, stored by OutputType.
Definition: spend.h:45
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
Definition: spend.cpp:194
std::map< OutputType, std::vector< COutput > > coins
Definition: spend.h:46
std::optional< DatabaseFormat > require_format
Definition: db.h:171
Information about a descriptor to be imported.
Definition: imports.h:49
Result of a wallet scan.
Definition: scan.h:19
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: scan.h:25
enum wallet::ScanResult::@19 status
std::optional< int > last_scanned_height
Definition: scan.h:26
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: scan.h:32
State of transaction confirmed in a block.
Definition: transaction.h:34
State of transaction not confirmed or conflicting with a known block and not in the mempool.
Definition: transaction.h:61
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:36
interfaces::Chain * chain
Definition: context.h:37
ArgsManager * args
Definition: context.h:39
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
FuzzedDataProvider provider
Definition: dbwrapper.cpp:366
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
assert(!tx.IsCoinBase())
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:544
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)