Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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/wallet.h>
6
7#include <array>
8#include <cstddef>
9#include <cstdint>
10#include <future>
11#include <limits>
12#include <memory>
13#include <optional>
14#include <stdexcept>
15#include <string>
16#include <utility>
17#include <vector>
18
19#include <addresstype.h>
20#include <chain.h>
21#include <consensus/tx_verify.h>
23#include <interfaces/chain.h>
24#include <key_io.h>
25#include <node/types.h>
26#include <policy/feerate.h>
27#include <policy/policy.h>
28#include <rpc/server.h>
29#include <script/descriptor.h>
30#include <script/solver.h>
31#include <test/util/common.h>
32#include <test/util/logging.h>
33#include <test/util/random.h>
35#include <test/util/time.h>
36#include <util/check.h>
37#include <util/strencodings.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
51namespace wallet {
52
53// Ensure that fee levels defined in the wallet are at least as high
54// as the default levels for node policy.
55static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
56static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
57
58BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
59
60static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
61{
63 mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
64 mtx.vin.push_back({CTxIn{from.GetHash(), index}});
66 keystore.AddKey(key);
67 std::map<COutPoint, Coin> coins;
68 coins[mtx.vin[0].prevout].out = from.vout[index];
69 std::map<int, bilingual_str> input_errors;
70 BOOST_CHECK(SignTransaction(mtx, &keystore, coins, {.sighash_type = SIGHASH_ALL}, input_errors));
71 return mtx;
72}
73
74static bool BroadcastTestSimpleSpend(interfaces::Chain& chain, ChainstateManager& chainman, const CMutableTransaction& tx, std::string& error)
75{
76 const auto tx_ref{MakeTransactionRef(tx)};
81 // TestSimpleSpend pays a high fee; use a limit just above its feerate.
84}
85
87{
88 const int height{*Assert(m_node.chain->getHeight())};
89 {
90 LOCK(m_wallet.cs_wallet);
91 m_wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
92 m_wallet.SetLastBlockProcessed(height, m_node.chain->getBlockHash(height));
93 }
94
96 ext_key.SetSeed(std::array<std::byte, 32>{});
97 const std::string descriptor_without_checksum{"wpkh(" + EncodeExtKey(ext_key) + "/*)"};
99
100 const std::array invalid_ranges{
101 std::pair{std::pair<int64_t, int64_t>{2, 1}, "Range specified as [begin,end] must not have begin after end"},
102 std::pair{std::pair<int64_t, int64_t>{std::numeric_limits<int64_t>::max(), 0}, "Range specified as [begin,end] must not have begin after end"},
103 std::pair{std::pair<int64_t, int64_t>{-1, 10}, "Range should be greater or equal than 0"},
104 std::pair{std::pair<int64_t, int64_t>{0, 1'000'000}, "Range is too large"},
105 std::pair{std::pair<int64_t, int64_t>{0, std::numeric_limits<int64_t>::max()}, "End of range is too high"},
106 std::pair{std::pair<int64_t, int64_t>{0, 1LL << 31}, "End of range is too high"},
107 };
108
109 for (const auto& [range, expected_error] : invalid_ranges) {
110 std::vector requests{ImportDescriptorRequest{
111 .descriptor = descriptor,
112 .label = {},
113 .timestamp = 0,
114 .active = false,
115 .internal = std::nullopt,
116 .range = range,
117 .next_index = std::nullopt,
118 }};
119 const auto results{ProcessDescriptorsImport(m_wallet, requests)};
120 BOOST_REQUIRE_EQUAL(results.size(), 1U);
121 BOOST_REQUIRE(results.front().error.has_value());
122 BOOST_CHECK(results.front().error->wallet_error.code == WalletErrorCode::InvalidParameter);
123 BOOST_CHECK_EQUAL(results.front().error->wallet_error.message.original, expected_error);
124 BOOST_CHECK(!results.front().error->is_general_error);
125 }
126}
127
128namespace {
129struct EncryptionFailureSetup : TestingSetup {
130 WalletContext context;
131 FaultInjectingDatabase* fail_db{nullptr};
132 std::shared_ptr<CWallet> wallet;
133 FakeNodeClock clock; // Frozen time makes EncryptMasterKey use the default KDF iteration count
134
135 EncryptionFailureSetup()
136 {
137 context.args = &m_args;
138 m_args.ForceSetArg("-keypool", "1"); // Failure injection does not depend on keypool depth
139 context.chain = m_node.chain.get();
141 }
142
143 void RecreateWallet(uint64_t create_flags)
144 {
145 if (wallet) TestUnloadWallet(std::move(wallet));
146 auto database{std::make_unique<FaultInjectingDatabase>()};
147 fail_db = database.get();
148 wallet = TestCreateWallet(std::move(database), context, create_flags);
149 }
150
152};
153} // namespace
154
156{
158
159 fail_db->FailNextWrite(DBKeys::MASTER_KEY); // The injected failure affects only the first attempt
160 for (bool success : {false, true}) {
161 BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
162 BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
163 BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
167 }
168}
169
171{
173
174 fail_db->FailNextCommit(); // The injected failure affects only the first attempt
175 test_only_CheckFailuresAreExceptionsNotAborts mock_checks; // Keep abort regressions observable
176 BOOST_CHECK(!wallet->EncryptWallet("passphrase"));
177 BOOST_CHECK(!wallet->HasEncryptionKeys());
178 BOOST_CHECK(!wallet->HaveCryptedKeys());
182 BOOST_CHECK( wallet->EncryptWallet("passphrase"));
183 BOOST_CHECK( wallet->HasEncryptionKeys());
184 BOOST_CHECK( wallet->HaveCryptedKeys());
188}
189
191{
193
194 fail_db->FailNextWrite(DBKeys::WALLETDESCRIPTORCKEY, /*match_skip_count=*/1); // Only one write fails
195 for (bool success : {false, true}) {
196 BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
197 BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
198 BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
202 }
203}
204
206{
208
209 fail_db->FailNextErase(DBKeys::WALLETDESCRIPTORKEY); // Only one erase fails
210 for (bool success : {false, true}) {
211 BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
212 BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
213 BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
217 }
218}
219
221{
223 BOOST_REQUIRE(wallet->EncryptWallet("old_pass"));
224 BOOST_REQUIRE(wallet->IsLocked());
227
228 fail_db->FailNextWrite(DBKeys::MASTER_KEY); // The injected failure affects only the first attempt
229 const auto changed{wallet->ChangeWalletPassphrase("old_pass", "new_pass")};
232 BOOST_CHECK_EQUAL(changed.error().message.original, "Error: Writing the new encryption key to the wallet database failed");
233 BOOST_CHECK( wallet->IsLocked());
235 BOOST_CHECK( wallet->Unlock("old_pass"));
236 wallet->Lock();
237 BOOST_CHECK(!wallet->Unlock("new_pass"));
238 BOOST_CHECK( wallet->ChangeWalletPassphrase("old_pass", "new_pass"));
239 BOOST_CHECK( wallet->IsLocked());
241 BOOST_CHECK( wallet->Unlock("new_pass"));
242 wallet->Lock();
243 const auto unlocked{wallet->Unlock("old_pass")};
246 BOOST_CHECK_EQUAL(unlocked.error().message.original, "Error: The wallet passphrase entered was incorrect.");
247}
248
260
262{
263 enum class Failure { PlaintextWrite, EncryptedWrite, Erase, Commit };
264 for (auto failure : {Failure::PlaintextWrite, Failure::EncryptedWrite, Failure::Erase, Failure::Commit}) {
265 const bool encrypted{failure != Failure::PlaintextWrite};
267 CKey key{GenerateRandomKey()};
268 // Add a public descriptor first so the private-key update exercises an existing live manager
269 auto* spkm{CreateDescriptor(*wallet, strprintf("combo(%s)", HexStr(key.GetPubKey())), /*success=*/true)};
270 WalletDescriptor descriptor{WITH_LOCK(spkm->cs_desc_man, return spkm->GetWalletDescriptor())};
272 provider.keys.emplace(key.GetPubKey().GetID(), key);
273 auto add_key{[&] {
274 LOCK(wallet->cs_wallet);
275 return wallet->AddWalletDescriptor(descriptor, provider, /*label=*/"", /*internal=*/false);
276 }};
277 auto has_key{[&] {
278 LOCK(wallet->cs_wallet);
279 return wallet->GetKey(key.GetPubKey().GetID()).has_value();
280 }};
281 if (encrypted) {
282 BOOST_REQUIRE(wallet->EncryptWallet("passphrase"));
283 BOOST_REQUIRE(wallet->Unlock("passphrase"));
284 }
286
287 const std::string record_type{encrypted ? DBKeys::WALLETDESCRIPTORCKEY : DBKeys::WALLETDESCRIPTORKEY};
288 if (failure == Failure::Erase) {
290 } else if (failure == Failure::Commit) {
292 } else {
293 fail_db->FailNextWrite(record_type);
294 }
295 BOOST_CHECK_EXCEPTION((void)add_key(), std::runtime_error, HasReason{"UpdateWithSigningProvider: writing descriptor private key failed"});
297 BOOST_CHECK(!fail_db->HasRecordType(record_type));
300 BOOST_CHECK( fail_db->HasRecordType(record_type));
301 }
302}
303
305{
307 {
308 LOCK(wallet.cs_wallet);
309 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
310 auto key{GenerateRandomKey()};
311 auto desc_str{"combo(" + EncodeSecret(key) + ")"};
313 std::string error;
314 auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
315 auto& desc{descs.at(0)};
316 WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
317 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
318 // Wallet should update the non-range descriptor successfully
319 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
320 }
321}
322
323
324// This test verifies that wallet settings can be added and removed
325// concurrently, ensuring no race conditions occur during either process.
327{
328 auto chain = m_node.chain.get();
329 const auto NUM_WALLETS{5};
330
331 // Since we're counting the number of wallets, ensure we start without any.
332 BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
333
334 const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
335 std::vector<std::thread> threads;
336 threads.reserve(NUM_WALLETS);
337 for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
338 for (auto& t : threads) t.join();
339
340 auto wallets = chain->getRwSetting("wallet");
342 };
343
344 // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
345 check_concurrent_wallet([&chain](int i) {
346 Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
347 },
348 /*num_expected_wallets=*/NUM_WALLETS);
349
350 // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
351 check_concurrent_wallet([&chain](int i) {
352 Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
353 },
354 /*num_expected_wallets=*/0);
355}
356
358{
360 TxState state = TxStateInactive{};
361 tx.nLockTime = lockTime;
363 CBlockIndex* block = nullptr;
364 if (blockTime > 0) {
365 LOCK(cs_main);
366 auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
367 assert(inserted.second);
368 const uint256& hash = inserted.first->first;
369 block = &inserted.first->second;
370 block->nTime = blockTime;
371 block->phashBlock = &hash;
372 state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
373 }
374 return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
375 // Assign wtx.m_state to simplify test and avoid the need to simulate
376 // reorg events. Without this, AddToWallet asserts false when the same
377 // transaction is confirmed in different blocks.
378 wtx.m_state = state;
379 return true;
380 })->nTimeSmart;
381}
382
383// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
384// expanded to cover more corner cases of smart time logic.
385BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
386{
387 // New transaction should use clock time if lower than block time.
388 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100s, 120), 100);
389
390 // Test that updating existing transaction does not change smart time.
391 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200s, 220), 100);
392
393 // New transaction should use clock time if there's no block time.
394 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300s, 0), 300);
395
396 // New transaction should use block time if lower than clock time.
397 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420s, 400), 400);
398
399 // New transaction should use latest entry time if higher than
400 // min(block time, clock time).
401 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500s, 390), 400);
402
403 // If there are future entries, new transaction should use time of the
404 // newest entry that is no more than 300 seconds ahead of the clock time.
405 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50s, 600), 300);
406}
407
408void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
409{
411 auto chain{interfaces::MakeChain(node)};
412 DatabaseOptions options;
413 options.require_format = format;
414 DatabaseStatus status;
415 bilingual_str error;
416 std::vector<bilingual_str> warnings;
417 auto database{MakeWalletDatabase(name, options, status, error)};
418 auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
419 BOOST_CHECK_EQUAL(wallet->PopulateWalletFromDB(error, warnings), DBErrors::LOAD_OK);
420 WITH_LOCK(wallet->cs_wallet, f(wallet));
421}
422
424{
425 for (DatabaseFormat format : DATABASE_FORMATS) {
426 const std::string name{strprintf("receive-requests-%i", format)};
427 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
428 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
429 WalletBatch batch{wallet->GetDatabase()};
430 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
431 BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
432 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
433 BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
434 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
435 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
436 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
437 });
438 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
439 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
440 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
441 auto requests = wallet->GetAddressReceiveRequests();
442 auto erequests = {"val_rr11", "val_rr20"};
443 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
444 RunWithinTxn(wallet->GetDatabase(), /*process_desc=*/"test", [](WalletBatch& batch){
445 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
446 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
447 return true;
448 });
449 });
450 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
451 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
452 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
453 auto requests = wallet->GetAddressReceiveRequests();
454 auto erequests = {"val_rr11"};
455 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
456 });
457 }
458}
459
461{
462public:
464 {
465 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
466 wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
467 }
468
470 {
471 wallet.reset();
472 }
473
475 {
477 CCoinControl dummy;
478 {
479 auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
481 tx = res->tx;
482 }
483 wallet->CommitTransaction(tx);
485 {
486 LOCK(wallet->cs_wallet);
487 blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).GetTx());
488 }
489 CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
490
491 LOCK(wallet->cs_wallet);
492 LOCK(Assert(m_node.chainman)->GetMutex());
493 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
494 auto it = wallet->mapWallet.find(tx->GetHash());
495 BOOST_CHECK(it != wallet->mapWallet.end());
496 it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
497 return it->second;
498 }
499
500 std::unique_ptr<CWallet> wallet;
501};
502
504{
505 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
506
507 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
508 // address.
509 std::map<CTxDestination, std::vector<COutput>> list;
510 {
511 LOCK(wallet->cs_wallet);
512 list = ListCoins(*wallet);
513 }
514 BOOST_CHECK_EQUAL(list.size(), 1U);
515 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
516 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
517
518 // Check initial balance from one mature coinbase transaction.
519 BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
520
521 // Add a transaction creating a change address, and confirm ListCoins still
522 // returns the coin associated with the change address underneath the
523 // coinbaseKey pubkey, even though the change address has a different
524 // pubkey.
525 AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
526 {
527 LOCK(wallet->cs_wallet);
528 list = ListCoins(*wallet);
529 }
530 BOOST_CHECK_EQUAL(list.size(), 1U);
531 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
532 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
533
534 // Lock both coins. Confirm number of available coins drops to 0.
535 {
536 LOCK(wallet->cs_wallet);
537 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 2U);
538 }
539 for (const auto& group : list) {
540 for (const auto& coin : group.second) {
541 LOCK(wallet->cs_wallet);
542 wallet->LockCoin(coin.outpoint, /*persist=*/false);
543 }
544 }
545 {
546 LOCK(wallet->cs_wallet);
547 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 0U);
548 }
549 // Confirm ListCoins still returns same result as before, despite coins
550 // being locked.
551 {
552 LOCK(wallet->cs_wallet);
553 list = ListCoins(*wallet);
554 }
555 BOOST_CHECK_EQUAL(list.size(), 1U);
556 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
557 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
558}
559
561 std::map<OutputType, size_t>& expected_coins_sizes)
562{
563 LOCK(context.wallet->cs_wallet);
564 util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
565 CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
566 CoinFilterParams filter;
567 filter.skip_locked = false;
568 CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
569 // Lock outputs so they are not spent in follow-up transactions
570 for (uint32_t i = 0; i < wtx.GetTx()->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i}, /*persist=*/false);
571 for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
572}
573
575{
576 std::map<OutputType, size_t> expected_coins_sizes;
577 for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
578
579 // Verify our wallet has one usable coinbase UTXO before starting
580 // This UTXO is a P2PK, so it should show up in the Other bucket
585
586 // We will create a self transfer for each of the OutputTypes and
587 // verify it is put in the correct bucket after running GetAvailablecoins
588 //
589 // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
590 // 1. One UTXO as the recipient
591 // 2. One UTXO from the change, due to payment address matching logic
592
593 for (const auto& out_type : OUTPUT_TYPES) {
594 if (out_type == OutputType::UNKNOWN) continue;
597 }
598}
599
601{
602 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
603 LOCK(wallet->cs_wallet);
604 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
606 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
607}
608
609// Explicit calculation which is used to test the wallet constant
610// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
612{
613 // Generate ephemeral valid pubkey
614 CKey key = GenerateRandomKey();
615 CPubKey pubkey = key.GetPubKey();
616
617 // Generate pubkey hash
618 uint160 key_hash(Hash160(pubkey));
619
620 // Create inner-script to enter into keystore. Key hash can't be 0...
622
623 // Create outer P2SH script for the output
626
627 // Add inner-script to key store and key to watchonly
629 BOOST_CHECK(keystore.AddCScript(inner_script));
630 keystore.AddKeyPubKey(key, pubkey);
631
632 // Fill in dummy signatures for fee calculation.
634
636 // We're hand-feeding it correct arguments; shouldn't happen
637 assert(false);
638 }
639
640 CTxIn tx_in;
643}
644
650
651bool malformed_descriptor(std::ios_base::failure e)
652{
653 std::string s(e.what());
654 return s.find("Missing checksum") != std::string::npos;
655}
656
658{
659 std::vector<unsigned char> malformed_record;
661 vw << std::string("notadescriptor");
662 vw << uint64_t{0};
663 vw << int32_t{0};
664 vw << int32_t{0};
665 vw << int32_t{1};
666
668 std::optional<WalletDescriptor> w_desc;
669 BOOST_CHECK_EXCEPTION(w_desc.emplace(WalletDescriptor::FromStream(deserialize, vr)), std::ios_base::failure, malformed_descriptor);
670}
671
691{
692 m_args.ForceSetArg("-unsafesqlitesync", "1");
693 // Create new wallet with known key and unload it.
695 context.args = &m_args;
696 context.chain = m_node.chain.get();
698 CKey key = GenerateRandomKey();
699 AddKey(*wallet, key);
700 TestUnloadWallet(std::move(wallet));
701
702
703 // Add log hook to detect AddToWallet events from rescans, blockConnected,
704 // and transactionAddedToMempool notifications
705 int addtx_count = 0;
706 DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
707 if (s) ++addtx_count;
708 return false;
709 });
710
711
712 bool rescan_completed = false;
713 DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
714 if (s) rescan_completed = true;
715 return false;
716 });
717
718
719 // Block the queue to prevent the wallet receiving blockConnected and
720 // transactionAddedToMempool notifications, and create block and mempool
721 // transactions paying to the wallet
722 std::promise<void> promise;
723 m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
724 promise.get_future().wait();
725 });
726 std::string error;
727 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), /*sync=*/false).vtx[0]);
728 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
729 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), /*sync=*/false).vtx[0]);
730 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
732
733 // Reload wallet and make sure new transactions are detected despite events
734 // being blocked
735 // Loading will also ask for current mempool transactions
738 // AddToWallet events for block_tx and mempool_tx (x2)
740 {
741 LOCK(wallet->cs_wallet);
742 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
743 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
744 }
745
746
747 // Unblock notification queue and make sure stale blockConnected and
748 // transactionAddedToMempool events are processed
749 promise.set_value();
750 m_node.validation_signals->SyncWithValidationInterfaceQueue();
751 // AddToWallet events for block_tx and mempool_tx events are counted a
752 // second time as the notification queue is processed
754
755
756 TestUnloadWallet(std::move(wallet));
757
758
759 // Load wallet again, this time creating new block and mempool transactions
760 // paying to the wallet as the wallet finishes loading and syncing the
761 // queue so the events have to be handled immediately. Releasing the wallet
762 // lock during the sync is a little artificial but is needed to avoid a
763 // deadlock during the sync and simulates a new block notification happening
764 // as soon as possible.
765 addtx_count = 0;
766 auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
768 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
769 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
770 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
771 mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
773 m_node.validation_signals->SyncWithValidationInterfaceQueue();
774 });
776 // Since mempool transactions are requested at the end of loading, there will
777 // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
779 {
780 LOCK(wallet->cs_wallet);
781 BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
782 BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
783 }
784
785
786 TestUnloadWallet(std::move(wallet));
787}
788
797
799{
800 m_args.ForceSetArg("-unsafesqlitesync", "1");
802 context.args = &m_args;
803 context.chain = m_node.chain.get();
805 CKey key = GenerateRandomKey();
806 AddKey(*wallet, key);
807
808 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
809 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
810 CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
811
812 m_node.validation_signals->SyncWithValidationInterfaceQueue();
813
814 {
815 auto block_hash = block_tx.GetHash();
816 auto prev_tx = m_coinbase_txns[0];
817
818 LOCK(wallet->cs_wallet);
819 BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
820 BOOST_CHECK(wallet->mapWallet.contains(block_hash));
821
822 std::vector<Txid> vHashIn{ block_hash };
823 BOOST_CHECK(wallet->RemoveTxs(vHashIn));
824
825 BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
826 BOOST_CHECK(!wallet->mapWallet.contains(block_hash));
827 }
828
829 TestUnloadWallet(std::move(wallet));
830}
831
833} // 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
BOOST_FIXTURE_TEST_CASE(util_CheckValue, CheckValueTest)
static void AddTx(const CTransactionRef &tx, const CAmount &fee, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
node::NodeContext m_node
#define Assert(val)
Identity function.
Definition check.h:119
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
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition chain.h:106
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.
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(
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 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
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.
const Txid & GetHash() const LIFETIMEBOUND
CTransactionRef GetTx() const
void FailNextWrite(std::string record_type, size_t match_skip_count=0)
Definition util.h:81
bool HasRecordType(const std::string &record_type)
Definition util.h:100
std::optional< SerializeData > GetRecordValue(const std::string &record_type)
Definition util.h:88
void FailNextErase(std::string record_type)
Definition util.h:85
CWalletTx & AddTx(CRecipient recipient)
std::unique_ptr< CWallet > wallet
Access to the wallet database.
Definition walletdb.h:199
Descriptor with some wallet metadata.
Definition walletutil.h:86
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_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.
@ MEMPOOL_NO_BROADCAST
Add the transaction to the mempool, but don't broadcast to anybody.
const std::string WALLETDESCRIPTORCKEY
Definition walletdb.cpp:62
const std::string WALLETDESCRIPTORKEY
Definition walletdb.cpp:63
const std::string MASTER_KEY
Definition walletdb.cpp:48
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:131
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase()
Definition util.cpp:126
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)
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:230
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:103
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:2777
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
void AddKey(CWallet &wallet, const CKey &key)
Definition util.cpp:45
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context)
Definition util.cpp:81
static bool BroadcastTestSimpleSpend(interfaces::Chain &chain, ChainstateManager &chainman, const CMutableTransaction &tx, std::string &error)
std::shared_ptr< CWallet > TestCreateWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context, uint64_t create_flags)
Definition util.cpp:57
bool malformed_descriptor(std::ios_base::failure e)
constexpr CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition wallet.h:113
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)
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_EQUAL(v1, v2)
Definition object.cpp:17
#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:112
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)
std::shared_ptr< const CTransaction > CTransactionRef
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
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 key.h:238
void SetSeed(std::span< const std::byte > seed)
Definition key.cpp:381
A mutable version of CTransaction.
std::vector< CTxOut > vout
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Testing setup that configures a complete environment.
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
std::optional< DatabaseFormat > require_format
Definition db.h:171
Information about a descriptor to be imported.
Definition imports.h:49
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
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
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
BOOST_CHECK_EQUAL_COLLECTIONS(R1L.begin(), R1L.end(), R1Array, R1Array+uint256::size())
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())
std::shared_ptr< CWallet > m_wallet
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)
WalletContext context
FakeNodeClock clock
FaultInjectingDatabase * fail_db