Bitcoin Core 30.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/wallet.h>
6
7#include <cstdint>
8#include <future>
9#include <memory>
10#include <vector>
11
12#include <addresstype.h>
13#include <interfaces/chain.h>
14#include <key_io.h>
15#include <node/blockstorage.h>
16#include <node/types.h>
17#include <policy/policy.h>
18#include <rpc/server.h>
19#include <script/solver.h>
20#include <test/util/logging.h>
21#include <test/util/random.h>
23#include <util/translation.h>
24#include <validation.h>
25#include <validationinterface.h>
26#include <wallet/coincontrol.h>
27#include <wallet/context.h>
28#include <wallet/receive.h>
29#include <wallet/spend.h>
30#include <wallet/test/util.h>
32
33#include <boost/test/unit_test.hpp>
34#include <univalue.h>
35
37
38namespace wallet {
39
40// Ensure that fee levels defined in the wallet are at least as high
41// as the default levels for node policy.
42static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
43static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
44
45BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
46
47static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
48{
50 mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
51 mtx.vin.push_back({CTxIn{from.GetHash(), index}});
53 keystore.AddKey(key);
54 std::map<COutPoint, Coin> coins;
55 coins[mtx.vin[0].prevout].out = from.vout[index];
56 std::map<int, bilingual_str> input_errors;
57 BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
58 return mtx;
59}
60
61static void AddKey(CWallet& wallet, const CKey& key)
62{
63 LOCK(wallet.cs_wallet);
64 FlatSigningProvider provider;
65 std::string error;
66 auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
67 assert(descs.size() == 1);
68 auto& desc = descs.at(0);
69 WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
70 Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
71}
72
73BOOST_FIXTURE_TEST_CASE(update_non_range_descriptor, TestingSetup)
74{
76 {
77 LOCK(wallet.cs_wallet);
78 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
79 auto key{GenerateRandomKey()};
80 auto desc_str{"combo(" + EncodeSecret(key) + ")"};
81 FlatSigningProvider provider;
82 std::string error;
83 auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
84 auto& desc{descs.at(0)};
85 WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
86 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
87 // Wallet should update the non-range descriptor successfully
88 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
89 }
90}
91
92BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
93{
94 // Cap last block file size, and mine new block in a new block file.
95 CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
96 WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
97 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
98 CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
99
100 // Verify ScanForWalletTransactions fails to read an unknown start block.
101 {
103 {
104 LOCK(wallet.cs_wallet);
105 LOCK(Assert(m_node.chainman)->GetMutex());
106 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
107 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
108 }
109 AddKey(wallet, coinbaseKey);
111 reserver.reserve();
112 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
117 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
118 }
119
120 // Verify ScanForWalletTransactions picks up transactions in both the old
121 // and new block files.
122 {
124 {
125 LOCK(wallet.cs_wallet);
126 LOCK(Assert(m_node.chainman)->GetMutex());
127 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
128 wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
129 }
130 AddKey(wallet, coinbaseKey);
132 std::chrono::steady_clock::time_point fake_time;
133 reserver.setNow([&] { fake_time += 60s; return fake_time; });
134 reserver.reserve();
135
136 {
137 CBlockLocator locator;
138 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
139 BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
140 }
141
142 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true);
145 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
146 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
147 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
148
149 {
150 CBlockLocator locator;
151 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
152 BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
153 }
154 }
155
156 // Prune the older block file.
157 int file_number;
158 {
159 LOCK(cs_main);
160 file_number = oldTip->GetBlockPos().nFile;
161 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
162 }
163 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
164
165 // Verify ScanForWalletTransactions only picks transactions in the new block
166 // file.
167 {
169 {
170 LOCK(wallet.cs_wallet);
171 LOCK(Assert(m_node.chainman)->GetMutex());
172 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
173 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
174 }
175 AddKey(wallet, coinbaseKey);
177 reserver.reserve();
178 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
181 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
182 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
183 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
184 }
185
186 // Prune the remaining block file.
187 {
188 LOCK(cs_main);
189 file_number = newTip->GetBlockPos().nFile;
190 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
191 }
192 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
193
194 // Verify ScanForWalletTransactions scans no blocks.
195 {
197 {
198 LOCK(wallet.cs_wallet);
199 LOCK(Assert(m_node.chainman)->GetMutex());
200 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
201 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
202 }
203 AddKey(wallet, coinbaseKey);
205 reserver.reserve();
206 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
208 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
211 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
212 }
213}
214
215// This test verifies that wallet settings can be added and removed
216// concurrently, ensuring no race conditions occur during either process.
217BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
218{
219 auto chain = m_node.chain.get();
220 const auto NUM_WALLETS{5};
221
222 // Since we're counting the number of wallets, ensure we start without any.
223 BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
224
225 const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
226 std::vector<std::thread> threads;
227 threads.reserve(NUM_WALLETS);
228 for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
229 for (auto& t : threads) t.join();
230
231 auto wallets = chain->getRwSetting("wallet");
232 BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
233 };
234
235 // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
236 check_concurrent_wallet([&chain](int i) {
237 Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
238 },
239 /*num_expected_wallets=*/NUM_WALLETS);
240
241 // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
242 check_concurrent_wallet([&chain](int i) {
243 Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
244 },
245 /*num_expected_wallets=*/0);
246}
247
248static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
249{
251 TxState state = TxStateInactive{};
252 tx.nLockTime = lockTime;
253 SetMockTime(mockTime);
254 CBlockIndex* block = nullptr;
255 if (blockTime > 0) {
256 LOCK(cs_main);
257 auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
258 assert(inserted.second);
259 const uint256& hash = inserted.first->first;
260 block = &inserted.first->second;
261 block->nTime = blockTime;
262 block->phashBlock = &hash;
263 state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
264 }
265 return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
266 // Assign wtx.m_state to simplify test and avoid the need to simulate
267 // reorg events. Without this, AddToWallet asserts false when the same
268 // transaction is confirmed in different blocks.
269 wtx.m_state = state;
270 return true;
271 })->nTimeSmart;
272}
273
274// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
275// expanded to cover more corner cases of smart time logic.
276BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
277{
278 // New transaction should use clock time if lower than block time.
279 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
280
281 // Test that updating existing transaction does not change smart time.
282 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
283
284 // New transaction should use clock time if there's no block time.
285 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
286
287 // New transaction should use block time if lower than clock time.
288 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
289
290 // New transaction should use latest entry time if higher than
291 // min(block time, clock time).
292 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
293
294 // If there are future entries, new transaction should use time of the
295 // newest entry that is no more than 300 seconds ahead of the clock time.
296 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
297}
298
299void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
300{
302 auto chain{interfaces::MakeChain(node)};
303 DatabaseOptions options;
304 options.require_format = format;
305 DatabaseStatus status;
306 bilingual_str error;
307 std::vector<bilingual_str> warnings;
308 auto database{MakeWalletDatabase(name, options, status, error)};
309 auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
311 WITH_LOCK(wallet->cs_wallet, f(wallet));
312}
313
315{
317 const std::string name{strprintf("receive-requests-%i", format)};
318 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
319 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
320 WalletBatch batch{wallet->GetDatabase()};
321 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
322 BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
323 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
324 BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
325 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
326 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
327 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
328 });
329 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
330 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
331 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
332 auto requests = wallet->GetAddressReceiveRequests();
333 auto erequests = {"val_rr11", "val_rr20"};
334 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
335 RunWithinTxn(wallet->GetDatabase(), /*process_desc*/"test", [](WalletBatch& batch){
336 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
337 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
338 return true;
339 });
340 });
341 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
342 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
343 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
344 auto requests = wallet->GetAddressReceiveRequests();
345 auto erequests = {"val_rr11"};
346 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
347 });
348 }
349}
350
352{
353public:
355 {
356 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
357 wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
358 }
359
361 {
362 wallet.reset();
363 }
364
366 {
368 CCoinControl dummy;
369 {
370 auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
371 BOOST_CHECK(res);
372 tx = res->tx;
373 }
374 wallet->CommitTransaction(tx, {}, {});
375 CMutableTransaction blocktx;
376 {
377 LOCK(wallet->cs_wallet);
378 blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
379 }
380 CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
381
382 LOCK(wallet->cs_wallet);
383 LOCK(Assert(m_node.chainman)->GetMutex());
384 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
385 auto it = wallet->mapWallet.find(tx->GetHash());
386 BOOST_CHECK(it != wallet->mapWallet.end());
387 it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
388 return it->second;
389 }
390
391 std::unique_ptr<CWallet> wallet;
392};
393
395{
396 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
397
398 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
399 // address.
400 std::map<CTxDestination, std::vector<COutput>> list;
401 {
402 LOCK(wallet->cs_wallet);
403 list = ListCoins(*wallet);
404 }
405 BOOST_CHECK_EQUAL(list.size(), 1U);
406 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
407 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
408
409 // Check initial balance from one mature coinbase transaction.
410 BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
411
412 // Add a transaction creating a change address, and confirm ListCoins still
413 // returns the coin associated with the change address underneath the
414 // coinbaseKey pubkey, even though the change address has a different
415 // pubkey.
416 AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
417 {
418 LOCK(wallet->cs_wallet);
419 list = ListCoins(*wallet);
420 }
421 BOOST_CHECK_EQUAL(list.size(), 1U);
422 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
423 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
424
425 // Lock both coins. Confirm number of available coins drops to 0.
426 {
427 LOCK(wallet->cs_wallet);
428 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 2U);
429 }
430 for (const auto& group : list) {
431 for (const auto& coin : group.second) {
432 LOCK(wallet->cs_wallet);
433 wallet->LockCoin(coin.outpoint, /*persist=*/false);
434 }
435 }
436 {
437 LOCK(wallet->cs_wallet);
438 BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 0U);
439 }
440 // Confirm ListCoins still returns same result as before, despite coins
441 // being locked.
442 {
443 LOCK(wallet->cs_wallet);
444 list = ListCoins(*wallet);
445 }
446 BOOST_CHECK_EQUAL(list.size(), 1U);
447 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
448 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
449}
450
451void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
452 std::map<OutputType, size_t>& expected_coins_sizes)
453{
454 LOCK(context.wallet->cs_wallet);
455 util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
456 CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
457 CoinFilterParams filter;
458 filter.skip_locked = false;
459 CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
460 // Lock outputs so they are not spent in follow-up transactions
461 for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i}, /*persist=*/false);
462 for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
463}
464
465BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
466{
467 std::map<OutputType, size_t> expected_coins_sizes;
468 for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
469
470 // Verify our wallet has one usable coinbase UTXO before starting
471 // This UTXO is a P2PK, so it should show up in the Other bucket
472 expected_coins_sizes[OutputType::UNKNOWN] = 1U;
473 CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
474 BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
475 BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
476
477 // We will create a self transfer for each of the OutputTypes and
478 // verify it is put in the correct bucket after running GetAvailablecoins
479 //
480 // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
481 // 1. One UTXO as the recipient
482 // 2. One UTXO from the change, due to payment address matching logic
483
484 for (const auto& out_type : OUTPUT_TYPES) {
485 if (out_type == OutputType::UNKNOWN) continue;
486 expected_coins_sizes[out_type] = 2U;
487 TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
488 }
489}
490
492{
493 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
494 LOCK(wallet->cs_wallet);
495 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
497 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
498}
499
500// Explicit calculation which is used to test the wallet constant
501// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
502static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
503{
504 // Generate ephemeral valid pubkey
505 CKey key = GenerateRandomKey();
506 CPubKey pubkey = key.GetPubKey();
507
508 // Generate pubkey hash
509 uint160 key_hash(Hash160(pubkey));
510
511 // Create inner-script to enter into keystore. Key hash can't be 0...
512 CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
513
514 // Create outer P2SH script for the output
515 uint160 script_id(Hash160(inner_script));
516 CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
517
518 // Add inner-script to key store and key to watchonly
520 keystore.AddCScript(inner_script);
521 keystore.AddKeyPubKey(key, pubkey);
522
523 // Fill in dummy signatures for fee calculation.
524 SignatureData sig_data;
525
526 if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
527 // We're hand-feeding it correct arguments; shouldn't happen
528 assert(false);
529 }
530
531 CTxIn tx_in;
532 UpdateInput(tx_in, sig_data);
533 return (size_t)GetVirtualTransactionInputSize(tx_in);
534}
535
537{
540}
541
542bool malformed_descriptor(std::ios_base::failure e)
543{
544 std::string s(e.what());
545 return s.find("Missing checksum") != std::string::npos;
546}
547
549{
550 std::vector<unsigned char> malformed_record;
551 VectorWriter vw{malformed_record, 0};
552 vw << std::string("notadescriptor");
553 vw << uint64_t{0};
554 vw << int32_t{0};
555 vw << int32_t{0};
556 vw << int32_t{1};
557
558 SpanReader vr{malformed_record};
559 WalletDescriptor w_desc;
560 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
561}
562
582{
583 m_args.ForceSetArg("-unsafesqlitesync", "1");
584 // Create new wallet with known key and unload it.
585 WalletContext context;
586 context.args = &m_args;
587 context.chain = m_node.chain.get();
588 auto wallet = TestLoadWallet(context);
589 CKey key = GenerateRandomKey();
590 AddKey(*wallet, key);
591 TestUnloadWallet(std::move(wallet));
592
593
594 // Add log hook to detect AddToWallet events from rescans, blockConnected,
595 // and transactionAddedToMempool notifications
596 int addtx_count = 0;
597 DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
598 if (s) ++addtx_count;
599 return false;
600 });
601
602
603 bool rescan_completed = false;
604 DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
605 if (s) rescan_completed = true;
606 return false;
607 });
608
609
610 // Block the queue to prevent the wallet receiving blockConnected and
611 // transactionAddedToMempool notifications, and create block and mempool
612 // transactions paying to the wallet
613 std::promise<void> promise;
614 m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
615 promise.get_future().wait();
616 });
617 std::string error;
618 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
619 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
620 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
621 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
623
624
625 // Reload wallet and make sure new transactions are detected despite events
626 // being blocked
627 // Loading will also ask for current mempool transactions
628 wallet = TestLoadWallet(context);
629 BOOST_CHECK(rescan_completed);
630 // AddToWallet events for block_tx and mempool_tx (x2)
631 BOOST_CHECK_EQUAL(addtx_count, 3);
632 {
633 LOCK(wallet->cs_wallet);
634 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
635 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
636 }
637
638
639 // Unblock notification queue and make sure stale blockConnected and
640 // transactionAddedToMempool events are processed
641 promise.set_value();
642 m_node.validation_signals->SyncWithValidationInterfaceQueue();
643 // AddToWallet events for block_tx and mempool_tx events are counted a
644 // second time as the notification queue is processed
645 BOOST_CHECK_EQUAL(addtx_count, 5);
646
647
648 TestUnloadWallet(std::move(wallet));
649
650
651 // Load wallet again, this time creating new block and mempool transactions
652 // paying to the wallet as the wallet finishes loading and syncing the
653 // queue so the events have to be handled immediately. Releasing the wallet
654 // lock during the sync is a little artificial but is needed to avoid a
655 // deadlock during the sync and simulates a new block notification happening
656 // as soon as possible.
657 addtx_count = 0;
658 auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
659 BOOST_CHECK(rescan_completed);
660 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
661 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
662 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
663 mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
665 m_node.validation_signals->SyncWithValidationInterfaceQueue();
666 });
667 wallet = TestLoadWallet(context);
668 // Since mempool transactions are requested at the end of loading, there will
669 // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
670 BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
671 {
672 LOCK(wallet->cs_wallet);
673 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
674 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
675 }
676
677
678 TestUnloadWallet(std::move(wallet));
679}
680
682{
683 WalletContext context;
684 context.args = &m_args;
685 auto wallet = TestLoadWallet(context);
687 WaitForDeleteWallet(std::move(wallet));
688}
689
691{
692 m_args.ForceSetArg("-unsafesqlitesync", "1");
693 WalletContext context;
694 context.args = &m_args;
695 context.chain = m_node.chain.get();
696 auto wallet = TestLoadWallet(context);
697 CKey key = GenerateRandomKey();
698 AddKey(*wallet, key);
699
700 std::string error;
701 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
702 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
703 CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
704
705 m_node.validation_signals->SyncWithValidationInterfaceQueue();
706
707 {
708 auto block_hash = block_tx.GetHash();
709 auto prev_tx = m_coinbase_txns[0];
710
711 LOCK(wallet->cs_wallet);
712 BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
713 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
714
715 std::vector<Txid> vHashIn{ block_hash };
716 BOOST_CHECK(wallet->RemoveTxs(vHashIn));
717
718 BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
719 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
720 }
721
722 TestUnloadWallet(std::move(wallet));
723}
724
726} // namespace wallet
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
node::NodeContext m_node
Definition: bitcoin-gui.cpp:43
#define Assert(val)
Identity function.
Definition: check.h:113
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:103
uint32_t nTime
Definition: chain.h:151
uint256 GetBlockHash() const
Definition: chain.h:207
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:115
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:172
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:106
An encapsulated private key.
Definition: key.h:36
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:183
An encapsulated public key.
Definition: pubkey.h:34
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
An input of a transaction.
Definition: transaction.h:67
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:899
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1140
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
virtual bool AddCScript(const CScript &redeemScript)
virtual bool AddKey(const CKey &key)
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:83
constexpr bool IsNull() const
Definition: uint256.h:48
constexpr unsigned char * end()
Definition: uint256.h:102
constexpr unsigned char * begin()
Definition: uint256.h:101
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
Coin Control Features.
Definition: coincontrol.h:83
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:312
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:195
CTransactionRef tx
Definition: transaction.h:269
CWalletTx & AddTx(CRecipient recipient)
std::unique_ptr< CWallet > wallet
Access to the wallet database.
Definition: walletdb.h:193
Descriptor with some wallet metadata.
Definition: walletutil.h:64
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1076
void setNow(NowFn now)
Definition: wallet.h:1106
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1086
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:393
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:92
@ SIGHASH_ALL
Definition: interpreter.h:31
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:475
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:231
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:990
Definition: messages.h:21
@ MEMPOOL_NO_BROADCAST
Add the transaction to the mempool, but don't broadcast to anybody.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:117
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
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:145
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:245
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:1411
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:139
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Definition: walletdb.cpp:1209
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:79
BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context, uint64_t create_flags)
Definition: util.cpp:50
DatabaseFormat
Definition: db.h:167
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:95
static const DatabaseFormat DATABASE_FORMATS[]
Definition: util.h:27
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:108
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:215
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
Definition: util.cpp:20
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:112
void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
Definition: util.cpp:73
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:2843
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
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:549
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:186
BOOST_AUTO_TEST_CASE(bnb_test)
static void AddKey(CWallet &wallet, const CKey &key)
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:126
bool malformed_descriptor(std::ios_base::failure e)
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:376
void TestCoinsResult(ListCoinsTest &context, OutputType out_type, CAmount amount, std::map< OutputType, size_t > &expected_coins_sizes)
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:30
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
Definition: wallet.cpp:253
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
DatabaseStatus
Definition: db.h:186
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:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
OutputType
Definition: outputtype.h:18
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:26
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:391
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
Definition: policy.h:45
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: policy.h:67
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
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:1108
const char * name
Definition: rest.cpp:48
@ OP_EQUAL
Definition: script.h:146
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:731
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:904
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:990
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:989
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:213
Basic testing setup.
Definition: setup_common.h:64
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:124
std::vector< uint256 > vHave
Definition: block.h:134
bool IsNull() const
Definition: block.h:152
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
int32_t nFile
Definition: flatfile.h:16
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:146
Testing setup that configures a complete environment.
Definition: setup_common.h:121
Bilingual messages:
Definition: translation.h:24
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:88
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:76
std::optional< int > last_scanned_height
Definition: wallet.h:644
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:643
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:650
enum wallet::CWallet::ScanResult::@18 status
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:175
State of transaction confirmed in a block.
Definition: transaction.h:32
State of transaction not confirmed or conflicting with a known block and not in the mempool.
Definition: transaction.h:59
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:259
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:290
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:40
assert(!tx.IsCoinBase())
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:533
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)