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 <stdexcept>
16#include <string>
17#include <utility>
18#include <vector>
19
20#include <addresstype.h>
21#include <blockfilter.h>
22#include <chain.h>
23#include <consensus/tx_verify.h>
26#include <interfaces/chain.h>
27#include <key_io.h>
28#include <node/blockstorage.h>
29#include <node/types.h>
30#include <policy/feerate.h>
31#include <policy/policy.h>
32#include <rpc/server.h>
33#include <script/descriptor.h>
34#include <script/solver.h>
35#include <test/util/common.h>
36#include <test/util/logging.h>
37#include <test/util/random.h>
39#include <test/util/time.h>
40#include <util/byte_units.h>
41#include <util/check.h>
42#include <util/strencodings.h>
43#include <util/translation.h>
44#include <validation.h>
45#include <validationinterface.h>
46#include <wallet/coincontrol.h>
47#include <wallet/context.h>
48#include <wallet/imports.h>
49#include <wallet/receive.h>
50#include <wallet/spend.h>
51#include <wallet/test/util.h>
53
54#include <boost/test/unit_test.hpp>
55
57
58namespace wallet {
59
60// Ensure that fee levels defined in the wallet are at least as high
61// as the default levels for node policy.
62static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
63static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
64
65BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
66
67static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
68{
70 mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
71 mtx.vin.push_back({CTxIn{from.GetHash(), index}});
73 keystore.AddKey(key);
74 std::map<COutPoint, Coin> coins;
75 coins[mtx.vin[0].prevout].out = from.vout[index];
76 std::map<int, bilingual_str> input_errors;
77 BOOST_CHECK(SignTransaction(mtx, &keystore, coins, {.sighash_type = SIGHASH_ALL}, input_errors));
78 return mtx;
79}
80
81static bool BroadcastTestSimpleSpend(interfaces::Chain& chain, ChainstateManager& chainman, const CMutableTransaction& tx, std::string& error)
82{
83 const auto tx_ref{MakeTransactionRef(tx)};
84 const auto tx_sigops = WITH_LOCK(::cs_main, return GetTransactionSigOpCost(
86 const auto tx_vsize{GetVirtualTransactionSize(*tx_ref, tx_sigops, nBytesPerSigOp)};
87 const auto tx_feerate{CFeeRate{DEFAULT_TRANSACTION_MAXFEE, static_cast<int32_t>(tx_vsize)}};
88 // TestSimpleSpend pays a high fee; use a limit just above its feerate.
89 const auto tx_feerate_limit{CFeeRate{tx_feerate.GetFeePerK() + 1}};
91}
92
93static void AddKey(CWallet& wallet, const CKey& key)
94{
95 LOCK(wallet.cs_wallet);
97 std::string error;
98 auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
99 assert(descs.size() == 1);
100 auto& desc = descs.at(0);
101 WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
102 Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
103}
104
105BOOST_AUTO_TEST_CASE(reject_invalid_descriptor_ranges)
106{
107 const int height{*Assert(m_node.chain->getHeight())};
108 {
109 LOCK(m_wallet.cs_wallet);
110 m_wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
111 m_wallet.SetLastBlockProcessed(height, m_node.chain->getBlockHash(height));
112 }
113
114 CExtKey ext_key;
115 ext_key.SetSeed(std::array<std::byte, 32>{});
116 const std::string descriptor_without_checksum{"wpkh(" + EncodeExtKey(ext_key) + "/*)"};
117 const std::string descriptor{descriptor_without_checksum + "#" + GetDescriptorChecksum(descriptor_without_checksum)};
118
119 const std::array invalid_ranges{
120 std::pair{std::pair<int64_t, int64_t>{2, 1}, "Range specified as [begin,end] must not have begin after end"},
121 std::pair{std::pair<int64_t, int64_t>{-1, 10}, "Range should be greater or equal than 0"},
122 std::pair{std::pair<int64_t, int64_t>{0, 1'000'000}, "Range is too large"},
123 std::pair{std::pair<int64_t, int64_t>{0, std::numeric_limits<int64_t>::max()}, "End of range is too high"},
124 std::pair{std::pair<int64_t, int64_t>{0, 1LL << 31}, "End of range is too high"},
125 };
126
127 for (const auto& [range, expected_error] : invalid_ranges) {
128 std::vector requests{ImportDescriptorRequest{
129 .descriptor = descriptor,
130 .label = {},
131 .timestamp = 0,
132 .active = false,
133 .internal = std::nullopt,
134 .range = range,
135 .next_index = std::nullopt,
136 }};
137 const auto results{ProcessDescriptorsImport(m_wallet, requests)};
138 BOOST_REQUIRE_EQUAL(results.size(), 1U);
139 BOOST_REQUIRE(results.front().error.has_value());
140 BOOST_CHECK(results.front().error->wallet_error.code == WalletErrorCode::InvalidParameter);
141 BOOST_CHECK_EQUAL(results.front().error->wallet_error.message.original, expected_error);
142 BOOST_CHECK(!results.front().error->is_general_error);
143 }
144}
145
146namespace {
147struct EncryptionFailureSetup : TestingSetup {
148 WalletContext context;
149 FaultInjectingDatabase* fail_db{nullptr};
150 std::shared_ptr<CWallet> wallet;
151 FakeNodeClock clock; // Frozen time makes EncryptMasterKey use the default KDF iteration count
152
153 EncryptionFailureSetup()
154 {
155 context.args = &m_args;
156 m_args.ForceSetArg("-keypool", "1"); // Failure injection does not depend on keypool depth
157 context.chain = m_node.chain.get();
158 RecreateWallet(WALLET_FLAG_DESCRIPTORS);
159 }
160
161 void RecreateWallet(uint64_t create_flags)
162 {
163 if (wallet) TestUnloadWallet(std::move(wallet));
164 auto database{std::make_unique<FaultInjectingDatabase>()};
165 fail_db = database.get();
166 wallet = TestCreateWallet(std::move(database), context, create_flags);
167 }
168
169 ~EncryptionFailureSetup() { TestUnloadWallet(std::move(wallet)); }
170};
171} // namespace
172
173BOOST_FIXTURE_TEST_CASE(encrypt_wallet_master_key_write_failure, EncryptionFailureSetup)
174{
176
177 fail_db->FailNextWrite(DBKeys::MASTER_KEY); // The injected failure affects only the first attempt
178 for (bool success : {false, true}) {
179 BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
180 BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
181 BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
185 }
186}
187
188BOOST_FIXTURE_TEST_CASE(encrypt_wallet_commit_failure, EncryptionFailureSetup)
189{
191
192 fail_db->FailNextCommit(); // The injected failure affects only the first attempt
193 test_only_CheckFailuresAreExceptionsNotAborts mock_checks; // Keep abort regressions observable
194 BOOST_CHECK(!wallet->EncryptWallet("passphrase"));
195 BOOST_CHECK(!wallet->HasEncryptionKeys());
196 BOOST_CHECK(!wallet->HaveCryptedKeys());
200 BOOST_CHECK( wallet->EncryptWallet("passphrase"));
201 BOOST_CHECK( wallet->HasEncryptionKeys());
202 BOOST_CHECK( wallet->HaveCryptedKeys());
206}
207
208BOOST_FIXTURE_TEST_CASE(encrypt_wallet_descriptor_key_write_failure, EncryptionFailureSetup)
209{
211
212 fail_db->FailNextWrite(DBKeys::WALLETDESCRIPTORCKEY, /*match_skip_count=*/1); // Only one write fails
213 for (bool success : {false, true}) {
214 BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
215 BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
216 BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
220 }
221}
222
223BOOST_FIXTURE_TEST_CASE(encrypt_wallet_descriptor_key_erase_failure, EncryptionFailureSetup)
224{
226
227 fail_db->FailNextErase(DBKeys::WALLETDESCRIPTORKEY); // Only one erase fails
228 for (bool success : {false, true}) {
229 BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
230 BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
231 BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
235 }
236}
237
238BOOST_FIXTURE_TEST_CASE(change_passphrase_master_key_write_failure, EncryptionFailureSetup)
239{
241 BOOST_REQUIRE(wallet->EncryptWallet("old_pass"));
242 BOOST_REQUIRE(wallet->IsLocked());
243 const auto master_key_record{fail_db->GetRecordValue(DBKeys::MASTER_KEY)};
244 BOOST_REQUIRE(master_key_record);
245
246 fail_db->FailNextWrite(DBKeys::MASTER_KEY); // The injected failure affects only the first attempt
247 const auto changed{wallet->ChangeWalletPassphrase("old_pass", "new_pass")};
248 BOOST_REQUIRE(!changed);
250 BOOST_CHECK_EQUAL(changed.error().message.original, "Error: Writing the new encryption key to the wallet database failed");
251 BOOST_CHECK( wallet->IsLocked());
252 BOOST_CHECK( fail_db->GetRecordValue(DBKeys::MASTER_KEY) == master_key_record);
253 BOOST_CHECK( wallet->Unlock("old_pass"));
254 wallet->Lock();
255 BOOST_CHECK(!wallet->Unlock("new_pass"));
256 BOOST_CHECK( wallet->ChangeWalletPassphrase("old_pass", "new_pass"));
257 BOOST_CHECK( wallet->IsLocked());
258 BOOST_CHECK( fail_db->GetRecordValue(DBKeys::MASTER_KEY) != master_key_record);
259 BOOST_CHECK( wallet->Unlock("new_pass"));
260 wallet->Lock();
261 const auto unlocked{wallet->Unlock("old_pass")};
262 BOOST_REQUIRE(!unlocked);
264 BOOST_CHECK_EQUAL(unlocked.error().message.original, "Error: The wallet passphrase entered was incorrect.");
265}
266
267BOOST_FIXTURE_TEST_CASE(add_encrypted_descriptor_key_without_plaintext_record, EncryptionFailureSetup)
268{
270 BOOST_REQUIRE(wallet->EncryptWallet("passphrase"));
271 BOOST_REQUIRE(wallet->Unlock("passphrase"));
272
274 BOOST_CHECK( wallet->HaveCryptedKeys());
277}
278
279BOOST_FIXTURE_TEST_CASE(add_descriptor_key_database_failure, EncryptionFailureSetup)
280{
281 enum class Failure { PlaintextWrite, EncryptedWrite, Erase, Commit };
282 for (auto failure : {Failure::PlaintextWrite, Failure::EncryptedWrite, Failure::Erase, Failure::Commit}) {
283 const bool encrypted{failure != Failure::PlaintextWrite};
285 CKey key{GenerateRandomKey()};
286 // Add a public descriptor first so the private-key update exercises an existing live manager
287 auto* spkm{CreateDescriptor(*wallet, strprintf("combo(%s)", HexStr(key.GetPubKey())), /*success=*/true)};
288 WalletDescriptor descriptor{WITH_LOCK(spkm->cs_desc_man, return spkm->GetWalletDescriptor())};
290 provider.keys.emplace(key.GetPubKey().GetID(), key);
291 auto add_key{[&] {
292 LOCK(wallet->cs_wallet);
293 return wallet->AddWalletDescriptor(descriptor, provider, /*label=*/"", /*internal=*/false);
294 }};
295 auto has_key{[&] {
296 LOCK(wallet->cs_wallet);
297 return wallet->GetKey(key.GetPubKey().GetID()).has_value();
298 }};
299 if (encrypted) {
300 BOOST_REQUIRE(wallet->EncryptWallet("passphrase"));
301 BOOST_REQUIRE(wallet->Unlock("passphrase"));
302 }
303 BOOST_CHECK(!has_key());
304
305 const std::string record_type{encrypted ? DBKeys::WALLETDESCRIPTORCKEY : DBKeys::WALLETDESCRIPTORKEY};
306 if (failure == Failure::Erase) {
308 } else if (failure == Failure::Commit) {
310 } else {
311 fail_db->FailNextWrite(record_type);
312 }
313 BOOST_CHECK_EXCEPTION((void)add_key(), std::runtime_error, HasReason{"UpdateWithSigningProvider: writing descriptor private key failed"});
314 BOOST_CHECK(!has_key());
315 BOOST_CHECK(!fail_db->HasRecordType(record_type));
316 BOOST_CHECK( add_key());
317 BOOST_CHECK( has_key());
318 BOOST_CHECK( fail_db->HasRecordType(record_type));
319 }
320}
321
322BOOST_FIXTURE_TEST_CASE(update_non_range_descriptor, TestingSetup)
323{
325 {
326 LOCK(wallet.cs_wallet);
327 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
328 auto key{GenerateRandomKey()};
329 auto desc_str{"combo(" + EncodeSecret(key) + ")"};
331 std::string error;
332 auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
333 auto& desc{descs.at(0)};
334 WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
335 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
336 // Wallet should update the non-range descriptor successfully
337 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
338 }
339}
340
341BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
342{
343 // Cap last block file size, and mine new block in a new block file.
344 CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
345 WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
346 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
347 CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
348
349 // Verify Scan fails to read an unknown start block.
350 {
352 {
353 LOCK(wallet.cs_wallet);
354 LOCK(Assert(m_node.chainman)->GetMutex());
355 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
356 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
357 }
358 AddKey(wallet, coinbaseKey);
360 reserver.reserve();
361 ScanResult result = wallet.Scanner().Scan(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
366 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
367 }
368
369 // Verify Scan picks up transactions in both the old
370 // and new block files.
371 {
373 {
374 LOCK(wallet.cs_wallet);
375 LOCK(Assert(m_node.chainman)->GetMutex());
376 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
377 wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
378 }
379 AddKey(wallet, coinbaseKey);
381 std::chrono::steady_clock::time_point fake_time;
382 reserver.setNow([&] { fake_time += 60s; return fake_time; });
383 reserver.reserve();
384
385 {
386 CBlockLocator locator;
387 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
388 BOOST_REQUIRE(!locator.IsNull());
389 BOOST_CHECK(locator.vHave.front() == newTip->GetBlockHash());
390 }
391
392 ScanResult result = wallet.Scanner().Scan(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/true);
395 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
396 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
397 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
398
399 {
400 CBlockLocator locator;
401 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
402 BOOST_REQUIRE(!locator.IsNull());
403 BOOST_CHECK(locator.vHave.front() == newTip->GetBlockHash());
404 }
405 }
406
407 // Prune the older block file.
408 int file_number;
409 {
410 LOCK(cs_main);
411 file_number = oldTip->GetBlockPos().nFile;
412 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
413 }
414 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
415
416 // Verify Scan only picks transactions in the new block
417 // file.
418 {
420 {
421 LOCK(wallet.cs_wallet);
422 LOCK(Assert(m_node.chainman)->GetMutex());
423 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
424 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
425 }
426 AddKey(wallet, coinbaseKey);
428 reserver.reserve();
429 ScanResult result = wallet.Scanner().Scan(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/false);
432 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
433 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
434 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
435 }
436
437 // Prune the remaining block file.
438 {
439 LOCK(cs_main);
440 file_number = newTip->GetBlockPos().nFile;
441 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
442 }
443 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
444
445 // Verify Scan scans no blocks.
446 {
448 {
449 LOCK(wallet.cs_wallet);
450 LOCK(Assert(m_node.chainman)->GetMutex());
451 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
452 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
453 }
454 AddKey(wallet, coinbaseKey);
456 reserver.reserve();
457 ScanResult result = wallet.Scanner().Scan(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*save_progress=*/false);
459 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
462 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
463 }
464}
465
466BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_reorged_block, TestChain100Setup)
467{
468 BOOST_REQUIRE(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1_MiB, /*f_memory=*/true));
470 BOOST_REQUIRE(filter_index.Init());
471 filter_index.Sync();
472
473 // Reorg the tip out of the active chain: invalidate it, then mine a
474 // longer replacement branch paying a script unrelated to the wallets
475 // below.
476 CBlockIndex* stale_block = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
477 const uint256 stale_hash{stale_block->GetBlockHash()};
478 const int stale_height{stale_block->nHeight};
480 BOOST_REQUIRE(m_node.chainman->ActiveChainstate().InvalidateBlock(state, stale_block));
481 const CScript replacement_script{GetScriptForRawPubKey(GenerateRandomKey().GetPubKey())};
482 CreateAndProcessBlock({}, replacement_script);
483 CreateAndProcessBlock({}, replacement_script);
484 BOOST_REQUIRE(filter_index.BlockUntilSyncedToCurrentChain());
485 {
486 LOCK(Assert(m_node.chainman)->GetMutex());
487 BOOST_REQUIRE(!m_node.chainman->ActiveChain().Contains(*stale_block));
488 BOOST_REQUIRE_EQUAL(m_node.chainman->ActiveChain().Height(), stale_height + 1);
489 }
490
491 {
492 BlockFilter filter;
493 BOOST_REQUIRE(filter_index.LookupFilter(stale_block, filter));
494 }
495
496 // Test wallet whose scripts do not match the stale block's filter.
497 {
499 {
500 LOCK(wallet.cs_wallet);
501 LOCK(Assert(m_node.chainman)->GetMutex());
502 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
503 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
504 }
506 reserver.reserve();
507 ScanResult result = wallet.Scanner().Scan(stale_hash, stale_height, /*max_height=*/{}, reserver, /*save_progress=*/false);
510 BOOST_CHECK_EQUAL(result.last_scanned_block, stale_hash);
511 BOOST_CHECK_EQUAL(*result.last_scanned_height, stale_height);
512 }
513
514 // Test wallet whose scripts do match the stale block's filter.
515 {
517 {
518 LOCK(wallet.cs_wallet);
519 LOCK(Assert(m_node.chainman)->GetMutex());
520 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
521 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
522 }
523 AddKey(wallet, coinbaseKey); // the stale block's coinbase pays coinbaseKey
525 reserver.reserve();
526 ScanResult result = wallet.Scanner().Scan(stale_hash, stale_height, /*max_height=*/{}, reserver, /*save_progress=*/false);
528 BOOST_CHECK_EQUAL(result.last_failed_block, stale_hash);
531 BOOST_CHECK(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.empty()));
532 }
533
534 // Prune the stale block's file — the block is now not active AND unreadable.
535 int file_number;
536 {
537 LOCK(cs_main);
538 file_number = stale_block->GetBlockPos().nFile;
539 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
540 }
541 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
542
543 {
545 {
546 LOCK(wallet.cs_wallet);
547 LOCK(Assert(m_node.chainman)->GetMutex());
548 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
549 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
550 }
551 AddKey(wallet, coinbaseKey);
553 reserver.reserve();
554 ScanResult result = wallet.Scanner().Scan(stale_hash, stale_height, /*max_height=*/{}, reserver, /*save_progress=*/false);
556 BOOST_CHECK_EQUAL(result.last_failed_block, stale_hash);
559 BOOST_CHECK(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.empty()));
560 }
561
562 filter_index.Stop();
564}
565
566BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_abort, TestChain100Setup)
567{
569 uint256 genesis_hash;
570 {
571 LOCK(wallet.cs_wallet);
572 LOCK(Assert(m_node.chainman)->GetMutex());
573 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
574 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
575 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
576 }
577
578 // An abort requested while no rescan is held is stale and must
579 // not cancel a later scan.
580 wallet.Scanner().Abort();
582 BOOST_CHECK(reserver.reserve());
583 BOOST_CHECK(!wallet.Scanner().IsAborting());
584
585 // An abort requested after the reservation but before the scan starts
586 // (e.g. while importdescriptors is still deriving keys) must cancel the
587 // scan.
588 wallet.Scanner().Abort();
589 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
594}
595
596BOOST_FIXTURE_TEST_CASE(wallet_rescan_reserver, TestingSetup)
597{
599
600 // No scan in progress: accessors report idle state.
601 BOOST_CHECK(!wallet.Scanner().IsScanning());
602 BOOST_CHECK(wallet.Scanner().ScanningDuration() == SteadyClock::duration{});
603 BOOST_CHECK_EQUAL(wallet.Scanner().ScanningProgress(), 0.0);
604
605 {
606 WalletRescanReserver first_reserver(wallet);
607 BOOST_CHECK(first_reserver.reserve());
608 BOOST_CHECK(first_reserver.isReserved());
609 BOOST_CHECK(wallet.Scanner().IsScanning());
610 BOOST_CHECK(!wallet.Scanner().IsScanningWithPassphrase());
611 BOOST_CHECK_EQUAL(wallet.Scanner().ScanningProgress(), 0.0);
612
613 // Only one reservation can be held at a time.
614 WalletRescanReserver second_reserver(wallet);
615 BOOST_CHECK(!second_reserver.reserve());
616 BOOST_CHECK(!second_reserver.isReserved());
617 }
618 // Destroying the reserver (RAII) clears the scanning state.
619 BOOST_CHECK(!wallet.Scanner().IsScanning());
620
621 {
622 WalletRescanReserver passphrase_reserver(wallet);
623 BOOST_CHECK(passphrase_reserver.reserve(/*with_passphrase=*/true));
624 BOOST_CHECK(wallet.Scanner().IsScanningWithPassphrase());
625 }
626 BOOST_CHECK(!wallet.Scanner().IsScanningWithPassphrase());
627}
628
629BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_bounded, TestChain100Setup)
630{
631 uint256 genesis_hash, max_hash, tip_hash;
632 int max_height, tip_height;
633 {
634 LOCK(Assert(m_node.chainman)->GetMutex());
635 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
636 tip_height = m_node.chainman->ActiveChain().Height();
637 tip_hash = m_node.chainman->ActiveChain().Tip()->GetBlockHash();
638 max_height = tip_height - 2;
639 max_hash = m_node.chainman->ActiveChain()[max_height]->GetBlockHash();
640 }
641
642 // A scan with max_height set stops exactly at max_height and does not
643 // sync any blocks beyond it.
644 {
646 {
647 LOCK(wallet.cs_wallet);
648 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
649 wallet.SetLastBlockProcessed(tip_height, tip_hash);
650 }
651 AddKey(wallet, coinbaseKey);
653 reserver.reserve();
654 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, max_height, reserver, /*save_progress=*/false);
657 BOOST_CHECK_EQUAL(result.last_scanned_block, max_hash);
658 BOOST_CHECK_EQUAL(*result.last_scanned_height, max_height);
659 // One coinbase per block from height 1 through max_height.
660 BOOST_CHECK_EQUAL(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.size()), static_cast<size_t>(max_height));
661 }
662
663 // A single-block range (start == max_height == tip) scans exactly that
664 // block.
665 {
667 {
668 LOCK(wallet.cs_wallet);
669 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
670 wallet.SetLastBlockProcessed(tip_height, tip_hash);
671 }
672 AddKey(wallet, coinbaseKey);
674 reserver.reserve();
675 ScanResult result = wallet.Scanner().Scan(tip_hash, tip_height, tip_height, reserver, /*save_progress=*/false);
678 BOOST_CHECK_EQUAL(result.last_scanned_block, tip_hash);
679 BOOST_CHECK_EQUAL(*result.last_scanned_height, tip_height);
680 BOOST_CHECK_EQUAL(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.size()), 1U);
681 }
682}
683
684BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_tip_extension, TestChain100Setup)
685{
687 uint256 genesis_hash;
688 int start_tip_height{0};
689 {
690 LOCK(wallet.cs_wallet);
691 LOCK(Assert(m_node.chainman)->GetMutex());
692 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
693 start_tip_height = m_node.chainman->ActiveChain().Height();
694 wallet.SetLastBlockProcessed(start_tip_height, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
695 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
696 }
697 AddKey(wallet, coinbaseKey);
698
699 // Connect a block while the scan is running (the handler fires on the
700 // scanning thread as the scan starts) and advance the wallet's tip, as
701 // the blockConnected notification would. The scan must pick up the new
702 // tip instead of stopping at the height it started with.
703 uint256 new_tip_hash;
704 bool extended{false};
705 auto handler = wallet.ShowProgress.connect([&](const std::string&, int) {
706 if (extended) return;
707 extended = true;
708 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
709 LOCK(wallet.cs_wallet);
710 LOCK(Assert(m_node.chainman)->GetMutex());
711 const CBlockIndex* new_tip = m_node.chainman->ActiveChain().Tip();
712 new_tip_hash = new_tip->GetBlockHash();
713 wallet.SetLastBlockProcessed(new_tip->nHeight, new_tip_hash);
714 });
715
717 reserver.reserve();
718 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
719 handler.disconnect();
721 BOOST_CHECK_EQUAL(result.last_scanned_block, new_tip_hash);
722 BOOST_CHECK_EQUAL(*result.last_scanned_height, start_tip_height + 1);
723}
724
725BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_no_progress_saved, TestChain100Setup)
726{
728 uint256 genesis_hash, tip_hash;
729 int max_height;
730 {
731 LOCK(wallet.cs_wallet);
732 LOCK(Assert(m_node.chainman)->GetMutex());
733 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
734 tip_hash = m_node.chainman->ActiveChain().Tip()->GetBlockHash();
735 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), tip_hash);
736 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
737 max_height = m_node.chainman->ActiveChain().Height() - 2;
738 }
739 AddKey(wallet, coinbaseKey);
740
742 // Advance the clock on every call so that every scanned block would be
743 // eligible for a progress write if save_progress were set.
744 std::chrono::steady_clock::time_point fake_time;
745 reserver.setNow([&] { fake_time += 60s; return fake_time; });
746 reserver.reserve();
747
748 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, max_height, reserver, /*save_progress=*/false);
750
751 // With save_progress=false the scan must not touch the wallet's best
752 // block record: it still points at the tip written when the descriptor
753 // was added, not at any block the scan visited.
754 CBlockLocator locator;
755 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
756 BOOST_CHECK(!locator.IsNull());
757 BOOST_CHECK_EQUAL(locator.vHave.front(), tip_hash);
758}
759
761{
762 // Cap last block file size, and mine new block in a new block file.
763 CBlockIndex* old_tip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
764 WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(old_tip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
765 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
766 CBlockIndex* new_tip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
767
768 // Prune the older block file.
769 int file_number;
770 {
771 LOCK(cs_main);
772 file_number = old_tip->GetBlockPos().nFile;
773 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
774 }
775 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
776
778 {
779 LOCK(wallet.cs_wallet);
780 LOCK(Assert(m_node.chainman)->GetMutex());
781 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
782 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
783 }
784 AddKey(wallet, coinbaseKey);
786 reserver.reserve();
787
788 // Blocks before the prune point cannot be read: the returned timestamp
789 // is moved past the last unreadable block, telling the caller from when
790 // the rescan is actually complete.
791 const int64_t genesis_time{WITH_LOCK(::cs_main, return m_node.chainman->ActiveChain().Genesis()->GetBlockTime())};
792 BOOST_CHECK_EQUAL(wallet.Scanner().ScanFromTime(genesis_time, reserver),
793 WITH_LOCK(::cs_main, return old_tip->GetBlockTimeMax()) + TIMESTAMP_WINDOW + 1);
794
795 bool scan_logged{false};
796 DebugLogHelper scan_check{"Rescan started from block", [&](const std::string* s) {
797 if (s) scan_logged = true;
798 return false;
799 }};
800 // A timestamp past the tip requires no scanning and is returned unchanged.
801 const int64_t future_time{WITH_LOCK(::cs_main, return new_tip->GetBlockTimeMax()) + TIMESTAMP_WINDOW + 1};
802 BOOST_CHECK(!scan_logged);
803 BOOST_CHECK_EQUAL(wallet.Scanner().ScanFromTime(future_time, reserver), future_time);
804}
805
806BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_missing_filter, TestChain100Setup)
807{
808 // Enable the block filter index but do not sync it: no filters are
809 // available, so the scan must inspect every block rather than treat
810 // the missing filters as misses and skip blocks.
811 BOOST_REQUIRE(InitBlockFilterIndex([&]{ return interfaces::MakeChain(m_node); }, BlockFilterType::BASIC, 1_MiB, /*f_memory=*/true));
813 BOOST_REQUIRE(filter_index.Init());
814
815 {
817 uint256 genesis_hash, tip_hash;
818 int tip_height;
819 {
820 LOCK(wallet.cs_wallet);
821 LOCK(Assert(m_node.chainman)->GetMutex());
822 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
823 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
824 tip_height = m_node.chainman->ActiveChain().Height();
825 auto tip{m_node.chainman->ActiveChain().Tip()};
826 tip_hash = tip->GetBlockHash();
827 wallet.SetLastBlockProcessed(tip_height, tip_hash);
828 BlockFilter filter;
829 BOOST_REQUIRE(!filter_index.LookupFilter(tip, filter));
830 }
831 AddKey(wallet, coinbaseKey);
833 reserver.reserve();
834 bool fast_scan_logged{false};
835 DebugLogHelper scan_check{"fast variant using block filters", [&](const std::string* s) {
836 if (s) fast_scan_logged = true;
837 return false;
838 }};
839 ScanResult result = wallet.Scanner().Scan(genesis_hash, /*start_height=*/0, /*max_height=*/{}, reserver, /*save_progress=*/false);
840 BOOST_REQUIRE(fast_scan_logged);
843 BOOST_CHECK_EQUAL(result.last_scanned_block, tip_hash);
844 BOOST_CHECK_EQUAL(*result.last_scanned_height, tip_height);
845 // One coinbase per block from height 1 through the tip.
846 BOOST_CHECK_EQUAL(WITH_LOCK(wallet.cs_wallet, return wallet.mapWallet.size()), static_cast<size_t>(tip_height));
847 }
848
849 filter_index.Stop();
851}
852
856BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_attach_chain, TestChain100Setup)
857{
858 // Do not wait for sqlite to flush data to disk to improve performance
859 m_args.ForceSetArg("-unsafesqlitesync", "1");
860
861 // Create a wallet owning the coinbases, and unload it at the current tip.
863 context.args = &m_args;
864 context.chain = m_node.chain.get();
866 AddKey(*wallet, coinbaseKey);
867 TestUnloadWallet(std::move(wallet));
868
869 // Extend the chain while the wallet is not loaded.
870 constexpr int NEW_BLOCKS{5};
871 for (int i = 0; i < NEW_BLOCKS; ++i) {
872 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
873 }
874
875 int tip_height;
876 uint256 tip_hash;
877 {
878 LOCK(Assert(m_node.chainman)->GetMutex());
879 tip_height = m_node.chainman->ActiveChain().Height();
880 tip_hash = m_node.chainman->ActiveChain().Tip()->GetBlockHash();
881 }
882
883 // Loading the wallet must rescan the extension from the recorded best
884 // block and find its coinbases.
886 {
887 LOCK(wallet->cs_wallet);
888 BOOST_CHECK_EQUAL(wallet->GetLastBlockHeight(), tip_height);
889 BOOST_CHECK_EQUAL(wallet->GetLastBlockHash(), tip_hash);
890 // The extension's coinbases plus the one of the recorded best block:
891 // the load rescan starts mid-chain, at that block inclusive.
892 BOOST_CHECK_EQUAL(wallet->mapWallet.size(), static_cast<size_t>(NEW_BLOCKS + 1));
893 }
894 TestUnloadWallet(std::move(wallet));
895}
896
897// This test verifies that wallet settings can be added and removed
898// concurrently, ensuring no race conditions occur during either process.
899BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
900{
901 auto chain = m_node.chain.get();
902 const auto NUM_WALLETS{5};
903
904 // Since we're counting the number of wallets, ensure we start without any.
905 BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
906
907 const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
908 std::vector<std::thread> threads;
909 threads.reserve(NUM_WALLETS);
910 for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
911 for (auto& t : threads) t.join();
912
913 auto wallets = chain->getRwSetting("wallet");
914 BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
915 };
916
917 // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
918 check_concurrent_wallet([&chain](int i) {
919 Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
920 },
921 /*num_expected_wallets=*/NUM_WALLETS);
922
923 // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
924 check_concurrent_wallet([&chain](int i) {
925 Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
926 },
927 /*num_expected_wallets=*/0);
928}
929
930static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, std::chrono::seconds mock_time, int64_t blockTime)
931{
933 TxState state = TxStateInactive{};
934 tx.nLockTime = lockTime;
935 FakeNodeClock clock{mock_time};
936 CBlockIndex* block = nullptr;
937 if (blockTime > 0) {
938 LOCK(cs_main);
939 auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
940 assert(inserted.second);
941 const uint256& hash = inserted.first->first;
942 block = &inserted.first->second;
943 block->nTime = blockTime;
944 block->phashBlock = &hash;
945 state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
946 }
947 return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
948 // Assign wtx.m_state to simplify test and avoid the need to simulate
949 // reorg events. Without this, AddToWallet asserts false when the same
950 // transaction is confirmed in different blocks.
951 wtx.m_state = state;
952 return true;
953 })->nTimeSmart;
954}
955
956// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
957// expanded to cover more corner cases of smart time logic.
958BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
959{
960 // New transaction should use clock time if lower than block time.
961 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100s, 120), 100);
962
963 // Test that updating existing transaction does not change smart time.
964 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200s, 220), 100);
965
966 // New transaction should use clock time if there's no block time.
967 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300s, 0), 300);
968
969 // New transaction should use block time if lower than clock time.
970 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420s, 400), 400);
971
972 // New transaction should use latest entry time if higher than
973 // min(block time, clock time).
974 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500s, 390), 400);
975
976 // If there are future entries, new transaction should use time of the
977 // newest entry that is no more than 300 seconds ahead of the clock time.
978 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50s, 600), 300);
979}
980
981void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
982{
984 auto chain{interfaces::MakeChain(node)};
985 DatabaseOptions options;
986 options.require_format = format;
987 DatabaseStatus status;
988 bilingual_str error;
989 std::vector<bilingual_str> warnings;
990 auto database{MakeWalletDatabase(name, options, status, error)};
991 auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
992 BOOST_CHECK_EQUAL(wallet->PopulateWalletFromDB(error, warnings), DBErrors::LOAD_OK);
993 WITH_LOCK(wallet->cs_wallet, f(wallet));
994}
995
997{
999 const std::string name{strprintf("receive-requests-%i", format)};
1000 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
1001 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
1002 WalletBatch batch{wallet->GetDatabase()};
1003 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
1004 BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
1005 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
1006 BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
1007 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
1008 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
1009 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
1010 });
1011 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
1012 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
1013 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
1014 auto requests = wallet->GetAddressReceiveRequests();
1015 auto erequests = {"val_rr11", "val_rr20"};
1016 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
1017 RunWithinTxn(wallet->GetDatabase(), /*process_desc=*/"test", [](WalletBatch& batch){
1018 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
1019 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
1020 return true;
1021 });
1022 });
1023 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
1024 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
1025 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
1026 auto requests = wallet->GetAddressReceiveRequests();
1027 auto erequests = {"val_rr11"};
1028 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
1029 });
1030 }
1031}
1032
1034{
1035public:
1037 {
1038 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
1039 wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
1040 }
1041
1043 {
1044 wallet.reset();
1045 }
1046
1048 {
1049 CTransactionRef tx;
1050 CCoinControl dummy;
1051 {
1052 auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
1053 BOOST_CHECK(res);
1054 tx = res->tx;
1055 }
1056 wallet->CommitTransaction(tx);
1057 CMutableTransaction blocktx;
1058 {
1059 LOCK(wallet->cs_wallet);
1060 blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).GetTx());
1061 }
1062 CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
1063
1064 LOCK(wallet->cs_wallet);
1065 LOCK(Assert(m_node.chainman)->GetMutex());
1066 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
1067 auto it = wallet->mapWallet.find(tx->GetHash());
1068 BOOST_CHECK(it != wallet->mapWallet.end());
1069 it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
1070 return it->second;
1071 }
1072
1073 std::unique_ptr<CWallet> wallet;
1074};
1075
1077{
1078 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
1079
1080 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
1081 // address.
1082 std::map<CTxDestination, std::vector<COutput>> list;
1083 {
1084 LOCK(wallet->cs_wallet);
1085 list = ListCoins(*wallet);
1086 }
1087 BOOST_CHECK_EQUAL(list.size(), 1U);
1088 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
1089 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
1090
1091 // Check initial balance from one mature coinbase transaction.
1092 BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
1093
1094 // Add a transaction creating a change address, and confirm ListCoins still
1095 // returns the coin associated with the change address underneath the
1096 // coinbaseKey pubkey, even though the change address has a different
1097 // pubkey.
1098 AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
1099 {
1100 LOCK(wallet->cs_wallet);
1101 list = ListCoins(*wallet);
1102 }
1103 BOOST_CHECK_EQUAL(list.size(), 1U);
1104 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
1105 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
1106
1107 // Lock both coins. Confirm number of available coins drops to 0.
1108 {
1109 LOCK(wallet->cs_wallet);
1110 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 2U);
1111 }
1112 for (const auto& group : list) {
1113 for (const auto& coin : group.second) {
1114 LOCK(wallet->cs_wallet);
1115 wallet->LockCoin(coin.outpoint, /*persist=*/false);
1116 }
1117 }
1118 {
1119 LOCK(wallet->cs_wallet);
1120 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 0U);
1121 }
1122 // Confirm ListCoins still returns same result as before, despite coins
1123 // being locked.
1124 {
1125 LOCK(wallet->cs_wallet);
1126 list = ListCoins(*wallet);
1127 }
1128 BOOST_CHECK_EQUAL(list.size(), 1U);
1129 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
1130 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
1131}
1132
1133void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
1134 std::map<OutputType, size_t>& expected_coins_sizes)
1135{
1136 LOCK(context.wallet->cs_wallet);
1137 util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
1138 CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
1139 CoinFilterParams filter;
1140 filter.skip_locked = false;
1141 CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
1142 // Lock outputs so they are not spent in follow-up transactions
1143 for (uint32_t i = 0; i < wtx.GetTx()->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i}, /*persist=*/false);
1144 for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
1145}
1146
1147BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
1148{
1149 std::map<OutputType, size_t> expected_coins_sizes;
1150 for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
1151
1152 // Verify our wallet has one usable coinbase UTXO before starting
1153 // This UTXO is a P2PK, so it should show up in the Other bucket
1154 expected_coins_sizes[OutputType::UNKNOWN] = 1U;
1155 CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
1156 BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
1157 BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
1158
1159 // We will create a self transfer for each of the OutputTypes and
1160 // verify it is put in the correct bucket after running GetAvailablecoins
1161 //
1162 // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
1163 // 1. One UTXO as the recipient
1164 // 2. One UTXO from the change, due to payment address matching logic
1165
1166 for (const auto& out_type : OUTPUT_TYPES) {
1167 if (out_type == OutputType::UNKNOWN) continue;
1168 expected_coins_sizes[out_type] = 2U;
1169 TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
1170 }
1171}
1172
1174{
1175 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
1176 LOCK(wallet->cs_wallet);
1177 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
1179 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
1180}
1181
1182// Explicit calculation which is used to test the wallet constant
1183// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
1184static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
1185{
1186 // Generate ephemeral valid pubkey
1187 CKey key = GenerateRandomKey();
1188 CPubKey pubkey = key.GetPubKey();
1189
1190 // Generate pubkey hash
1191 uint160 key_hash(Hash160(pubkey));
1192
1193 // Create inner-script to enter into keystore. Key hash can't be 0...
1194 CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
1195
1196 // Create outer P2SH script for the output
1197 uint160 script_id(Hash160(inner_script));
1198 CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
1199
1200 // Add inner-script to key store and key to watchonly
1201 FillableSigningProvider keystore;
1202 keystore.AddCScript(inner_script);
1203 keystore.AddKeyPubKey(key, pubkey);
1204
1205 // Fill in dummy signatures for fee calculation.
1206 SignatureData sig_data;
1207
1208 if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
1209 // We're hand-feeding it correct arguments; shouldn't happen
1210 assert(false);
1211 }
1212
1213 CTxIn tx_in;
1214 UpdateInput(tx_in, sig_data);
1215 return (size_t)GetVirtualTransactionInputSize(tx_in);
1216}
1217
1219{
1222}
1223
1224bool malformed_descriptor(std::ios_base::failure e)
1225{
1226 std::string s(e.what());
1227 return s.find("Missing checksum") != std::string::npos;
1228}
1229
1231{
1232 std::vector<unsigned char> malformed_record;
1233 VectorWriter vw{malformed_record, 0};
1234 vw << std::string("notadescriptor");
1235 vw << uint64_t{0};
1236 vw << int32_t{0};
1237 vw << int32_t{0};
1238 vw << int32_t{1};
1239
1240 SpanReader vr{malformed_record};
1241 std::optional<WalletDescriptor> w_desc;
1242 BOOST_CHECK_EXCEPTION(w_desc.emplace(WalletDescriptor::FromStream(deserialize, vr)), std::ios_base::failure, malformed_descriptor);
1243}
1244
1264{
1265 m_args.ForceSetArg("-unsafesqlitesync", "1");
1266 // Create new wallet with known key and unload it.
1268 context.args = &m_args;
1269 context.chain = m_node.chain.get();
1271 CKey key = GenerateRandomKey();
1272 AddKey(*wallet, key);
1273 TestUnloadWallet(std::move(wallet));
1274
1275
1276 // Add log hook to detect AddToWallet events from rescans, blockConnected,
1277 // and transactionAddedToMempool notifications
1278 int addtx_count = 0;
1279 DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
1280 if (s) ++addtx_count;
1281 return false;
1282 });
1283
1284
1285 bool rescan_completed = false;
1286 DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
1287 if (s) rescan_completed = true;
1288 return false;
1289 });
1290
1291
1292 // Block the queue to prevent the wallet receiving blockConnected and
1293 // transactionAddedToMempool notifications, and create block and mempool
1294 // transactions paying to the wallet
1295 std::promise<void> promise;
1296 m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
1297 promise.get_future().wait();
1298 });
1299 std::string error;
1300 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1301 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1302 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1303 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1305
1306 // Reload wallet and make sure new transactions are detected despite events
1307 // being blocked
1308 // Loading will also ask for current mempool transactions
1310 BOOST_CHECK(rescan_completed);
1311 // AddToWallet events for block_tx and mempool_tx (x2)
1312 BOOST_CHECK_EQUAL(addtx_count, 3);
1313 {
1314 LOCK(wallet->cs_wallet);
1315 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
1316 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
1317 }
1318
1319
1320 // Unblock notification queue and make sure stale blockConnected and
1321 // transactionAddedToMempool events are processed
1322 promise.set_value();
1323 m_node.validation_signals->SyncWithValidationInterfaceQueue();
1324 // AddToWallet events for block_tx and mempool_tx events are counted a
1325 // second time as the notification queue is processed
1326 BOOST_CHECK_EQUAL(addtx_count, 5);
1327
1328
1329 TestUnloadWallet(std::move(wallet));
1330
1331
1332 // Load wallet again, this time creating new block and mempool transactions
1333 // paying to the wallet as the wallet finishes loading and syncing the
1334 // queue so the events have to be handled immediately. Releasing the wallet
1335 // lock during the sync is a little artificial but is needed to avoid a
1336 // deadlock during the sync and simulates a new block notification happening
1337 // as soon as possible.
1338 addtx_count = 0;
1339 auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
1340 BOOST_CHECK(rescan_completed);
1341 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1342 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1343 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1344 mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1346 m_node.validation_signals->SyncWithValidationInterfaceQueue();
1347 });
1349 // Since mempool transactions are requested at the end of loading, there will
1350 // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
1351 BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
1352 {
1353 LOCK(wallet->cs_wallet);
1354 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
1355 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
1356 }
1357
1358
1359 TestUnloadWallet(std::move(wallet));
1360}
1361
1363{
1365 context.args = &m_args;
1368 WaitForDeleteWallet(std::move(wallet));
1369}
1370
1372{
1373 m_args.ForceSetArg("-unsafesqlitesync", "1");
1375 context.args = &m_args;
1376 context.chain = m_node.chain.get();
1378 CKey key = GenerateRandomKey();
1379 AddKey(*wallet, key);
1380
1381 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1382 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
1383 CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
1384
1385 m_node.validation_signals->SyncWithValidationInterfaceQueue();
1386
1387 {
1388 auto block_hash = block_tx.GetHash();
1389 auto prev_tx = m_coinbase_txns[0];
1390
1391 LOCK(wallet->cs_wallet);
1392 BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
1393 BOOST_CHECK(wallet->mapWallet.contains(block_hash));
1394
1395 std::vector<Txid> vHashIn{ block_hash };
1396 BOOST_CHECK(wallet->RemoveTxs(vHashIn));
1397
1398 BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
1399 BOOST_CHECK(!wallet->mapWallet.contains(block_hash));
1400 }
1401
1402 TestUnloadWallet(std::move(wallet));
1403}
1404
1406} // 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
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition: feerate.h:71
An encapsulated private key.
Definition: key.h:46
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
An encapsulated public key.
Definition: pubkey.h:43
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
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:694
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
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
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)
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: common.h:19
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
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:117
virtual bool broadcastTransaction(const CTransactionRef &tx, const CAmount &max_tx_fee, const CFeeRate &max_tx_fee_rate, node::TxBroadcast broadcast_method, std::string &err_string)=0
Process a local transaction, optionally adding it to the mempool and optionally broadcasting it to th...
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:318
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
void FailNextWrite(std::string record_type, size_t match_skip_count=0)
Definition: util.h:79
bool HasRecordType(const std::string &record_type)
Definition: util.h:98
std::optional< SerializeData > GetRecordValue(const std::string &record_type)
Definition: util.h:86
void FailNextErase(std::string record_type)
Definition: util.h:83
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:411
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
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
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:283
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:233
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
const std::string WALLETDESCRIPTORCKEY
Definition: walletdb.cpp:60
const std::string WALLETDESCRIPTORKEY
Definition: walletdb.cpp:61
const std::string MASTER_KEY
Definition: walletdb.cpp:46
constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:151
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
wallet::DescriptorScriptPubKeyMan * CreateDescriptor(CWallet &keystore, const std::string &desc_str, const bool success)
Definition: util.cpp:126
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:1448
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:1241
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
@ PassphraseIncorrect
The passphrase does not decrypt the wallet. Callers may ask the user to enter it again.
@ GenericError
Generic wallet error.
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:2766
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:32
static void AddKey(CWallet &wallet, const CKey &key)
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context)
Definition: util.cpp:76
static bool BroadcastTestSimpleSpend(interfaces::Chain &chain, ChainstateManager &chainman, const CMutableTransaction &tx, std::string &error)
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
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:50
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
unsigned int nBytesPerSigOp
Definition: settings.cpp:10
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:395
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:405
constexpr script_verify_flags STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:118
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:750
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:923
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:1009
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:243
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:1008
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:238
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:143
Testing setup that configures a complete environment.
Definition: setup_common.h:119
Bilingual messages:
Definition: translation.h:24
NodeContext struct containing references to chain state and connection state.
Definition: context.h:57
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:89
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:74
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:78
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
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:149
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)
std::shared_ptr< CWallet > wallet
WalletContext context
FakeNodeClock clock
FaultInjectingDatabase * fail_db